Conditions | 2 |
Total Lines | 80 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
21 | public static function castUsing(array $arguments) |
||
22 | { |
||
23 | $encoder = isset($arguments[0]) ? $arguments[0] : null; |
||
24 | return new class($encoder) implements CastsAttributes { |
||
|
|||
25 | |||
26 | protected $encoder = 'json'; |
||
27 | |||
28 | /** |
||
29 | * constructor. |
||
30 | * @param $encoder |
||
31 | */ |
||
32 | public function __construct($encoder) |
||
33 | { |
||
34 | $this->encoder = $encoder; |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * @inheritDoc |
||
39 | */ |
||
40 | public function get($model, $key, $value, $attributes): Metadata |
||
41 | { |
||
42 | if (empty($value)) { |
||
43 | $value = []; |
||
44 | } else { |
||
45 | $value = $this->decode($value); |
||
46 | } |
||
47 | if (!is_array($value)) { |
||
48 | $value = []; |
||
49 | } |
||
50 | return (new Metadata($value))->setObserver( |
||
51 | function (Metadata $metadata) use ($model, $key) { |
||
52 | $model->set($key, $metadata); |
||
53 | } |
||
54 | ); |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * @inheritDoc |
||
59 | */ |
||
60 | public function set($model, $key, $value, $attributes) |
||
61 | { |
||
62 | if (is_string($value)) { |
||
63 | return [$key => $value]; |
||
64 | } |
||
65 | if ($value instanceof Metadata) { |
||
66 | $value = $this->encode($value); |
||
67 | } |
||
68 | return [$key => $value]; |
||
69 | } |
||
70 | |||
71 | /** |
||
72 | * @inheritDoc |
||
73 | */ |
||
74 | public function serialize($model, string $key, $value, array $attributes) |
||
75 | { |
||
76 | return $value->getArrayCopy(); |
||
77 | } |
||
78 | |||
79 | /** |
||
80 | * @param $value |
||
81 | * @return false|string |
||
82 | */ |
||
83 | protected function encode($value) |
||
84 | { |
||
85 | if ($this->encoder == 'serialize') { |
||
86 | return $value instanceof Metadata ? $value->serialize() : serialize($value); |
||
87 | } |
||
88 | return json_encode($value); |
||
89 | } |
||
90 | |||
91 | /** |
||
92 | * @param $value |
||
93 | * @return mixed |
||
94 | */ |
||
95 | protected function decode($value) |
||
96 | { |
||
97 | if ($this->encoder == 'serialize') { |
||
98 | return unserialize($value); |
||
99 | } |
||
100 | return Json::decode($value, true); |
||
101 | } |
||
105 |
In the issue above, the returned value is violating the contract defined by the mentioned interface.
Let's take a look at an example: