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 |
||
| 18 | class CryptTest extends TestCase |
||
| 19 | { |
||
| 20 | /** |
||
| 21 | * @test |
||
| 22 | */ |
||
| 23 | public function should_encode_and_decode_data() |
||
| 24 | { |
||
| 25 | |||
| 26 | $data = [ |
||
| 27 | 'custom' => 'data', |
||
| 28 | 'collection' => [ |
||
| 29 | 'a' => 'b', |
||
| 30 | 'c' => 'd', |
||
| 31 | ], |
||
| 32 | 'float' => 5.669 |
||
| 33 | ]; |
||
| 34 | |||
| 35 | $hash = data_encrypt($data, 'test'); |
||
| 36 | |||
| 37 | $this->assertTrue(\is_string($hash)); |
||
| 38 | |||
| 39 | $this->assertSame($data, data_decrypt($hash, 'test')); |
||
| 40 | |||
| 41 | $this->assertArrayHasKey('collection', $data); |
||
| 42 | } |
||
| 43 | |||
| 44 | /** |
||
| 45 | * @test |
||
| 46 | * |
||
| 47 | * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException |
||
| 48 | * @throws \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException |
||
| 49 | */ |
||
| 50 | public function should_fail_to_decode_data_with_wrong_key() |
||
| 51 | { |
||
| 52 | $this->expectException(WrongKeyOrModifiedCiphertextException::class); |
||
| 53 | |||
| 54 | $data = "test data"; |
||
| 55 | |||
| 56 | $hash = data_encrypt($data, 'testkey'); |
||
| 57 | |||
| 58 | data_decrypt($hash, 'mykey'); |
||
| 59 | } |
||
| 60 | |||
| 61 | /** |
||
| 62 | * @test |
||
| 63 | * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException |
||
| 64 | * @throws WrongKeyOrModifiedCiphertextException |
||
| 65 | */ |
||
| 66 | public function should_fail_to_decode_data_with_modified_cypher_text() |
||
| 67 | { |
||
| 68 | $this->expectException(WrongKeyOrModifiedCiphertextException::class); |
||
| 69 | $data = "test data"; |
||
| 70 | |||
| 71 | $hash = data_encrypt($data, 'testkey') . 'HgtQQQ'; |
||
| 72 | |||
| 73 | data_decrypt($hash, 'testkey'); |
||
| 74 | } |
||
| 75 | } |
||
| 76 |