Complex classes like CryptTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use CryptTrait, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
11 | trait CryptTrait |
||
12 | { |
||
13 | protected $cipher; |
||
14 | protected $key; |
||
15 | |||
16 | /** |
||
17 | * Set the key and cipher used by the crypt. |
||
18 | * |
||
19 | * @param string $key |
||
20 | * @param string $cipher |
||
21 | * |
||
22 | * @return self |
||
23 | */ |
||
24 | public function crypt($key, $cipher = 'AES-128-CBC') |
||
37 | |||
38 | /** |
||
39 | * Generates the default cipher and key. |
||
40 | */ |
||
41 | protected function generateCryptKey() |
||
45 | |||
46 | /** |
||
47 | * Encrypt the given value. |
||
48 | * |
||
49 | * @param string $value |
||
50 | * |
||
51 | * @return string |
||
52 | */ |
||
53 | protected function encrypt($value) |
||
67 | |||
68 | /** |
||
69 | * Decrypt the given value. |
||
70 | * |
||
71 | * @param string $payload |
||
72 | * |
||
73 | * @return string |
||
74 | */ |
||
75 | protected function decrypt($payload) |
||
96 | |||
97 | /** |
||
98 | * Create a MAC for the given value. |
||
99 | * |
||
100 | * @param string $iv |
||
101 | * @param string $value |
||
102 | * |
||
103 | * @return string |
||
104 | */ |
||
105 | protected function hash($iv, $value) |
||
109 | |||
110 | /** |
||
111 | * Verify that the encryption payload is valid. |
||
112 | * |
||
113 | * @param array|mixed $data |
||
114 | * |
||
115 | * @return bool |
||
116 | */ |
||
117 | protected function invalidPayload($data) |
||
121 | |||
122 | /** |
||
123 | * Determine if the MAC for the given payload is valid. |
||
124 | * |
||
125 | * @param array $payload |
||
126 | * |
||
127 | * @throws \RuntimeException |
||
128 | * |
||
129 | * @return bool |
||
130 | */ |
||
131 | protected function validMac(array $payload) |
||
138 | } |
||
139 |
This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.
If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.
In this case you can add the
@ignore
PhpDoc annotation to the duplicate definition and it will be ignored.