BodyMatchers
1 year ago
CoreTestCase.php
1 year ago
HeadersMatcher.php
1 year ago
StatusCodeMatcher.php
1 year ago
TestParam.php
1 year ago
HeadersMatcher.php
68 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Core\TestCase; |
| 6 | |
| 7 | use PHPUnit\Framework\TestCase; |
| 8 | |
| 9 | class HeadersMatcher |
| 10 | { |
| 11 | private $headers = []; |
| 12 | private $allowExtra = false; |
| 13 | private $testCase; |
| 14 | public function __construct(TestCase $testCase) |
| 15 | { |
| 16 | $this->testCase = $testCase; |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * Set an array of arrays, where inner arrays must be of length 2, |
| 21 | * i.e. index0 => headerValue, index1 => checkValueBool |
| 22 | * |
| 23 | * @param array<string,array> $headers |
| 24 | */ |
| 25 | public function setHeaders(array $headers): void |
| 26 | { |
| 27 | $this->headers = $headers; |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * Sets allowExtra flag to true. |
| 32 | */ |
| 33 | public function allowExtra(): void |
| 34 | { |
| 35 | $this->allowExtra = true; |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Asserts if provided headers match according to the properties set within object. |
| 40 | */ |
| 41 | public function assert(array $headers) |
| 42 | { |
| 43 | if (empty($this->headers)) { |
| 44 | return; |
| 45 | } |
| 46 | |
| 47 | // Http headers are case-insensitive |
| 48 | $expected = array_change_key_case($this->headers); |
| 49 | $actual = array_change_key_case($headers); |
| 50 | $message = "Headers do not match"; |
| 51 | if (!$this->allowExtra) { |
| 52 | $message = "$message strictly"; |
| 53 | $this->testCase->assertCount(count($expected), $actual, $message); |
| 54 | } |
| 55 | |
| 56 | $actualKeys = array_keys($actual); |
| 57 | array_walk($expected, function ($valueArray, $key) use ($actual, $actualKeys, $message): void { |
| 58 | $this->testCase->assertTrue(in_array($key, $actualKeys, true), $message); |
| 59 | if (!is_bool($valueArray[1])) { |
| 60 | return; |
| 61 | } |
| 62 | if ($valueArray[1]) { |
| 63 | $this->testCase->assertEquals($valueArray[0], $actual[$key], $message); |
| 64 | } |
| 65 | }); |
| 66 | } |
| 67 | } |
| 68 |