1 <?php
2
3 namespace Docoflow\Traits;
4
5 /**
6 * You can attach a static macro method to this class. Means, you can extend the class on the fly.
7 *
8 * @author Krisan Alfa Timur <krisanalfa@docotel.co.id>
9 */
10 trait HasMutator
11 {
12 /**
13 * Stored mutator
14 *
15 * @var array
16 */
17 protected static $mutator = [];
18
19 /**
20 * Static implementation of this class.
21 *
22 * @var \Docoflow\Models\WorkflowVerificator
23 */
24 protected static $instance;
25
26 /**
27 * This method is invoked after each record is instantiated by a find method. Here, we can bind static instance for mutator.
28 *
29 * @return void
30 */
31 protected function afterFind()
32 {
33 parent::afterFind();
34
35 static::$instance = $this;
36 }
37
38 /**
39 * Statically get instance, useful to get instance from mutator
40 *
41 * @return \Docoflow\Models\WorkflowVerificator
42 */
43 public static function getInstance()
44 {
45 return static::$instance;
46 }
47
48 /**
49 * Determine if mutator is exist
50 *
51 * @param string $mutator Mutator name
52 *
53 * @return boolean
54 */
55 public static function hasMutator($mutator)
56 {
57 return isset(static::$mutator[$mutator]);
58 }
59
60 /**
61 * Register new mutator
62 *
63 * @param string $mutator Mutator name
64 * @param callable $callback Mutator callback
65 *
66 * @return void
67 */
68 public static function mutate($mutator, callable $callback)
69 {
70 static::$mutator[$mutator] = $callback;
71 }
72
73 /**
74 * Call mutator statically
75 *
76 * @param string $method Mutator name
77 * @param array $parameters Parameters bind to your mutator
78 *
79 * @return mixed
80 */
81 public static function callMutator($method, array $parameters = array())
82 {
83 if (static::$mutator[$method] instanceof Closure) {
84 return call_user_func_array(Closure::bind(static::$mutator[$method], null, get_called_class()), $parameters);
85 } else {
86 return call_user_func_array(static::$mutator[$method], $parameters);
87 }
88 }
89 }
90