diff --git a/src/Framework/Assert.php b/src/Framework/Assert.php index 682b6920..59b2aed5 100644 --- a/src/Framework/Assert.php +++ b/src/Framework/Assert.php @@ -141,6 +141,38 @@ public static function notContains($needle, $actual, string $description = null) } + /** + * Asserts that a haystack (string or array) has an expected key. + */ + public static function hasKey($key, $actual, string $description = null): void + { + self::$counter++; + if (is_array($actual)) { + if (!array_key_exists($key, $actual)) { + self::fail(self::describe('%1 should contain key %2', $description), $actual, $key); + } + } else { + self::fail(self::describe('%1 should be array', $description), $actual); + } + } + + + /** + * Asserts that a haystack (string or array) doesnt have an expected key. + */ + public static function hasNotKey($key, $actual, string $description = null): void + { + self::$counter++; + if (is_array($actual)) { + if (array_key_exists($key, $actual)) { + self::fail(self::describe('%1 should not contain key %2', $description), $actual, $key); + } + } else { + self::fail(self::describe('%1 should be array', $description), $actual); + } + } + + /** * Asserts that a value is true. * @param mixed $actual diff --git a/tests/Framework/Assert.hasKey.phpt b/tests/Framework/Assert.hasKey.phpt new file mode 100644 index 00000000..a73d45e2 --- /dev/null +++ b/tests/Framework/Assert.hasKey.phpt @@ -0,0 +1,55 @@ + 1, + 'one' => 'one', +]; + +$string= 'Lorem ipsum'; + +Assert::hasKey(1, $array); +Assert::hasKey('one', $array); + +Assert::hasNotKey(2, $array); +Assert::hasNotKey('two', $array); + +Assert::exception(function () use ($array) { + Assert::hasKey(2, $array); +}, Tester\AssertException::class, '%a% should contain key %a%'); + +Assert::exception(function () use ($array) { + Assert::hasKey('two', $array); +}, Tester\AssertException::class, '%a% should contain key %a%'); + +Assert::exception(function () use ($string) { + Assert::hasKey('two', $string); +}, Tester\AssertException::class, '%a% should be array'); + + +Assert::exception(function () use ($array) { + Assert::hasNotKey(1, $array); +}, Tester\AssertException::class, '%a% should not contain key %a%'); + +Assert::exception(function () use ($array) { + Assert::hasNotKey('one', $array); +}, Tester\AssertException::class, '%a% should not contain key %a%'); + + +Assert::exception(function () use ($string) { + Assert::hasNotKey('two', $string); +}, Tester\AssertException::class, '%a% should be array'); + +Assert::exception(function () use ($array) { + Assert::hasKey('two', $array, 'Custom description'); +}, Tester\AssertException::class, "Custom description: [1 => 1, 'one' => 'one'] should contain key 'two'"); + +Assert::exception(function () use ($array) { + Assert::hasNotKey('one', $array, 'Custom description'); +}, Tester\AssertException::class, "Custom description: [1 => 1, 'one' => 'one'] should not contain key 'one'");