From ad0f6b9708387e4bc689e945e02974c9002f2f40 Mon Sep 17 00:00:00 2001 From: Victor Bjelkholm Date: Mon, 14 Jul 2014 12:43:00 +0200 Subject: [PATCH] Add instanceOf validation --- src/Valitron/Validator.php | 25 +++++++++++++++++++++++-- tests/Valitron/ValidateTest.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/src/Valitron/Validator.php b/src/Valitron/Validator.php index 1e3bc3c..13bff59 100644 --- a/src/Valitron/Validator.php +++ b/src/Valitron/Validator.php @@ -667,6 +667,25 @@ class Validator return false; } + protected function validateInstanceOf($field, $value, $params) + { + $isInstanceOf = false; + if(is_object($value)) { + if(is_object($params[0]) && $value instanceof $params[0]) { + $isInstanceOf = true; + } + if(get_class($value) === $params[0]) { + $isInstanceOf = true; + } + } + if(is_string($value)) { + if(is_string($params[0]) && get_class($value) === $params[0]) { + $isInstanceOf = true; + } + } + return $isInstanceOf; + } + /** * Get array of fields and data @@ -713,8 +732,10 @@ class Validator $param = $param->format('Y-m-d'); } // Use custom label instead of field name if set - if (isset($this->_labels[$param])) { - $param = $this->_labels[$param]; + if(is_string($params[0])) { + if (isset($this->_labels[$param])) { + $param = $this->_labels[$param]; + } } $values[] = $param; } diff --git a/tests/Valitron/ValidateTest.php b/tests/Valitron/ValidateTest.php index a05bd7d..b38097b 100644 --- a/tests/Valitron/ValidateTest.php +++ b/tests/Valitron/ValidateTest.php @@ -800,6 +800,35 @@ class ValidateTest extends BaseTestCase } } } + + public function testInstanceOfValidWithString() + { + $v = new Validator(['attributeName' => new stdClass()]); + $v->rule('instanceOf', 'attributeName', 'stdClass'); + $this->assertTrue($v->validate()); + } + + public function testInstanceOfInvalidWithInstance() + { + $v = new Validator(['attributeName' => new stdClass()]); + $v->rule('instanceOf', 'attributeName', new Validator([])); + $this->assertFalse($v->validate()); + } + + public function testInstanceOfValidWithInstance() + { + $v = new Validator(['attributeName' => new stdClass()]); + $v->rule('instanceOf', 'attributeName', new stdClass()); + $this->assertTrue($v->validate()); + } + + public function testInstanceOfInvalidWithString() + { + $v = new Validator(['attributeName' => new stdClass()]); + $v->rule('instanceOf', 'attributeName', 'SomeOtherClass'); + $this->assertFalse($v->validate()); + } + } function sampleFunctionCallback($field, $value, array $params) {