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 |
||
| 16 | class SandboxStrategyTest extends TestCase |
||
| 17 | { |
||
| 18 | |||
| 19 | /** |
||
| 20 | * @test |
||
| 21 | */ |
||
| 22 | public function should_make_a_post_to_the_sandbox_auth_endpoint() |
||
| 23 | { |
||
| 24 | |||
| 25 | $client_id = 'sample_client_id'; |
||
| 26 | $secret_key = 'sample_secret_key'; |
||
| 27 | $username = 'sample_username'; |
||
| 28 | $password = 'sample_password'; |
||
| 29 | $token = 'a_sample_token123456789'; |
||
| 30 | |||
| 31 | $fakeResponseContent = [ |
||
| 32 | "access_token" => $token, |
||
| 33 | |||
| 34 | ]; |
||
| 35 | |||
| 36 | $headerAuth = base64_encode( |
||
| 37 | sprintf( |
||
| 38 | '%s:%s', |
||
| 39 | $client_id, |
||
| 40 | $secret_key |
||
| 41 | ) |
||
| 42 | ); |
||
| 43 | |||
| 44 | $cache = $this->prophesize(Cache::class); |
||
| 45 | |||
| 46 | $cache->contains(Argument::any())->willReturn(false)->shouldBeCalled(); |
||
| 47 | $cache->save(Argument::any(), $token, Argument::type('integer'))->shouldBeCalled(); |
||
| 48 | |||
| 49 | $dummyStream = $this->prophesize(Stream::class); |
||
| 50 | $dummyStream->getContents()->willReturn(json_encode($fakeResponseContent)); |
||
| 51 | $dummyStream->rewind()->shouldBeCalled(); |
||
| 52 | |||
| 53 | $dummyResponse = $this->prophesize(Response::class); |
||
| 54 | $dummyResponse->getBody()->willReturn($dummyStream->reveal()); |
||
| 55 | |||
| 56 | |||
| 57 | $client = $this->prophesize(ClientInterface::class); |
||
| 58 | |||
| 59 | $client |
||
| 60 | ->request('POST', SandboxStrategy::BASE_URL, [ |
||
| 61 | 'headers' => |
||
| 62 | [ |
||
| 63 | 'Authorization' => 'Basic ' . $headerAuth |
||
| 64 | ], |
||
| 65 | 'form_params' => |
||
| 66 | [ |
||
| 67 | 'grant_type' => 'password', |
||
| 68 | 'username' => $username, |
||
| 69 | 'password' => $password, |
||
| 70 | ] |
||
| 71 | ] |
||
| 72 | ) |
||
| 73 | ->willReturn($dummyResponse->reveal()); |
||
| 74 | |||
| 75 | $auth = new SandboxStrategy($client->reveal(), $cache->reveal()); |
||
| 76 | $auth->authenticate($client_id, $secret_key, $username, $password, true); |
||
| 77 | |||
| 78 | |||
| 79 | } |
||
| 80 | |||
| 81 | } |
||
| 82 |