Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
8 | class ItemDecorator extends BaseItemDecorator |
||
9 | { |
||
10 | /** @var resource */ |
||
11 | private $publicKey; |
||
12 | /** @var resource */ |
||
13 | private $privateKey; |
||
14 | |||
15 | 192 | public function __construct( |
|
26 | |||
27 | 183 | public function __destruct() |
|
32 | |||
33 | 129 | protected function isDecryptable() |
|
43 | |||
44 | 129 | protected function encrypt($data) |
|
45 | { |
||
46 | 129 | $key = $this->generateIv(); |
|
47 | 129 | $iv = $this->generateIv(); |
|
48 | 129 | $cipherText = $this->encryptString(serialize($data), $key, $iv); |
|
49 | |||
50 | 129 | return new EncryptedValue( |
|
51 | $cipherText, |
||
52 | 129 | $this->getCipherMethod(), |
|
53 | $iv, |
||
54 | 129 | $this->encryptEnvelopeKey($key), |
|
55 | 129 | $this->signString($this->getKey() . $cipherText) |
|
56 | ); |
||
57 | } |
||
58 | |||
59 | 66 | View Code Duplication | protected function decrypt($data) |
|
|||
60 | { |
||
61 | 66 | if (!$data instanceof EncryptedValue) return null; |
|
62 | |||
63 | 66 | return unserialize($this->decryptString( |
|
64 | 66 | $data->getCipherText(), |
|
65 | 66 | $data->getMethod(), |
|
66 | 66 | $this->decryptEnvelopeKey($data->getEnvelopeKey()), |
|
67 | 66 | $data->getInitializationVector() |
|
68 | )); |
||
69 | } |
||
70 | |||
71 | 192 | private function setPublicKey($cert) |
|
72 | { |
||
73 | 192 | $publicKey = @openssl_pkey_get_public($cert); |
|
74 | 192 | if (!$this->validateOpenSslKey($publicKey)) { |
|
75 | 6 | throw new InvalidArgumentException('Unable to create public key' |
|
76 | . ' from provided certificate. Certificate must be a valid x509' |
||
77 | . ' certificate, a PEM encoded certificate, or a path to a file' |
||
78 | 6 | . ' containing a PEM encoded certificate.'); |
|
79 | } |
||
80 | |||
81 | 186 | $this->publicKey = $publicKey; |
|
82 | 186 | } |
|
83 | |||
84 | 186 | private function setPrivateKey($key, $passPhrase) |
|
93 | |||
94 | 192 | private function validateOpenSslKey($key) |
|
98 | |||
99 | 129 | private function signString($string) |
|
105 | |||
106 | 93 | private function validateSignature($signed, $signature) |
|
110 | |||
111 | 129 | private function encryptEnvelopeKey($key) |
|
117 | |||
118 | 66 | private function decryptEnvelopeKey($sealedKey) |
|
124 | } |
||
125 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.