Created
January 10, 2018 14:39
-
-
Save Jan0707/55e5465fb43dea909f7835ac487cd381 to your computer and use it in GitHub Desktop.
Asserter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include_once 'vendor/autoload.php'; | |
class Dummy | |
{ | |
private $foo = 'bar'; | |
private $bars = ['foo_One', 'fooKey' => 'fooValue']; | |
} | |
Class Asserter { | |
public function contains($test, $expected, $strict = false) | |
{ | |
if ($strict) { | |
throw new \Exception('Strict mode is not supported yet.'); | |
} | |
if (is_object($test)) { | |
return $this->objectContains($test, $expected, $strict); | |
} elseif (is_array($test)) { | |
return $this->arrayContains($test, $expected, $strict); | |
} else { | |
return $test === $expected; | |
} | |
} | |
protected function objectContains($testObject, $expectedArray, $strict = false) | |
{ | |
if (!is_array($expectedArray)) { | |
return false; | |
} | |
$reflection = new ReflectionObject($testObject); | |
foreach ($expectedArray as $expectedProperty => $expectedValue) { | |
$property = $reflection->getProperty($expectedProperty); | |
$property->setAccessible(true); | |
$value = $property->getValue($testObject); | |
$equal = $this->contains($value, $expectedValue); | |
if (!$equal) { | |
return false; | |
} | |
} | |
return true; | |
} | |
protected function arrayContains(array $testArray, $expectedArray, $strict = false) | |
{ | |
if (!is_array($expectedArray)) { | |
return false; | |
} | |
foreach ($expectedArray as $expectedKey => $expectedValue) { | |
if (array_key_exists($expectedKey, $testArray)) { | |
$value = $testArray[$expectedKey]; | |
$equal = $this->contains($value, $expectedValue); | |
if (!$equal) { | |
return false; | |
} | |
} else { | |
return false; | |
} | |
} | |
return true; | |
} | |
} | |
$asserter = new Asserter(); | |
$instance = new Dummy(); | |
var_dump('Should be true:'); | |
var_dump($asserter->contains($instance, [ | |
'foo' => 'bar', | |
'bars' => ['foo_One', 'fooKey' => 'fooValue'], | |
])); | |
var_dump('Should be false:'); | |
var_dump($asserter->contains($instance, [ | |
'foo' => 'bar', | |
'bars' => ['foo_One', 'fooKey' => 'fooValue2'], | |
])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment