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 |
||
| 7 | class BadSslTest extends TestCase |
||
| 8 | { |
||
| 9 | public function testWithMiddleware() |
||
| 10 | { |
||
| 11 | $stack = HandlerStack::create(); |
||
| 12 | |||
| 13 | // Enable HSTS middleware |
||
| 14 | $stack->push(HstsMiddleware::handler()); |
||
| 15 | |||
| 16 | $client = new Client(['handler' => $stack]); |
||
| 17 | |||
| 18 | // Make first request to https to mark host as HSTS host |
||
| 19 | $client->request('GET', 'https://hsts.badssl.com/'); |
||
| 20 | |||
| 21 | // Make second request to http to test rewrite |
||
| 22 | $response = $client->request('GET', 'http://hsts.badssl.com/'); |
||
| 23 | |||
| 24 | $body = $response->getBody()->getContents(); |
||
| 25 | |||
| 26 | // Request was over https |
||
| 27 | $this->assertFalse(strpos($body, 'favicon-red')); |
||
| 28 | $this->assertNotFalse(strpos($body, 'favicon-green')); |
||
| 29 | } |
||
| 30 | |||
| 31 | public function testWithoutMiddleware() |
||
| 32 | { |
||
| 33 | $client = new Client(); |
||
| 34 | |||
| 35 | // Make first request to https |
||
| 36 | $client->request('GET', 'https://hsts.badssl.com/'); |
||
| 37 | |||
| 38 | // Make second request to http |
||
| 39 | $response = $client->request('GET', 'http://hsts.badssl.com/'); |
||
| 40 | |||
| 41 | $body = $response->getBody()->getContents(); |
||
| 42 | |||
| 43 | // Request was over http |
||
| 44 | $this->assertNotFalse(strpos($body, 'favicon-red')); |
||
| 45 | $this->assertFalse(strpos($body, 'favicon-green')); |
||
| 46 | } |
||
| 47 | |||
| 48 | public function testWithMiddlewareOverHttp() |
||
| 49 | { |
||
| 50 | $stack = HandlerStack::create(); |
||
| 51 | |||
| 52 | // Enable HSTS middleware |
||
| 53 | $stack->push(HstsMiddleware::handler()); |
||
| 54 | |||
| 55 | $client = new Client(['handler' => $stack]); |
||
| 56 | |||
| 57 | // Make first request to http |
||
| 58 | $client->request('GET', 'http://hsts.badssl.com/'); |
||
| 59 | |||
| 60 | // Make second request to http |
||
| 61 | $response = $client->request('GET', 'http://hsts.badssl.com/'); |
||
| 62 | |||
| 63 | $body = $response->getBody()->getContents(); |
||
| 64 | |||
| 65 | // Request was over http |
||
| 66 | $this->assertNotFalse(strpos($body, 'favicon-red')); |
||
| 67 | $this->assertFalse(strpos($body, 'favicon-green')); |
||
| 68 | } |
||
| 69 | } |
||
| 70 |