From e8708fad831622b55ac28e3680356e4202b167d6 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 22 Apr 2015 21:17:56 +0300 Subject: [PATCH 001/112] Fixed issue: "Illegal offset type in isset or empty" --- src/RuleFactory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/RuleFactory.php b/src/RuleFactory.php index 34fa31d..53573a5 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -158,7 +158,7 @@ protected function constructValidatorByNameAndOptions($name, $options) 'arguments' => $options ) ); - } else { + } elseif (is_string($name)) { $name = trim($name); // use the validator map if (isset($this->validatorsMap[ strtolower($name) ])) { From f7308fd7249442594145e80b55a8f8ccb8d16ebd Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Sun, 17 May 2015 10:11:18 +0300 Subject: [PATCH 002/112] Changelog and readme updates --- CHANGELOG.md | 4 +++- docs/couscous.yml | 2 +- readme.md | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40416ca..749fbfc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,9 @@ #### 2.0.0 -- added the `data_key:label` feature +- added the `data_selector:label` feature - implemented default rule messages in the `RuleFactory` class. This way, if you have a custom error message for the `required` fields, you don't have to provide it to all the required fields, just set it up once in the `RuleFactory` +- implemented a way to allow validation rule options to be passed as CSV (eg: '100,200' instead of 'min=200&max=200') + #### 1.2.4 diff --git a/docs/couscous.yml b/docs/couscous.yml index 3055226..049ec4e 100644 --- a/docs/couscous.yml +++ b/docs/couscous.yml @@ -12,7 +12,7 @@ exclude: # Base URL of the published website (no "/" at the end!) # You are advised to set and use this variable to write your links in the HTML layouts -baseUrl: http://www.sirius.ro/php/validation +baseUrl: http://www.sirius.ro/php/sirius/validation projectName: Sirius\Validation title: Sirius\Validation diff --git a/readme.md b/readme.md index 5dabd7c..1a20132 100755 --- a/readme.md +++ b/readme.md @@ -61,7 +61,7 @@ $validator->add('shipping_address[city]:City', 'MyApp\Validator\City'); // uses ##Links -- [documentation](http://www.sirius.ro/php/sirius/validation) +- [documentation](http://www.sirius.ro/php/sirius/validation/) - [changelog](CHANGELOG.md) ##Known issues From 5b55bc8a72c5ec1a976f425ccc708a879301a1e5 Mon Sep 17 00:00:00 2001 From: kenjis Date: Fri, 19 Jun 2015 17:27:26 +0900 Subject: [PATCH 003/112] Fix typos --- docs/validation_rules.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/validation_rules.md b/docs/validation_rules.md index bb0eaeb..eb548a6 100644 --- a/docs/validation_rules.md +++ b/docs/validation_rules.md @@ -22,9 +22,9 @@ title: Built-in validation rules ### Array validators 1. `ArrayLength`: values which are arrays must contain a specific number of items. Rule options: `min` and `max` 2. `ArrayMinlength`: array must contain at least a specific number of items: Rule options: `min` -3. `ArrayMinlength`: array must contain at most a specific number of items: Rule options: `max` -4. `InList: the value must be in a list of acceptable values. Rule options: `list` -5. `NotInList: the value must not be in a list of forbidden values: Rule options: `list` +3. `ArrayMaxlength`: array must contain at most a specific number of items: Rule options: `max` +4. `InList`: the value must be in a list of acceptable values. Rule options: `list` +5. `NotInList`: the value must not be in a list of forbidden values: Rule options: `list` ### Number validators 7. `Between`: value must be a number between 2 limits: Rule options: `min` and `max` @@ -67,4 +67,4 @@ Upload validators work only uploaded files (each file is an upload-like array) a 5. `Upload\ImageHeight`. Checks if the uploaded image's height is between certain limits. Rule options: `min` (default: 0) and `max` (default: 1 million) 6. `Upload\Size`. Checks if the uploaded file' size is bellow a certain limit. Rule options: `size` which can be a number or a string like '10K', '0.5M' or '1.3G` (default: 2M) -*Note!* The upload validators use only the `tmp_name` and `name` values to perform the validation \ No newline at end of file +*Note!* The upload validators use only the `tmp_name` and `name` values to perform the validation From 36b27d08ac8b193bad17623a67a8fbecfbffe810 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Thu, 25 Jun 2015 09:46:03 +0300 Subject: [PATCH 004/112] Fixed bug with default label (issue #28) --- src/Validator.php | 9 +++++---- src/ValueValidator.php | 4 ++-- tests/src/ValidatorTest.php | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/Validator.php b/src/Validator.php index edba6c3..bc4a798 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -214,7 +214,7 @@ public function add($selector, $name = null, $options = null, $messageTemplate = list($selector, $label) = explode(':', $selector, 2); } - $this->ensureSelectorRulesExist($selector); + $this->ensureSelectorRulesExist($selector, $label); call_user_func(array($this->rules[$selector], 'add'), $name, $options, $messageTemplate, $label); return $this; @@ -393,12 +393,13 @@ public function getRules() } /** - * @param $selector + * @param string $selector + * @param string $label */ - protected function ensureSelectorRulesExist($selector) + protected function ensureSelectorRulesExist($selector, $label = null) { if (!isset($this->rules[$selector])) { - $this->rules[$selector] = new ValueValidator($this->getRuleFactory(), $this->getErroMessagePrototype()); + $this->rules[$selector] = new ValueValidator($this->getRuleFactory(), $this->getErroMessagePrototype(), $label); } } diff --git a/src/ValueValidator.php b/src/ValueValidator.php index 3f0cdc7..fd0c29d 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -98,7 +98,7 @@ public function add($name, $options = null, $messageTemplate = null, $label = nu if (is_string($name)) { // rule was supplied like 'required | email' if (strpos($name, ' | ') !== false) { - return $this->add(explode(' | ', $name)); + return $this->addMultiple(explode(' | ', $name)); } // rule was supplied like this 'length(2,10)(error message template)(label)' if (strpos($name, '(') !== false) { @@ -107,7 +107,7 @@ public function add($name, $options = null, $messageTemplate = null, $label = nu } // check for the default label - if (!$label and $this->label) { + if (!$label && $this->label) { $label = $this->label; } diff --git a/tests/src/ValidatorTest.php b/tests/src/ValidatorTest.php index 0de9540..e5e1f60 100755 --- a/tests/src/ValidatorTest.php +++ b/tests/src/ValidatorTest.php @@ -136,6 +136,24 @@ function testAddingMultipleRulesAtOnce() $this->assertEquals(array('This field is required'), $this->validator->getMessages('itemb')); } + function testAddingValidationRulesViaStringsWithoutLabelArg() + { + $this->validator + // mixed rules in 1 string + ->add('item:Item', 'required | minLength({"min":4})') + // validator options as a QUERY string + ->add('itema:Item', 'minLength', 'min=8') + // validator without options and custom message + ->add('itemb:Item B', 'required') + // validator with defaults + ->add('itemc', 'email'); + $this->validator->validate(array('item' => 'ab', 'itema' => 'abc', 'itemc' => 'abc')); + $this->assertEquals(array('Item should have at least 4 characters'), array((string)$this->validator->getMessages('item')[0])); + $this->assertEquals(array('Item should have at least 8 characters'), $this->validator->getMessages('itema')); + $this->assertEquals(array('Item B is required'), $this->validator->getMessages('itemb')); + $this->assertEquals(array('This input must be a valid email address'), $this->validator->getMessages('itemc')); + } + function testAddingValidationRulesViaStrings() { $this->validator From 9f44fc3530f6e22bdbf323802c6d9cac9cf5ef3d Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Thu, 25 Jun 2015 09:50:26 +0300 Subject: [PATCH 005/112] Updated the documentation (issue #27) --- docs/validation_rules.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/validation_rules.md b/docs/validation_rules.md index bb0eaeb..a4d9fb8 100644 --- a/docs/validation_rules.md +++ b/docs/validation_rules.md @@ -27,9 +27,11 @@ title: Built-in validation rules 5. `NotInList: the value must not be in a list of forbidden values: Rule options: `list` ### Number validators -7. `Between`: value must be a number between 2 limits: Rule options: `min` and `max` -8. `LessThan`: value must be less than a number. Rule options: `max` and `inclusive` (to determine if the comparator is < or <=, defaults to TRUE) -9. `GreaterThan`: value must be greater than a number. Rule options: `min` and `inclusive` (to determine if the comparator is > or >=, defaults to TRUE) +1. `Number`: value must be a valid number +2. `Integer`: value must be a valid integer +3. `LessThan`: value must be less than a number. Rule options: `max` and `inclusive` (to determine if the comparator is < or <=, defaults to TRUE) +4. `GreaterThan`: value must be greater than a number. Rule options: `min` and `inclusive` (to determine if the comparator is > or >=, defaults to TRUE) +5. `Between`: value must be a number between 2 limits: Rule options: `min` and `max`. The same as `GreaterThan` and `LessThan`, both inclusive. ### Email/URLs validators 1. `Email`: value must be an email address. Uses a regular expression for validation From 463a2da1ee9ad27b18e961b65f5913aeea8e0e9b Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Thu, 25 Jun 2015 09:57:04 +0300 Subject: [PATCH 006/112] Added a missing method (issue #26) --- src/RuleFactory.php | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/RuleFactory.php b/src/RuleFactory.php index 75e569c..13fc732 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -15,15 +15,27 @@ class RuleFactory */ protected $validatorsMap = array(); + /** + * @var array + */ protected $errorMessages = array(); + /** + * @var array + */ protected $labeledErrorMessages = array(); + /** + * Constructor + */ function __construct() { $this->registerDefaultRules(); } + /** + * Set up the default rules that come with the library + */ protected function registerDefaultRules() { $rulesClasses = array( @@ -139,6 +151,25 @@ public function createRule($name, $options = null, $messageTemplate = null, $lab return $validator; } + /** + * Set default error message for a rule + * + * @param string $rule + * @param string|null $messageWithoutLabel + * @param string|null $messageWithLabel + * + * @return $this + */ + public function setMessages($rule, $messageWithoutLabel = null, $messageWithLabel = null) { + if ($messageWithoutLabel) { + $this->errorMessages[$rule] = $messageWithoutLabel; + } + if ($messageWithLabel) { + $this->labeledErrorMessages[$rule] = $messageWithLabel; + } + return $this; + } + /** * Get the error message saved in the registry for a rule, where the message * is with or without a the label From 90a79e77dac94831e69594dc664a88804b4eabbb Mon Sep 17 00:00:00 2001 From: kenjis Date: Fri, 26 Jun 2015 13:10:07 +0900 Subject: [PATCH 007/112] Fix markdown Ordered list output is broken now. --- docs/validation_rules.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/validation_rules.md b/docs/validation_rules.md index 4f15d75..609b0ca 100644 --- a/docs/validation_rules.md +++ b/docs/validation_rules.md @@ -53,6 +53,7 @@ title: Built-in validation rules ### File validators File validators work only with local files and they fail if the file does not exist + 1. `File\Extension`. Checks if the file has a certain extension. Rule options: `allowed` which can be an array or a comma separated string. 2. `File\Image`. Checks if the file is an image of a certain type. Rule options: `allowed` which can be an array or a comma separated string (default: `jpg,png,gif`) 3. `File\ImageRatio`. Checks if the image has a certain ratio. Rule options: `ratio` which can be a number or a string like `4:3`, `error_margin` - how much the file's ratio can deviate from the target (default: 0) @@ -62,6 +63,7 @@ File validators work only with local files and they fail if the file does not ex ### Upload validators Upload validators work only uploaded files (each file is an upload-like array) and they fail if the temporary file does not exist. + 1. `Upload\Extension`. Checks if the uploaded file has a certain extension. Rule options: `allowed` which can be an array or a comma separated string. 2. `Upload\Image`. Checks if the uploaded file is an image of a certain type. Rule options: `allowed` which can be an array or a comma separated string (default: `jpg,png,gif`) 3. `Upload\ImageRatio`. Checks if the uploaded image has a certain ratio. Rule options: `ratio` which can be a number or a string like `4:3`, `error_margin` - how much the file's ratio can deviate from the target (default: 0) From 4c06b24679f3b77ed6d3a5703fb909c5b9dbdca5 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 26 Jun 2015 09:21:10 +0300 Subject: [PATCH 008/112] Where available, use mb_strlen for validating the length of a string --- src/Rule/AbstractStringRule.php | 18 ++++++++++++++++++ src/Rule/Alpha.php | 4 ++-- src/Rule/Length.php | 4 +++- src/Rule/MaxLength.php | 8 +++++--- src/Rule/MinLength.php | 8 +++++--- 5 files changed, 33 insertions(+), 9 deletions(-) create mode 100644 src/Rule/AbstractStringRule.php diff --git a/src/Rule/AbstractStringRule.php b/src/Rule/AbstractStringRule.php new file mode 100644 index 0000000..80b68c2 --- /dev/null +++ b/src/Rule/AbstractStringRule.php @@ -0,0 +1,18 @@ +options['encoding']) && $this->options['encoding']) ? + $this->options['encoding'] : mb_internal_encoding()); + } + + return strlen($str); + } +} \ No newline at end of file diff --git a/src/Rule/Alpha.php b/src/Rule/Alpha.php index 7445581..ab4b799 100755 --- a/src/Rule/Alpha.php +++ b/src/Rule/Alpha.php @@ -9,8 +9,8 @@ class Alpha extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; - $this->success = (bool)ctype_alpha((string)str_replace(' ', '', $value)); + $this->value = $value; + $this->success = (bool) ctype_alpha((string) str_replace(' ', '', $value)); return $this->success; } diff --git a/src/Rule/Length.php b/src/Rule/Length.php index 60f919e..a57717e 100755 --- a/src/Rule/Length.php +++ b/src/Rule/Length.php @@ -6,6 +6,7 @@ class Length extends AbstractRule const OPTION_MIN = 'min'; const OPTION_MAX = 'max'; + const OPTION_ENCODING = 'encoding'; const MESSAGE = 'This input must be between {min} and {max} characters long'; const LABELED_MESSAGE = '{label} must be between {min} and {max} characters long'; @@ -14,7 +15,8 @@ class Length extends AbstractRule protected $optionsIndexMap = array( 0 => self::OPTION_MIN, - 1 => self::OPTION_MAX + 1 => self::OPTION_MAX, + 2 => self::OPTION_ENCODING ); public function validate($value, $valueIdentifier = null) diff --git a/src/Rule/MaxLength.php b/src/Rule/MaxLength.php index 7a60d2d..7af7fbb 100755 --- a/src/Rule/MaxLength.php +++ b/src/Rule/MaxLength.php @@ -1,10 +1,11 @@ self::OPTION_MAX + 0 => self::OPTION_MAX, + 1 => self::OPTION_ENCODING ); public function validate($value, $valueIdentifier = null) @@ -21,7 +23,7 @@ public function validate($value, $valueIdentifier = null) if (!isset($this->options['max'])) { $this->success = true; } else { - $this->success = strlen($value) <= $this->options['max']; + $this->success = $this->getStringLength($value) <= $this->options['max']; } return $this->success; diff --git a/src/Rule/MinLength.php b/src/Rule/MinLength.php index 2c95f8a..119a15a 100755 --- a/src/Rule/MinLength.php +++ b/src/Rule/MinLength.php @@ -1,10 +1,11 @@ self::OPTION_MIN + 0 => self::OPTION_MIN, + 1 => self::OPTION_ENCODING ); public function validate($value, $valueIdentifier = null) @@ -21,7 +23,7 @@ public function validate($value, $valueIdentifier = null) if (!isset($this->options['min'])) { $this->success = true; } else { - $this->success = strlen($value) >= $this->options['min']; + $this->success = $this->getStringLength($value) >= $this->options['min']; } return $this->success; From cbea1a01536a06a67b9d1838fac11d3dece03bb3 Mon Sep 17 00:00:00 2001 From: kenjis Date: Thu, 2 Jul 2015 13:15:23 +0900 Subject: [PATCH 009/112] Add AbstractRule::getOption() --- src/Rule/AbstractRule.php | 15 +++++++++++++++ tests/src/Rule/AbstractValidatorTest.php | 7 +++++++ 2 files changed, 22 insertions(+) diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index 8a67074..1b7182f 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -202,6 +202,21 @@ public function setOption($name, $value) return $this; } + /** + * Get an option for the validator. + * + * @param string $name + * @return mixed + */ + public function getOption($name) + { + if (isset($this->options[$name])) { + return $this->options[$name]; + } else { + return null; + } + } + /** * The context of the validator can be used when the validator depends on other values * that are not known at the moment the validator is constructed diff --git a/tests/src/Rule/AbstractValidatorTest.php b/tests/src/Rule/AbstractValidatorTest.php index 2944d7a..4719188 100755 --- a/tests/src/Rule/AbstractValidatorTest.php +++ b/tests/src/Rule/AbstractValidatorTest.php @@ -65,4 +65,11 @@ function testErrorThrownOnInvalidContext() $this->setExpectedException('\InvalidArgumentException'); $this->rule->setContext(new \stdClass()); } + + function testGetOption() + { + $this->rule->setOption('label', 'Accept'); + $this->assertEquals('Accept', $this->rule->getOption('label')); + $this->assertNull($this->rule->getOption('notExist')); + } } From b855ccd71b8bb13c7a5fb20da1f711d67f8ff05e Mon Sep 17 00:00:00 2001 From: Theo Kouzelis Date: Tue, 7 Jul 2015 16:13:28 +0100 Subject: [PATCH 010/112] Variable name correction $validator was $validation --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 1a20132..43e0fb7 100755 --- a/readme.md +++ b/readme.md @@ -20,7 +20,7 @@ In order to validate other data containers you must create a [`DataWrapper`](htt ##Elevator pitch ```php -$validation = new \Sirius\Validation\Validator; +$validator = new \Sirius\Validation\Validator; // add a validation rule $validator->add('title', 'required'); From d3b2f741860b2ff24cb37b48e1e87195c5d3b78b Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Tue, 1 Sep 2015 11:39:10 +0300 Subject: [PATCH 011/112] Added PSR-4 support --- composer.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index bd4d042..e8dad58 100755 --- a/composer.json +++ b/composer.json @@ -24,8 +24,8 @@ "satooshi/php-coveralls": "dev-master" }, "autoload": { - "files": [ - "autoload.php" - ] + "psr-4": { + "Sirius\\Validation\\": "src/" + } } } From f9ef2d8145fff07d32ea08b90ab2fd61ed767fe9 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 9 Sep 2015 15:23:17 +0300 Subject: [PATCH 012/112] Added tests for validating empty arrays --- tests/src/ValidatorTest.php | 77 ++++++++++++++++++++++--------------- 1 file changed, 45 insertions(+), 32 deletions(-) diff --git a/tests/src/ValidatorTest.php b/tests/src/ValidatorTest.php index e5e1f60..80c498a 100755 --- a/tests/src/ValidatorTest.php +++ b/tests/src/ValidatorTest.php @@ -82,8 +82,8 @@ function testIfMissingItemsValidateAgainstTheRequiredRule() $this->validator->add('items[subitem]', 'required', null, 'This field is required'); $this->validator->setData(array()); $this->validator->validate(); - $this->assertEquals($this->validator->getMessages('item'), array('This field is required')); - $this->assertEquals($this->validator->getMessages('items[subitem]'), array('This field is required')); + $this->assertEquals($this->validator->getMessages('item'), array( 'This field is required' )); + $this->assertEquals($this->validator->getMessages('items[subitem]'), array( 'This field is required' )); } function testDifferentDataFormats() @@ -91,14 +91,14 @@ function testDifferentDataFormats() $this->validator->add('email', 'email'); // test array objects - $data = new \ArrayObject(array(), \ArrayObject::ARRAY_AS_PROPS); + $data = new \ArrayObject(array(), \ArrayObject::ARRAY_AS_PROPS); $data->email = 'not_an_email'; $this->validator->validate($data); $this->assertEquals(1, count($this->validator->getMessages('email'))); // test objects with a 'toArray' method - $data = new FakeObject(); + $data = new FakeObject(); $data->email = 'not_an_email'; $this->validator->validate($data); $this->assertEquals(1, count($this->validator->getMessages('email'))); @@ -116,9 +116,9 @@ function testAddingMultipleRulesAtOnce() array( 'item' => array( 'required', - array('minlength', 'min=4', '{label} should have at least {min} characters', 'Item') + array( 'minlength', 'min=4', '{label} should have at least {min} characters', 'Item' ) ), - 'itema' => array('required', 'minLength(min=8)', 'required'), + 'itema' => array( 'required', 'minLength(min=8)', 'required' ), 'itemb' => 'required' ) ); @@ -128,12 +128,12 @@ function testAddingMultipleRulesAtOnce() 'itema' => 'abc' ) ); - $this->assertEquals(array('Item should have at least 4 characters'), $this->validator->getMessages('item')); + $this->assertEquals(array( 'Item should have at least 4 characters' ), $this->validator->getMessages('item')); $this->assertEquals( - array('This input should have at least 8 characters'), + array( 'This input should have at least 8 characters' ), $this->validator->getMessages('itema') ); - $this->assertEquals(array('This field is required'), $this->validator->getMessages('itemb')); + $this->assertEquals(array( 'This field is required' ), $this->validator->getMessages('itemb')); } function testAddingValidationRulesViaStringsWithoutLabelArg() @@ -147,11 +147,13 @@ function testAddingValidationRulesViaStringsWithoutLabelArg() ->add('itemb:Item B', 'required') // validator with defaults ->add('itemc', 'email'); - $this->validator->validate(array('item' => 'ab', 'itema' => 'abc', 'itemc' => 'abc')); - $this->assertEquals(array('Item should have at least 4 characters'), array((string)$this->validator->getMessages('item')[0])); - $this->assertEquals(array('Item should have at least 8 characters'), $this->validator->getMessages('itema')); - $this->assertEquals(array('Item B is required'), $this->validator->getMessages('itemb')); - $this->assertEquals(array('This input must be a valid email address'), $this->validator->getMessages('itemc')); + $this->validator->validate(array( 'item' => 'ab', 'itema' => 'abc', 'itemc' => 'abc' )); + $this->assertEquals(array( 'Item should have at least 4 characters' ), + array( (string) $this->validator->getMessages('item')[0] )); + $this->assertEquals(array( 'Item should have at least 8 characters' ), $this->validator->getMessages('itema')); + $this->assertEquals(array( 'Item B is required' ), $this->validator->getMessages('itemb')); + $this->assertEquals(array( 'This input must be a valid email address' ), + $this->validator->getMessages('itemc')); } function testAddingValidationRulesViaStrings() @@ -165,11 +167,12 @@ function testAddingValidationRulesViaStrings() ->add('itemb', 'required()(Item B is required)') // validator with defaults ->add('itemc', 'email'); - $this->validator->validate(array('item' => 'ab', 'itema' => 'abc', 'itemc' => 'abc')); - $this->assertEquals(array('Item should have at least 4 characters'), $this->validator->getMessages('item')); - $this->assertEquals(array('Item should have at least 8 characters'), $this->validator->getMessages('itema')); - $this->assertEquals(array('Item B is required'), $this->validator->getMessages('itemb')); - $this->assertEquals(array('This input must be a valid email address'), $this->validator->getMessages('itemc')); + $this->validator->validate(array( 'item' => 'ab', 'itema' => 'abc', 'itemc' => 'abc' )); + $this->assertEquals(array( 'Item should have at least 4 characters' ), $this->validator->getMessages('item')); + $this->assertEquals(array( 'Item should have at least 8 characters' ), $this->validator->getMessages('itema')); + $this->assertEquals(array( 'Item B is required' ), $this->validator->getMessages('itemb')); + $this->assertEquals(array( 'This input must be a valid email address' ), + $this->validator->getMessages('itemc')); } function testExceptionOnInvalidValidatorOptions() @@ -192,11 +195,11 @@ static function fakeStaticValidationMethod($value, $return = false) function testCallbackValidators() { $this->validator->add('function', __NAMESPACE__ . '\fakeValidationFunction'); - $this->validator->add('method', array($this, 'fakeValidationMethod')); + $this->validator->add('method', array( $this, 'fakeValidationMethod' )); $this->validator->add( 'staticMethod', - array(__CLASS__, 'fakeStaticValidationMethod'), - array(true) + array( __CLASS__, 'fakeStaticValidationMethod' ), + array( true ) ); // this will return true $this->validator->validate( @@ -239,24 +242,24 @@ function testMatchingRules() $this->validator->validate( array( 'items' => array( - array('key' => 'sss'), - array('key' => 'sss') + array( 'key' => 'sss' ), + array( 'key' => 'sss' ) ) ) ); - $this->assertEquals(array('Key must be an email'), $this->validator->getMessages('items[0][key]')); - $this->assertEquals(array('Key must be an email'), $this->validator->getMessages('items[1][key]')); + $this->assertEquals(array( 'Key must be an email' ), $this->validator->getMessages('items[0][key]')); + $this->assertEquals(array( 'Key must be an email' ), $this->validator->getMessages('items[1][key]')); } function testIfParametersAreSentToValidationMethods() { $this->validator - ->add('a', 'email', array(0, 1), 'This should be an email') - ->add('b', 'email', array(0, 1, 2), 'This should be an email') - ->add('c', 'email', array(0, 1, 2, 3), 'This should be an email'); - $this->validator->validate(array('a' => 'a', 'b' => 'b', 'c' => 'c')); + ->add('a', 'email', array( 0, 1 ), 'This should be an email') + ->add('b', 'email', array( 0, 1, 2 ), 'This should be an email') + ->add('c', 'email', array( 0, 1, 2, 3 ), 'This should be an email'); + $this->validator->validate(array( 'a' => 'a', 'b' => 'b', 'c' => 'c' )); $messages = $this->validator->getMessages(); - foreach (array('a', 'b', 'c') as $k) { + foreach (array( 'a', 'b', 'c' ) as $k) { $this->assertEquals(1, count($messages[$k])); } } @@ -265,7 +268,17 @@ function testIfExceptionIsThrownForInvalidValidationMethods() { $this->setExpectedException('\InvalidArgumentException'); $this->validator->add('item', 'faker'); - $this->validator->validate(array('item' => true)); + $this->validator->validate(array( 'item' => true )); + } + + function testEmptyArrayValidation() + { + $this->validator->add(array( + 'a' => array( 'required' ), + 'b' => array( 'required' ) + )); + $this->validator->validate(array()); + $this->assertEquals(2, count($this->validator->getMessages())); } } From a364e117154ed8c238f38f939f8abb4bc067c92c Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 9 Sep 2015 15:23:32 +0300 Subject: [PATCH 013/112] Code formatting --- src/DataWrapper/ArrayWrapper.php | 3 +- src/ErrorMessage.php | 6 +-- src/Helper.php | 11 +++-- src/Rule/AbstractRule.php | 49 ++++++++++++++++------- src/Rule/AlphaNumHyphen.php | 6 +-- src/Rule/AlphaNumeric.php | 4 +- src/Rule/ArrayLength.php | 2 +- src/Rule/ArrayMaxLength.php | 2 +- src/Rule/ArrayMinLength.php | 2 +- src/Rule/Between.php | 2 +- src/Rule/Callback.php | 8 ++-- src/Rule/Date.php | 6 +-- src/Rule/Email.php | 4 +- src/Rule/EmailDomain.php | 4 +- src/Rule/File/Extension.php | 6 +-- src/Rule/File/Image.php | 10 ++--- src/Rule/File/ImageHeight.php | 6 +-- src/Rule/File/ImageRatio.php | 8 ++-- src/Rule/File/ImageWidth.php | 6 +-- src/Rule/File/Size.php | 14 +++---- src/Rule/GreaterThan.php | 2 +- src/Rule/InList.php | 2 +- src/Rule/Integer.php | 4 +- src/Rule/IpAddress.php | 4 +- src/Rule/Length.php | 2 +- src/Rule/LessThan.php | 2 +- src/Rule/MaxLength.php | 2 +- src/Rule/MinLength.php | 2 +- src/Rule/NotInList.php | 4 +- src/Rule/NotRegex.php | 2 +- src/Rule/Number.php | 4 +- src/Rule/Regex.php | 2 +- src/Rule/Required.php | 2 +- src/Rule/RequiredWhen.php | 14 +++---- src/Rule/RequiredWith.php | 2 +- src/Rule/RequiredWithout.php | 2 +- src/Rule/Upload/Extension.php | 6 +-- src/Rule/Upload/Image.php | 10 ++--- src/Rule/Upload/ImageHeight.php | 6 +-- src/Rule/Upload/ImageRatio.php | 8 ++-- src/Rule/Upload/ImageWidth.php | 6 +-- src/Rule/Upload/Size.php | 14 +++---- src/Rule/Url.php | 4 +- src/Rule/Website.php | 4 +- src/RuleFactory.php | 21 ++++++---- src/Util/Arr.php | 26 +++++++----- src/Validator.php | 29 +++++++++----- src/ValueValidator.php | 27 +++++++------ tests/src/ComplexTest.php | 14 +++---- tests/src/ErrorMessageTest.php | 4 +- tests/src/HelperTest.php | 8 ++-- tests/src/Rule/AbstractValidatorTest.php | 14 +++---- tests/src/Rule/CallbackTest.php | 6 +-- tests/src/Rule/File/ExtensionTest.php | 8 ++-- tests/src/Rule/File/ImageHeightTest.php | 2 +- tests/src/Rule/File/ImageRatioTest.php | 2 +- tests/src/Rule/File/ImageTest.php | 8 ++-- tests/src/Rule/File/ImageWidthTest.php | 2 +- tests/src/Rule/File/SizeTest.php | 2 +- tests/src/Rule/LessThanTest.php | 9 +++-- tests/src/Rule/RequiredWithTest.php | 4 +- tests/src/Rule/RequiredWithoutTest.php | 4 +- tests/src/Rule/Upload/ExtensionTest.php | 14 +++---- tests/src/Rule/Upload/ImageHeightTest.php | 8 ++-- tests/src/Rule/Upload/ImageRatioTest.php | 14 +++---- tests/src/Rule/Upload/ImageTest.php | 16 ++++---- tests/src/Rule/Upload/ImageWidthTest.php | 8 ++-- tests/src/Rule/Upload/SizeTest.php | 8 ++-- tests/src/RuleFactoryTest.php | 8 ++-- tests/src/Util/ArrTest.php | 10 ++--- 70 files changed, 295 insertions(+), 250 deletions(-) diff --git a/src/DataWrapper/ArrayWrapper.php b/src/DataWrapper/ArrayWrapper.php index e473fec..5ae78e4 100644 --- a/src/DataWrapper/ArrayWrapper.php +++ b/src/DataWrapper/ArrayWrapper.php @@ -15,6 +15,7 @@ class ArrayWrapper implements WrapperInterface /** * @param array|\ArrayObject|object $data + * * @throws \InvalidArgumentException */ public function __construct($data = array()) @@ -26,7 +27,7 @@ public function __construct($data = array()) $data = $data->toArray(); } } - if (!is_array($data)) { + if ( ! is_array($data)) { throw new \InvalidArgumentException('Data passed to validator is not an array or an ArrayObject'); } $this->data = $data; diff --git a/src/ErrorMessage.php b/src/ErrorMessage.php index 57da774..db7a2b5 100755 --- a/src/ErrorMessage.php +++ b/src/ErrorMessage.php @@ -10,14 +10,14 @@ class ErrorMessage public function __construct($template = '', $variables = array()) { $this->setTemplate($template) - ->setVariables($variables); + ->setVariables($variables); } public function setTemplate($template) { - $template = trim((string)$template); + $template = trim((string) $template); if ($template) { - $this->template = (string)$template; + $this->template = (string) $template; } return $this; diff --git a/src/Helper.php b/src/Helper.php index 12c2cad..ec09ae5 100755 --- a/src/Helper.php +++ b/src/Helper.php @@ -48,12 +48,12 @@ public static function required($value) public static function truthy($value) { - return (bool)$value; + return (bool) $value; } public static function falsy($value) { - return !static::truthy($value); + return ! static::truthy($value); } public static function number($value) @@ -63,7 +63,7 @@ public static function number($value) public static function integer($value) { - return $value == '0' || (int)$value == $value; + return $value == '0' || (int) $value == $value; } public static function lessThan($value, $max) @@ -107,7 +107,7 @@ public static function exactly($value, $otherValue) public static function not($value, $otherValue) { - return !self::exactly($value, $otherValue); + return ! self::exactly($value, $otherValue); } public static function alpha($value) @@ -303,6 +303,7 @@ public static function url($value) * Test if a variable is a valid IP address * * @param string $value + * * @return bool */ public static function ip($value) @@ -324,6 +325,7 @@ public static function email($value) * Criterias: at least 6 characters, 2 words * * @param mixed $value + * * @return bool */ public static function fullName($value) @@ -337,6 +339,7 @@ public static function fullName($value) * Test if the domain of an email address is available * * @param string $value + * * @return bool */ public static function emailDomain($value) diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index 1b7182f..6a6ac57 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -62,7 +62,7 @@ abstract class AbstractRule public function __construct($options = array()) { $options = $this->normalizeOptions($options); - if (is_array($options) && !empty($options)) { + if (is_array($options) && ! empty($options)) { foreach ($options as $k => $v) { $this->setOption($k, $v); } @@ -83,7 +83,7 @@ public function __construct($options = array()) */ protected function normalizeOptions($options) { - if (!$options) { + if ( ! $options) { return array(); } @@ -103,7 +103,7 @@ protected function normalizeOptions($options) } } - if (!is_array($result)) { + if ( ! is_array($result)) { throw new \InvalidArgumentException('Validator options should be an array, JSON string or query string'); } @@ -114,10 +114,13 @@ protected function normalizeOptions($options) * Converts a HTTP query string to an array * * @param $str + * * @return array */ - protected function parseHttpQueryString($str) { + protected function parseHttpQueryString($str) + { parse_str($str, $arr); + return $this->convertBooleanStrings($arr); } @@ -125,11 +128,13 @@ protected function parseHttpQueryString($str) { * Converts 'true' and 'false' strings to TRUE and FALSE * * @param $v + * * @return bool */ - protected function convertBooleanStrings($v) { + protected function convertBooleanStrings($v) + { if (is_array($v)) { - return array_map(array($this, 'convertBooleanStrings'), $v); + return array_map(array( $this, 'convertBooleanStrings' ), $v); } if ($v === 'true') { return true; @@ -137,6 +142,7 @@ protected function convertBooleanStrings($v) { if ($v === 'false') { return false; } + return $v; } @@ -145,21 +151,26 @@ protected function convertBooleanStrings($v) { * (an associative array that contains the options for the validation rule) * * @param $str + * * @return array */ - protected function parseCsvString($str) { - if (!isset($this->optionsIndexMap) || !is_array($this->optionsIndexMap) || empty($this->optionsIndexMap)) { - throw new \InvalidArgumentException(sprintf('Class %s is missing the `optionsIndexMap` property', get_class($this))); + protected function parseCsvString($str) + { + if ( ! isset($this->optionsIndexMap) || ! is_array($this->optionsIndexMap) || empty($this->optionsIndexMap)) { + throw new \InvalidArgumentException(sprintf('Class %s is missing the `optionsIndexMap` property', + get_class($this))); } $options = explode(',', $str); - $result = array(); + $result = array(); foreach ($options as $k => $v) { - if (!isset($this->optionsIndexMap[$k])) { - throw new \InvalidArgumentException(sprintf('Class %s does not have the index %d configured in the `optionsIndexMap` property', get_class($this), $k)); + if ( ! isset($this->optionsIndexMap[$k])) { + throw new \InvalidArgumentException(sprintf('Class %s does not have the index %d configured in the `optionsIndexMap` property', + get_class($this), $k)); } $result[$this->optionsIndexMap[$k]] = $v; } + return $this->convertBooleanStrings($result); } @@ -167,6 +178,7 @@ protected function parseCsvString($str) { * Checks if an array is associative (ie: the keys are not numbers in sequence) * * @param array $arr + * * @return bool */ protected function arrayIsAssoc($arr) @@ -193,6 +205,7 @@ public function getUniqueId() * * @param string $name * @param mixed $value + * * @return \Sirius\Validation\Rule\AbstractRule */ public function setOption($name, $value) @@ -204,8 +217,9 @@ public function setOption($name, $value) /** * Get an option for the validator. - * + * * @param string $name + * * @return mixed */ public function getOption($name) @@ -224,6 +238,7 @@ public function getOption($name) * to confirm the email address * * @param array|object $context + * * @throws \InvalidArgumentException * @return \Sirius\Validation\Rule\AbstractRule */ @@ -235,7 +250,7 @@ public function setContext($context = null) if (is_array($context)) { $context = new ArrayWrapper($context); } - if (!is_object($context) || !$context instanceof WrapperInterface) { + if ( ! is_object($context) || ! $context instanceof WrapperInterface) { throw new \InvalidArgumentException( 'Validator context must be either an array or an instance of Sirius\Validator\DataWrapper\WrapperInterface' ); @@ -249,6 +264,7 @@ public function setContext($context = null) * Custom message for this validator to used instead of the the default one * * @param string $messageTemplate + * * @return \Sirius\Validation\Rule\AbstractRule */ public function setMessageTemplate($messageTemplate) @@ -280,6 +296,7 @@ public function getMessageTemplate() * * @param mixed $value * @param null|mixed $valueIdentifier + * * @return mixed */ abstract function validate($value, $valueIdentifier = null); @@ -290,6 +307,7 @@ abstract function validate($value, $valueIdentifier = null); * This option can be used when you need translation * * @param ErrorMessage $errorMessagePrototype + * * @throws \InvalidArgumentException * @return \Sirius\Validation\Rule\AbstractRule */ @@ -308,7 +326,7 @@ public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype) */ public function getErrorMessagePrototype() { - if (!$this->errorMessagePrototype) { + if ( ! $this->errorMessagePrototype) { $this->errorMessagePrototype = new ErrorMessage(); } @@ -357,6 +375,7 @@ public function getPotentialMessage() * * @param $valueIdentifier * @param $relatedItem + * * @return string|null */ protected function getRelatedValueIdentifier($valueIdentifier, $relatedItem) diff --git a/src/Rule/AlphaNumHyphen.php b/src/Rule/AlphaNumHyphen.php index 4d94e3f..212f082 100755 --- a/src/Rule/AlphaNumHyphen.php +++ b/src/Rule/AlphaNumHyphen.php @@ -9,9 +9,9 @@ class AlphaNumHyphen extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; - $this->success = (bool)ctype_alnum( - (string)str_replace( + $this->value = $value; + $this->success = (bool) ctype_alnum( + (string) str_replace( array( ' ', '_', diff --git a/src/Rule/AlphaNumeric.php b/src/Rule/AlphaNumeric.php index 925c64b..14b6596 100755 --- a/src/Rule/AlphaNumeric.php +++ b/src/Rule/AlphaNumeric.php @@ -10,8 +10,8 @@ class AlphaNumeric extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; - $this->success = (bool)ctype_alnum((string)str_replace(' ', '', $value)); + $this->value = $value; + $this->success = (bool) ctype_alnum((string) str_replace(' ', '', $value)); return $this->success; } diff --git a/src/Rule/ArrayLength.php b/src/Rule/ArrayLength.php index 373223d..8b159c0 100755 --- a/src/Rule/ArrayLength.php +++ b/src/Rule/ArrayLength.php @@ -19,7 +19,7 @@ class ArrayLength extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; + $this->value = $value; $maxValidator = new ArrayMaxLength(); if (isset($this->options['max'])) { $maxValidator->setOption('max', $this->options['max']); diff --git a/src/Rule/ArrayMaxLength.php b/src/Rule/ArrayMaxLength.php index 82cb763..868e24f 100755 --- a/src/Rule/ArrayMaxLength.php +++ b/src/Rule/ArrayMaxLength.php @@ -19,7 +19,7 @@ class ArrayMaxLength extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!isset($this->options['max'])) { + if ( ! isset($this->options['max'])) { $this->success = true; } else { $this->success = is_array($value) && count($value) <= $this->options['max']; diff --git a/src/Rule/ArrayMinLength.php b/src/Rule/ArrayMinLength.php index 609ab68..b64ab08 100755 --- a/src/Rule/ArrayMinLength.php +++ b/src/Rule/ArrayMinLength.php @@ -18,7 +18,7 @@ class ArrayMinLength extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!isset($this->options['min'])) { + if ( ! isset($this->options['min'])) { $this->success = true; } else { $this->success = is_array($value) && count($value) >= $this->options['min']; diff --git a/src/Rule/Between.php b/src/Rule/Between.php index 285f6ea..b1f392c 100755 --- a/src/Rule/Between.php +++ b/src/Rule/Between.php @@ -19,7 +19,7 @@ class Between extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; + $this->value = $value; $minValidator = new LessThan(); if (isset($this->options['max'])) { $minValidator->setOption('max', $this->options['max']); diff --git a/src/Rule/Callback.php b/src/Rule/Callback.php index 3ec24e3..e4ce532 100755 --- a/src/Rule/Callback.php +++ b/src/Rule/Callback.php @@ -31,7 +31,7 @@ public function getUniqueId() } if (isset($this->options['arguments'])) { - $args = (array)$this->options['arguments']; + $args = (array) $this->options['arguments']; ksort($args); $uniqueId .= '|' . json_encode($args); } @@ -42,13 +42,13 @@ public function getUniqueId() public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!isset($this->options['callback']) || !is_callable($this->options['callback'])) { + if ( ! isset($this->options['callback']) || ! is_callable($this->options['callback'])) { $this->success = true; } else { - $args = (isset($this->options['arguments'])) ? (array)$this->options['arguments'] : array(); + $args = (isset($this->options['arguments'])) ? (array) $this->options['arguments'] : array(); array_unshift($args, $value); array_push($args, $valueIdentifier, $this->context); - $this->success = (bool)call_user_func_array($this->options['callback'], $args); + $this->success = (bool) call_user_func_array($this->options['callback'], $args); } return $this->success; diff --git a/src/Rule/Date.php b/src/Rule/Date.php index 0e4a9f1..36e730e 100644 --- a/src/Rule/Date.php +++ b/src/Rule/Date.php @@ -20,7 +20,7 @@ class Date extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; + $this->value = $value; $this->success = $value == date($this->options['format'], $this->getTimestampFromFormatedString($value, $this->options['format'])); @@ -31,7 +31,7 @@ protected function getTimestampFromFormatedString($string, $format) { $result = date_parse_from_format($format, $string); - return mktime((int)$result['hour'], (int)$result['minute'], (int)$result['second'], (int)$result['month'], - (int)$result['day'], (int)$result['year']); + return mktime((int) $result['hour'], (int) $result['minute'], (int) $result['second'], (int) $result['month'], + (int) $result['day'], (int) $result['year']); } } diff --git a/src/Rule/Email.php b/src/Rule/Email.php index be8005f..a86ac92 100755 --- a/src/Rule/Email.php +++ b/src/Rule/Email.php @@ -10,8 +10,8 @@ class Email extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; - $this->success = (filter_var((string)$value, FILTER_VALIDATE_EMAIL) !== false); + $this->value = $value; + $this->success = (filter_var((string) $value, FILTER_VALIDATE_EMAIL) !== false); return $this->success; } diff --git a/src/Rule/EmailDomain.php b/src/Rule/EmailDomain.php index 5d3ed6c..5c2113c 100755 --- a/src/Rule/EmailDomain.php +++ b/src/Rule/EmailDomain.php @@ -9,10 +9,10 @@ class EmailDomain extends AbstractRule public function validate($value, $valueIdentifier = null) { - $value = (string)$value; + $value = (string) $value; $this->value = $value; // Check if the email domain has a valid MX record - $this->success = (bool)checkdnsrr(preg_replace('/^[^@]+@/', '', $value), 'MX'); + $this->success = (bool) checkdnsrr(preg_replace('/^[^@]+@/', '', $value), 'MX'); return $this->success; } diff --git a/src/Rule/File/Extension.php b/src/Rule/File/Extension.php index dc7e140..66a4a69 100644 --- a/src/Rule/File/Extension.php +++ b/src/Rule/File/Extension.php @@ -33,10 +33,10 @@ public function setOption($name, $value) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!file_exists($value)) { + if ( ! file_exists($value)) { $this->success = false; } else { - $extension = strtolower(substr($value, strrpos($value, '.') + 1, 10)); + $extension = strtolower(substr($value, strrpos($value, '.') + 1, 10)); $this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array( $extension, $this->options[self::OPTION_ALLOWED_EXTENSIONS] @@ -48,7 +48,7 @@ public function validate($value, $valueIdentifier = null) public function getPotentialMessage() { - $message = parent::getPotentialMessage(); + $message = parent::getPotentialMessage(); $fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]); $message->setVariables( array( diff --git a/src/Rule/File/Image.php b/src/Rule/File/Image.php index 00abe80..bdca3e2 100644 --- a/src/Rule/File/Image.php +++ b/src/Rule/File/Image.php @@ -14,7 +14,7 @@ class Image extends AbstractRule const LABELED_MESSAGE = '{label} is not a valid image (only {image_types} are allowed)'; protected $options = array( - self::OPTION_ALLOWED_IMAGES => array('jpg', 'png', 'gif') + self::OPTION_ALLOWED_IMAGES => array( 'jpg', 'png', 'gif' ) ); protected $imageTypesMap = array( @@ -43,11 +43,11 @@ public function setOption($name, $value) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!file_exists($value)) { + if ( ! file_exists($value)) { $this->success = false; } else { - $imageInfo = getimagesize($value); - $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; + $imageInfo = getimagesize($value); + $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); } @@ -56,7 +56,7 @@ public function validate($value, $valueIdentifier = null) public function getPotentialMessage() { - $message = parent::getPotentialMessage(); + $message = parent::getPotentialMessage(); $imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]); $message->setVariables( array( diff --git a/src/Rule/File/ImageHeight.php b/src/Rule/File/ImageHeight.php index 610a5e7..e93e5ab 100644 --- a/src/Rule/File/ImageHeight.php +++ b/src/Rule/File/ImageHeight.php @@ -20,11 +20,11 @@ class ImageHeight extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!file_exists($value)) { + if ( ! file_exists($value)) { $this->success = false; } else { - $imageInfo = getimagesize($value); - $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; + $imageInfo = getimagesize($value); + $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; $this->success = $height && $height <= $this->options[self::OPTION_MAX] && $height >= $this->options[self::OPTION_MIN]; } diff --git a/src/Rule/File/ImageRatio.php b/src/Rule/File/ImageRatio.php index dd89169..8c76455 100644 --- a/src/Rule/File/ImageRatio.php +++ b/src/Rule/File/ImageRatio.php @@ -37,14 +37,14 @@ protected function normalizeRatio($ratio) public function validate($value, $valueIdentifier = null) { $this->value = $value; - $ratio = $this->normalizeRatio($this->options[self::OPTION_RATIO]); - if (!file_exists($value)) { + $ratio = $this->normalizeRatio($this->options[self::OPTION_RATIO]); + if ( ! file_exists($value)) { $this->success = false; } elseif ($ratio == 0) { $this->success = true; } else { - $imageInfo = getimagesize($value); - $actualRatio = $imageInfo[0] / $imageInfo[1]; + $imageInfo = getimagesize($value); + $actualRatio = $imageInfo[0] / $imageInfo[1]; $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; } diff --git a/src/Rule/File/ImageWidth.php b/src/Rule/File/ImageWidth.php index dadb32a..8d2ad0e 100644 --- a/src/Rule/File/ImageWidth.php +++ b/src/Rule/File/ImageWidth.php @@ -20,11 +20,11 @@ class ImageWidth extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!file_exists($value)) { + if ( ! file_exists($value)) { $this->success = false; } else { - $imageInfo = getimagesize($value); - $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; + $imageInfo = getimagesize($value); + $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; $this->success = $width && $width <= $this->options[self::OPTION_MAX] && $width >= $this->options[self::OPTION_MIN]; } diff --git a/src/Rule/File/Size.php b/src/Rule/File/Size.php index b61ed0d..0a03ade 100644 --- a/src/Rule/File/Size.php +++ b/src/Rule/File/Size.php @@ -17,12 +17,12 @@ class Size extends AbstractRule protected function normalizeSize($size) { - $units = array('B' => 0, 'K' => 1, 'M' => 2, 'G' => 3); - $unit = strtoupper(substr($size, strlen($size) - 1, 1)); - if (!isset($units[$unit])) { + $units = array( 'B' => 0, 'K' => 1, 'M' => 2, 'G' => 3 ); + $unit = strtoupper(substr($size, strlen($size) - 1, 1)); + if ( ! isset($units[$unit])) { $normalizedSize = filter_var($size, FILTER_SANITIZE_NUMBER_INT); } else { - $size = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); + $size = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); $normalizedSize = $size * pow(1024, $units[$unit]); } @@ -32,11 +32,11 @@ protected function normalizeSize($size) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!file_exists($value)) { + if ( ! file_exists($value)) { $this->success = false; } else { - $fileSize = @filesize($value); - $limit = $this->normalizeSize($this->options[self::OPTION_SIZE]); + $fileSize = @filesize($value); + $limit = $this->normalizeSize($this->options[self::OPTION_SIZE]); $this->success = $fileSize && $fileSize <= $limit; } diff --git a/src/Rule/GreaterThan.php b/src/Rule/GreaterThan.php index b57c5de..d665fbe 100755 --- a/src/Rule/GreaterThan.php +++ b/src/Rule/GreaterThan.php @@ -22,7 +22,7 @@ class GreaterThan extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!isset($this->options['min'])) { + if ( ! isset($this->options['min'])) { $this->success = true; } else { if ($this->options['inclusive']) { diff --git a/src/Rule/InList.php b/src/Rule/InList.php index a25940c..fead6a1 100755 --- a/src/Rule/InList.php +++ b/src/Rule/InList.php @@ -17,7 +17,7 @@ class InList extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!isset($this->options['list'])) { + if ( ! isset($this->options['list'])) { $this->success = true; } else { if (is_array($this->options['list'])) { diff --git a/src/Rule/Integer.php b/src/Rule/Integer.php index 8c99723..264922e 100644 --- a/src/Rule/Integer.php +++ b/src/Rule/Integer.php @@ -9,8 +9,8 @@ class Integer extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; - $this->success = (bool)filter_var($value, FILTER_VALIDATE_INT) || (string)$value === '0'; + $this->value = $value; + $this->success = (bool) filter_var($value, FILTER_VALIDATE_INT) || (string) $value === '0'; return $this->success; } diff --git a/src/Rule/IpAddress.php b/src/Rule/IpAddress.php index d477d42..d5a5077 100755 --- a/src/Rule/IpAddress.php +++ b/src/Rule/IpAddress.php @@ -13,9 +13,9 @@ public function validate($value, $valueIdentifier = null) // Do not allow private and reserved range IPs $flags = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; if (strpos($value, ':') !== false) { - $this->success = (bool)filter_var($value, FILTER_VALIDATE_IP, $flags | FILTER_FLAG_IPV6); + $this->success = (bool) filter_var($value, FILTER_VALIDATE_IP, $flags | FILTER_FLAG_IPV6); } else { - $this->success = (bool)filter_var($value, FILTER_VALIDATE_IP, $flags | FILTER_FLAG_IPV4); + $this->success = (bool) filter_var($value, FILTER_VALIDATE_IP, $flags | FILTER_FLAG_IPV4); } return $this->success; diff --git a/src/Rule/Length.php b/src/Rule/Length.php index a57717e..9e9d749 100755 --- a/src/Rule/Length.php +++ b/src/Rule/Length.php @@ -21,7 +21,7 @@ class Length extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; + $this->value = $value; $maxValidator = new MinLength(); if (isset($this->options['max'])) { $maxValidator->setOption('max', $this->options['max']); diff --git a/src/Rule/LessThan.php b/src/Rule/LessThan.php index 5d2c149..450407b 100755 --- a/src/Rule/LessThan.php +++ b/src/Rule/LessThan.php @@ -22,7 +22,7 @@ class LessThan extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!isset($this->options['max'])) { + if ( ! isset($this->options['max'])) { $this->success = true; } else { if ($this->options['inclusive']) { diff --git a/src/Rule/MaxLength.php b/src/Rule/MaxLength.php index 7af7fbb..613483a 100755 --- a/src/Rule/MaxLength.php +++ b/src/Rule/MaxLength.php @@ -20,7 +20,7 @@ class MaxLength extends AbstractStringRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!isset($this->options['max'])) { + if ( ! isset($this->options['max'])) { $this->success = true; } else { $this->success = $this->getStringLength($value) <= $this->options['max']; diff --git a/src/Rule/MinLength.php b/src/Rule/MinLength.php index 119a15a..72372d9 100755 --- a/src/Rule/MinLength.php +++ b/src/Rule/MinLength.php @@ -20,7 +20,7 @@ class MinLength extends AbstractStringRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!isset($this->options['min'])) { + if ( ! isset($this->options['min'])) { $this->success = true; } else { $this->success = $this->getStringLength($value) >= $this->options['min']; diff --git a/src/Rule/NotInList.php b/src/Rule/NotInList.php index b1bf8d9..fe2057f 100755 --- a/src/Rule/NotInList.php +++ b/src/Rule/NotInList.php @@ -16,11 +16,11 @@ class NotInList extends InList public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!isset($this->options['list'])) { + if ( ! isset($this->options['list'])) { $this->success = true; } else { if (is_array($this->options['list'])) { - $this->success = !in_array($value, $this->options['list']); + $this->success = ! in_array($value, $this->options['list']); } } diff --git a/src/Rule/NotRegex.php b/src/Rule/NotRegex.php index 25c2a42..0930d12 100755 --- a/src/Rule/NotRegex.php +++ b/src/Rule/NotRegex.php @@ -10,7 +10,7 @@ class NotRegex extends Regex public function validate($value, $valueIdentifier = null) { parent::validate($value, $valueIdentifier); - $this->success = !$this->success; + $this->success = ! $this->success; return $this->success; } diff --git a/src/Rule/Number.php b/src/Rule/Number.php index e6029b0..235b920 100644 --- a/src/Rule/Number.php +++ b/src/Rule/Number.php @@ -9,8 +9,8 @@ class Number extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; - $this->success = (bool)filter_var($value, FILTER_VALIDATE_FLOAT) || (string)$value === '0'; + $this->value = $value; + $this->success = (bool) filter_var($value, FILTER_VALIDATE_FLOAT) || (string) $value === '0'; return $this->success; } diff --git a/src/Rule/Regex.php b/src/Rule/Regex.php index 0333b35..9c25355 100755 --- a/src/Rule/Regex.php +++ b/src/Rule/Regex.php @@ -17,7 +17,7 @@ public function validate($value, $valueIdentifier = null) { $this->value = $value; if (isset($this->options['pattern'])) { - $this->success = (bool)preg_match($this->options['pattern'], $value); + $this->success = (bool) preg_match($this->options['pattern'], $value); } else { $this->success = true; } diff --git a/src/Rule/Required.php b/src/Rule/Required.php index f8c1679..55fe1c8 100755 --- a/src/Rule/Required.php +++ b/src/Rule/Required.php @@ -9,7 +9,7 @@ class Required extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; + $this->value = $value; $this->success = ($value !== null && $value !== ''); return $this->success; diff --git a/src/Rule/RequiredWhen.php b/src/Rule/RequiredWhen.php index b806ec7..0964d39 100644 --- a/src/Rule/RequiredWhen.php +++ b/src/Rule/RequiredWhen.php @@ -13,8 +13,8 @@ class RequiredWhen extends Required public function getItemRule() { /* @var $rule AbstractValidator */ - $rule = false; - $ruleOptions = (isset($this->options[self::OPTION_RULE_OPTIONS])) ? (array)$this->options[self::OPTION_RULE_OPTIONS] : array(); + $rule = false; + $ruleOptions = (isset($this->options[self::OPTION_RULE_OPTIONS])) ? (array) $this->options[self::OPTION_RULE_OPTIONS] : array(); if (is_string($this->options[self::OPTION_RULE])) { $ruleClass = $this->options[self::OPTION_RULE]; @@ -22,14 +22,14 @@ public function getItemRule() $rule = new $ruleClass($ruleOptions); } elseif (class_exists('Sirius\\Validation\\Rule\\' . $ruleClass)) { $ruleClass = 'Sirius\\Validation\\Rule\\' . $ruleClass; - $rule = new $ruleClass($ruleOptions); + $rule = new $ruleClass($ruleOptions); } } elseif (is_object($this->options[self::OPTION_RULE]) - && $this->options[self::OPTION_RULE] instanceof AbstractRule + && $this->options[self::OPTION_RULE] instanceof AbstractRule ) { $rule = $this->options[self::OPTION_RULE]; } - if (!$rule) { + if ( ! $rule) { throw new \InvalidArgumentException( 'Validator for the other item is not valid or cannot be constructed based on the data provided' ); @@ -44,11 +44,11 @@ public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!isset($this->options[self::OPTION_ITEM])) { + if ( ! isset($this->options[self::OPTION_ITEM])) { $this->success = true; } else { - $relatedItemPath = $this->getRelatedValueIdentifier($valueIdentifier, $this->options[self::OPTION_ITEM]); + $relatedItemPath = $this->getRelatedValueIdentifier($valueIdentifier, $this->options[self::OPTION_ITEM]); $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; $itemRule = $this->getItemRule(); diff --git a/src/Rule/RequiredWith.php b/src/Rule/RequiredWith.php index 18d82d1..3eaccfb 100644 --- a/src/Rule/RequiredWith.php +++ b/src/Rule/RequiredWith.php @@ -16,7 +16,7 @@ public function validate($value, $valueIdentifier = null) { $this->value = $value; - $relatedItemPath = $this->getRelatedValueIdentifier($valueIdentifier, $this->options[self::OPTION_ITEM]); + $relatedItemPath = $this->getRelatedValueIdentifier($valueIdentifier, $this->options[self::OPTION_ITEM]); $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; if (isset($this->options[self::OPTION_ITEM]) && $relatedItemValue !== null) { diff --git a/src/Rule/RequiredWithout.php b/src/Rule/RequiredWithout.php index 2832e72..b6bc18e 100644 --- a/src/Rule/RequiredWithout.php +++ b/src/Rule/RequiredWithout.php @@ -16,7 +16,7 @@ public function validate($value, $valueIdentifier = null) { $this->value = $value; - $relatedItemPath = $this->getRelatedValueIdentifier($valueIdentifier, $this->options[self::OPTION_ITEM]); + $relatedItemPath = $this->getRelatedValueIdentifier($valueIdentifier, $this->options[self::OPTION_ITEM]); $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; if (isset($this->options[self::OPTION_ITEM]) && $relatedItemValue === null) { diff --git a/src/Rule/Upload/Extension.php b/src/Rule/Upload/Extension.php index 5809c1d..91eaac8 100644 --- a/src/Rule/Upload/Extension.php +++ b/src/Rule/Upload/Extension.php @@ -33,10 +33,10 @@ public function setOption($name, $value) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!is_array($value) || !isset($value['tmp_name']) || !file_exists($value['tmp_name'])) { + if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { $this->success = false; } else { - $extension = strtolower(substr($value['name'], strrpos($value['name'], '.') + 1, 10)); + $extension = strtolower(substr($value['name'], strrpos($value['name'], '.') + 1, 10)); $this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array( $extension, $this->options[self::OPTION_ALLOWED_EXTENSIONS] @@ -48,7 +48,7 @@ public function validate($value, $valueIdentifier = null) public function getPotentialMessage() { - $message = parent::getPotentialMessage(); + $message = parent::getPotentialMessage(); $fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]); $message->setVariables( array( diff --git a/src/Rule/Upload/Image.php b/src/Rule/Upload/Image.php index f68947b..16a33b6 100644 --- a/src/Rule/Upload/Image.php +++ b/src/Rule/Upload/Image.php @@ -14,7 +14,7 @@ class Image extends AbstractRule const LABELED_MESSAGE = '{label} is not a valid image (only {image_types} are allowed)'; protected $options = array( - self::OPTION_ALLOWED_IMAGES => array('jpg', 'png', 'gif') + self::OPTION_ALLOWED_IMAGES => array( 'jpg', 'png', 'gif' ) ); protected $imageTypesMap = array( @@ -43,11 +43,11 @@ public function setOption($name, $value) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!is_array($value) || !isset($value['tmp_name']) || !file_exists($value['tmp_name'])) { + if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { $this->success = false; } else { - $imageInfo = getimagesize($value['tmp_name']); - $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; + $imageInfo = getimagesize($value['tmp_name']); + $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); } @@ -56,7 +56,7 @@ public function validate($value, $valueIdentifier = null) public function getPotentialMessage() { - $message = parent::getPotentialMessage(); + $message = parent::getPotentialMessage(); $imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]); $message->setVariables( array( diff --git a/src/Rule/Upload/ImageHeight.php b/src/Rule/Upload/ImageHeight.php index e933ecd..4ce2c07 100644 --- a/src/Rule/Upload/ImageHeight.php +++ b/src/Rule/Upload/ImageHeight.php @@ -20,11 +20,11 @@ class ImageHeight extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!is_array($value) || !isset($value['tmp_name']) || !file_exists($value['tmp_name'])) { + if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { $this->success = false; } else { - $imageInfo = getimagesize($value['tmp_name']); - $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; + $imageInfo = getimagesize($value['tmp_name']); + $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; $this->success = $height && $height <= $this->options[self::OPTION_MAX] && $height >= $this->options[self::OPTION_MIN]; } diff --git a/src/Rule/Upload/ImageRatio.php b/src/Rule/Upload/ImageRatio.php index 2fd1b0b..df9ac77 100644 --- a/src/Rule/Upload/ImageRatio.php +++ b/src/Rule/Upload/ImageRatio.php @@ -37,14 +37,14 @@ protected function normalizeRatio($ratio) public function validate($value, $valueIdentifier = null) { $this->value = $value; - $ratio = $this->normalizeRatio($this->options[self::OPTION_RATIO]); - if (!is_array($value) || !isset($value['tmp_name']) || !file_exists($value['tmp_name'])) { + $ratio = $this->normalizeRatio($this->options[self::OPTION_RATIO]); + if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { $this->success = false; } elseif ($ratio == 0) { $this->success = true; } else { - $imageInfo = getimagesize($value['tmp_name']); - $actualRatio = $imageInfo[0] / $imageInfo[1]; + $imageInfo = getimagesize($value['tmp_name']); + $actualRatio = $imageInfo[0] / $imageInfo[1]; $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; } diff --git a/src/Rule/Upload/ImageWidth.php b/src/Rule/Upload/ImageWidth.php index 03439b0..1f6a08c 100644 --- a/src/Rule/Upload/ImageWidth.php +++ b/src/Rule/Upload/ImageWidth.php @@ -20,11 +20,11 @@ class ImageWidth extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!is_array($value) || !isset($value['tmp_name']) || !file_exists($value['tmp_name'])) { + if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { $this->success = false; } else { - $imageInfo = getimagesize($value['tmp_name']); - $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; + $imageInfo = getimagesize($value['tmp_name']); + $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; $this->success = $width && $width <= $this->options[self::OPTION_MAX] && $width >= $this->options[self::OPTION_MIN]; } diff --git a/src/Rule/Upload/Size.php b/src/Rule/Upload/Size.php index 9b49182..6eedd08 100644 --- a/src/Rule/Upload/Size.php +++ b/src/Rule/Upload/Size.php @@ -17,12 +17,12 @@ class Size extends AbstractRule protected function normalizeSize($size) { - $units = array('B' => 0, 'K' => 1, 'M' => 2, 'G' => 3); - $unit = strtoupper(substr($size, strlen($size) - 1, 1)); - if (!isset($units[$unit])) { + $units = array( 'B' => 0, 'K' => 1, 'M' => 2, 'G' => 3 ); + $unit = strtoupper(substr($size, strlen($size) - 1, 1)); + if ( ! isset($units[$unit])) { $normalizedSize = filter_var($size, FILTER_SANITIZE_NUMBER_INT); } else { - $size = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); + $size = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); $normalizedSize = $size * pow(1024, $units[$unit]); } @@ -32,11 +32,11 @@ protected function normalizeSize($size) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!is_array($value) || !isset($value['tmp_name']) || !file_exists($value['tmp_name'])) { + if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { $this->success = false; } else { - $fileSize = @filesize($value['tmp_name']); - $limit = $this->normalizeSize($this->options[self::OPTION_SIZE]); + $fileSize = @filesize($value['tmp_name']); + $limit = $this->normalizeSize($this->options[self::OPTION_SIZE]); $this->success = $fileSize && $fileSize <= $limit; } diff --git a/src/Rule/Url.php b/src/Rule/Url.php index 6179de7..463e010 100755 --- a/src/Rule/Url.php +++ b/src/Rule/Url.php @@ -9,8 +9,8 @@ class Url extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; - $this->success = (bool)filter_var($value, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED); + $this->value = $value; + $this->success = (bool) filter_var($value, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED); return $this->success; } diff --git a/src/Rule/Website.php b/src/Rule/Website.php index e15210d..abfa848 100755 --- a/src/Rule/Website.php +++ b/src/Rule/Website.php @@ -11,9 +11,9 @@ class Website extends AbstractRule public function validate($value, $valueIdentifier = null) { - $this->value = $value; + $this->value = $value; $this->success = (substr($value, 0, 2) == '//') - || (preg_match(static::WEBSITE_REGEX, $value) && filter_var( + || (preg_match(static::WEBSITE_REGEX, $value) && filter_var( $value, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED diff --git a/src/RuleFactory.php b/src/RuleFactory.php index 13fc732..2565645 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -87,9 +87,9 @@ protected function registerDefaultRules() 'Upload\Size', ); foreach ($rulesClasses as $class) { - $fullClassName = '\\' . __NAMESPACE__ . '\Rule\\' . $class; - $name = strtolower(str_replace('\\', '', $class)); - $errorMessage = constant($fullClassName . '::MESSAGE'); + $fullClassName = '\\' . __NAMESPACE__ . '\Rule\\' . $class; + $name = strtolower(str_replace('\\', '', $class)); + $errorMessage = constant($fullClassName . '::MESSAGE'); $labeledErrorMessage = constant($fullClassName . '::LABELED_MESSAGE'); $this->register($name, $fullClassName, $errorMessage, $labeledErrorMessage); } @@ -101,6 +101,7 @@ protected function registerDefaultRules() * * @param string $name * @param string $class + * * @return \Sirius\Validation\RuleFactory */ public function register($name, $class, $errorMessage = '', $labeledErrorMessage = '') @@ -129,6 +130,7 @@ public function register($name, $class, $errorMessage = '', $labeledErrorMessage * error message template * @param string $label * label of the form input field or model attribute + * * @throws \InvalidArgumentException * @return \Sirius\Validation\Rule\AbstractValidator */ @@ -137,8 +139,8 @@ public function createRule($name, $options = null, $messageTemplate = null, $lab $validator = $this->construcRuleByNameAndOptions($name, $options); // no message template, try to get it from the registry - if (!$messageTemplate) { - $messageTemplate = $this->getSuggestedMessageTemplate($name, !!$label); + if ( ! $messageTemplate) { + $messageTemplate = $this->getSuggestedMessageTemplate($name, ! ! $label); } if (is_string($messageTemplate) && $messageTemplate !== '') { @@ -160,13 +162,15 @@ public function createRule($name, $options = null, $messageTemplate = null, $lab * * @return $this */ - public function setMessages($rule, $messageWithoutLabel = null, $messageWithLabel = null) { + public function setMessages($rule, $messageWithoutLabel = null, $messageWithLabel = null) + { if ($messageWithoutLabel) { $this->errorMessages[$rule] = $messageWithoutLabel; } if ($messageWithLabel) { $this->labeledErrorMessages[$rule] = $messageWithLabel; } + return $this; } @@ -176,6 +180,7 @@ public function setMessages($rule, $messageWithoutLabel = null, $messageWithLabe * * @param string $name name of the rule * @param bool $withLabel + * * @return string|NULL */ protected function getSuggestedMessageTemplate($name, $withLabel) @@ -219,9 +224,9 @@ protected function construcRuleByNameAndOptions($name, $options) } } - if (!isset($validator)) { + if ( ! isset($validator)) { throw new \InvalidArgumentException( - sprintf('Impossible to determine the validator based on the name: %s', (string)$name) + sprintf('Impossible to determine the validator based on the name: %s', (string) $name) ); } diff --git a/src/Util/Arr.php b/src/Util/Arr.php index f11d09c..c7b9cca 100644 --- a/src/Util/Arr.php +++ b/src/Util/Arr.php @@ -12,22 +12,23 @@ class Arr /** * @param $selector + * * @return array */ protected static function getSelectorParts($selector) { $firstOpen = strpos($selector, '['); if ($firstOpen === false) { - return array($selector, ''); + return array( $selector, '' ); } - $firstClose = strpos($selector, ']'); - $container = substr($selector, 0, $firstOpen); + $firstClose = strpos($selector, ']'); + $container = substr($selector, 0, $firstOpen); $subselector = substr($selector, $firstOpen + 1, $firstClose - $firstOpen - 1) . substr( $selector, $firstClose + 1 ); - return array($container, $subselector); + return array( $container, $subselector ); } /** @@ -39,12 +40,13 @@ protected static function getSelectorParts($selector) * * @param array $array * @param string $path + * * @return mixed */ public static function getByPath($array, $path = self::PATH_ROOT) { $path = trim($path); - if (!$path || $path == self::PATH_ROOT) { + if ( ! $path || $path == self::PATH_ROOT) { return $array; } // fix the path in case it was provided as `[item][subitem]` @@ -72,6 +74,7 @@ public static function getByPath($array, $path = self::PATH_ROOT) * @param string $selector * @param mixed $value * @param bool $overwrite true if the $value should overwrite the existing value + * * @return array */ public static function setBySelector($array, $selector, $value, $overwrite = false) @@ -79,13 +82,13 @@ public static function setBySelector($array, $selector, $value, $overwrite = fal // make sure the array is an array in case we got here through a subsequent call // so arraySetElementBySelector(array(), 'item[subitem]', 'value'); // will call arraySetElementBySelector(null, 'subitem', 'value'); - if (!is_array($array)) { + if ( ! is_array($array)) { $array = array(); } list($container, $subselector) = self::getSelectorParts($selector); - if (!$subselector) { + if ( ! $subselector) { if ($container !== '*') { - if ($overwrite === true || !array_key_exists($container, $array)) { + if ($overwrite === true || ! array_key_exists($container, $array)) { $array[$container] = $value; } } @@ -94,7 +97,7 @@ public static function setBySelector($array, $selector, $value, $overwrite = fal } // if we have a subselector the $array[$container] must be an array - if ($container !== '*' && !array_key_exists($container, $array)) { + if ($container !== '*' && ! array_key_exists($container, $array)) { $array[$container] = array(); } // we got here through something like *[subitem] @@ -119,6 +122,7 @@ public static function setBySelector($array, $selector, $value, $overwrite = fal * * @param $array * @param $selector + * * @return array */ public static function getBySelector($array, $selector) @@ -132,11 +136,11 @@ public static function getBySelector($array, $selector) list($preffix, $suffix) = explode('[*]', $selector, 2); $base = self::getByPath($array, $preffix); - if (!is_array($base)) { + if ( ! is_array($base)) { $base = array(); } // we don't have a suffix, the selector was something like path[subpath][*] - if (!$suffix) { + if ( ! $suffix) { foreach ($base as $k => $v) { $result["{$preffix}[{$k}]"] = $v; } diff --git a/src/Validator.php b/src/Validator.php index bc4a798..a97d1b1 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -127,11 +127,11 @@ class Validator implements ValidatorInterface public function __construct(RuleFactory $ruleFactory = null, ErrorMessage $errorMessagePrototype = null) { - if (!$ruleFactory) { + if ( ! $ruleFactory) { $ruleFactory = new RuleFactory(); } $this->ruleFactory = $ruleFactory; - if (!$errorMessagePrototype) { + if ( ! $errorMessagePrototype) { $errorMessagePrototype = new ErrorMessage(); } $this->errorMessagePrototype = $errorMessagePrototype; @@ -202,7 +202,7 @@ public function add($selector, $name = null, $options = null, $messageTemplate = { // the $selector is an associative array with $selector => $rules if (func_num_args() == 1) { - if (!is_array($selector)) { + if ( ! is_array($selector)) { throw new \InvalidArgumentException('If $selector is the only argument it must be an array'); } @@ -215,7 +215,7 @@ public function add($selector, $name = null, $options = null, $messageTemplate = } $this->ensureSelectorRulesExist($selector, $label); - call_user_func(array($this->rules[$selector], 'add'), $name, $options, $messageTemplate, $label); + call_user_func(array( $this->rules[$selector], 'add' ), $name, $options, $messageTemplate, $label); return $this; } @@ -230,7 +230,7 @@ public function addMultiple($selectorRulesCollection) foreach ($selectorRulesCollection as $selector => $rules) { // a single rule was passed for the $valueSelector - if (!is_array($rules)) { + if ( ! is_array($rules)) { return $this->add($selector, $rules); } @@ -263,11 +263,12 @@ public function addMultiple($selectorRulesCollection) * rule name or true if all rules should be deleted for that selector * @param mixed $options * rule options, necessary for rules that depend on params for their ID + * * @return self */ public function remove($selector, $name = true, $options = null) { - if (!array_key_exists($selector, $this->rules)) { + if ( ! array_key_exists($selector, $this->rules)) { return $this; } /* @var $collection \Sirius\Validation\ValueValidator */ @@ -282,12 +283,13 @@ public function remove($selector, $name = true, $options = null) * This way you can validate anything, not just arrays (which is the default) * * @param mixed $data + * * @return \Sirius\Validation\DataWrapper\WrapperInterface */ public function getDataWrapper($data = null) { // if $data is set reconstruct the data wrapper - if (!$this->dataWrapper || $data) { + if ( ! $this->dataWrapper || $data) { $this->dataWrapper = new DataWrapper\ArrayWrapper($data); } @@ -309,6 +311,7 @@ public function setData($data) * * @param mixed $data * array to be validated + * * @return boolean */ public function validate($data = null) @@ -323,7 +326,7 @@ public function validate($data = null) foreach ($this->rules as $selector => $valueValidator) { foreach ($this->getDataWrapper()->getItemsBySelector($selector) as $valueIdentifier => $value) { /* @var $valueValidator \Sirius\Validation\ValueValidator */ - if (!$valueValidator->validate($value, $valueIdentifier, $this->getDataWrapper())) { + if ( ! $valueValidator->validate($value, $valueIdentifier, $this->getDataWrapper())) { foreach ($valueValidator->getMessages() as $message) { $this->addMessage($valueIdentifier, $message); } @@ -339,6 +342,7 @@ public function validate($data = null) * @param string $item * data identifier (eg: 'email', 'addresses[0][state]') * @param string $message + * * @return self */ public function addMessage($item, $message = null) @@ -346,7 +350,7 @@ public function addMessage($item, $message = null) if ($message === null || $message === '') { return $this; } - if (!array_key_exists($item, $this->messages)) { + if ( ! array_key_exists($item, $this->messages)) { $this->messages[$item] = array(); } $this->messages[$item][] = $message; @@ -358,6 +362,7 @@ public function addMessage($item, $message = null) * Clears the messages of an item * * @param string $item + * * @return self */ public function clearMessages($item = null) @@ -376,6 +381,7 @@ public function clearMessages($item = null) /** * @param string $item * key of the messages array (eg: 'password', 'addresses[0][line_1]') + * * @return array */ public function getMessages($item = null) @@ -398,8 +404,9 @@ public function getRules() */ protected function ensureSelectorRulesExist($selector, $label = null) { - if (!isset($this->rules[$selector])) { - $this->rules[$selector] = new ValueValidator($this->getRuleFactory(), $this->getErroMessagePrototype(), $label); + if ( ! isset($this->rules[$selector])) { + $this->rules[$selector] = new ValueValidator($this->getRuleFactory(), $this->getErroMessagePrototype(), + $label); } } diff --git a/src/ValueValidator.php b/src/ValueValidator.php index fd0c29d..ba42a93 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -45,11 +45,11 @@ class ValueValidator function __construct(RuleFactory $ruleFactory = null, ErrorMessage $errorMessagePrototype = null, $label = null) { - if (!$ruleFactory) { + if ( ! $ruleFactory) { $ruleFactory = new RuleFactory(); } $this->ruleFactory = $ruleFactory; - if (!$errorMessagePrototype) { + if ( ! $errorMessagePrototype) { $errorMessagePrototype = new ErrorMessage(); } $this->errorMessagePrototype = $errorMessagePrototype; @@ -92,7 +92,7 @@ public function setLabel($label = null) */ public function add($name, $options = null, $messageTemplate = null, $label = null) { - if (is_array($name) && !is_callable($name)) { + if (is_array($name) && ! is_callable($name)) { return $this->addMultiple($name); } if (is_string($name)) { @@ -107,7 +107,7 @@ public function add($name, $options = null, $messageTemplate = null, $label = nu } // check for the default label - if (!$label && $this->label) { + if ( ! $label && $this->label) { $label = $this->label; } @@ -160,6 +160,7 @@ public function addRule(AbstractRule $validationRule) * rule name or true if all rules should be deleted for that selector * @param mixed $options * rule options, necessary for rules that depend on params for their ID + * * @throws \InvalidArgumentException * @internal param string $selector data selector * @return self @@ -190,19 +191,21 @@ public function remove($name = true, $options = null) * '{label} must have at least {min} characters', * 'Street' // label * ) + * * @param string $ruleAsString + * * @return array */ protected function parseRule($ruleAsString) { - $ruleAsString = trim($ruleAsString); - $options = array(); + $ruleAsString = trim($ruleAsString); + $options = array(); $messageTemplate = null; - $label = null; + $label = null; - $name = substr($ruleAsString, 0, strpos($ruleAsString, '(')); + $name = substr($ruleAsString, 0, strpos($ruleAsString, '(')); $ruleAsString = substr($ruleAsString, strpos($ruleAsString, '(')); - $matches = array(); + $matches = array(); preg_match_all('/\(([^\)]*)\)/', $ruleAsString, $matches); if (isset($matches[1])) { @@ -229,7 +232,7 @@ protected function parseRule($ruleAsString) public function validate($value, $valueIdentifier = null, DataWrapper\WrapperInterface $context = null) { $this->messages = array(); - $isRequired = false; + $isRequired = false; foreach ($this->rules as $rule) { if ($rule instanceof Rule\Required) { $isRequired = true; @@ -237,14 +240,14 @@ public function validate($value, $valueIdentifier = null, DataWrapper\WrapperInt } } - if (!$isRequired && $value === null) { + if ( ! $isRequired && $value === null) { return true; } /* @var $rule \Sirius\Validation\Rule\AbstractValidator */ foreach ($this->rules as $rule) { $rule->setContext($context); - if (!$rule->validate($value, $valueIdentifier)) { + if ( ! $rule->validate($value, $valueIdentifier)) { $this->addMessage($rule->getMessage()); } // if field is required and we have an error, diff --git a/tests/src/ComplexTest.php b/tests/src/ComplexTest.php index f00ee67..9b09146 100644 --- a/tests/src/ComplexTest.php +++ b/tests/src/ComplexTest.php @@ -15,7 +15,7 @@ function setUp() ->add('password', 'required') ->add('password_confirm', 'required | match(item=password)') ->add('feedback', 'requiredwith(item=agree_to_provide_feedback)') - ->add('birthday', 'requiredwhen', array('item' => 'email_confirm', 'rule' => 'Email')) + ->add('birthday', 'requiredwhen', array( 'item' => 'email_confirm', 'rule' => 'Email' )) // the lines below don't match the example but that's ok, // the individual rules have tests ->add('lines[*][price]', 'requiredwith(item=lines[*][quantity])'); @@ -32,7 +32,7 @@ function notestWithCorrectData() 'feedback' => 'This is great!', 'birthday' => '1980-01-01', 'lines' => array( - array('quantity' => 10, 'price' => 20) + array( 'quantity' => 10, 'price' => 20 ) ) ); $this->assertTrue($this->validator->validate($data)); @@ -46,16 +46,16 @@ function testWithInvalidData() 'password_confirm' => '123456', 'agree_to_provide_feedback' => true, 'lines' => array( - array('quantity' => 10, 'price' => null) + array( 'quantity' => 10, 'price' => null ) ) ); $this->validator->validate($data); $messages = $this->validator->getMessages(); - $this->assertEquals('This field is required', (string)$messages['email'][0]); - $this->assertEquals('This input does not match password', (string)$messages['password_confirm'][0]); - $this->assertEquals('This field is required', (string)$messages['feedback'][0]); - $this->assertEquals('This field is required', (string)$messages['lines[0][price]'][0]); + $this->assertEquals('This field is required', (string) $messages['email'][0]); + $this->assertEquals('This input does not match password', (string) $messages['password_confirm'][0]); + $this->assertEquals('This field is required', (string) $messages['feedback'][0]); + $this->assertEquals('This field is required', (string) $messages['lines[0][price]'][0]); } } diff --git a/tests/src/ErrorMessageTest.php b/tests/src/ErrorMessageTest.php index f7bb31b..f1a61bf 100644 --- a/tests/src/ErrorMessageTest.php +++ b/tests/src/ErrorMessageTest.php @@ -24,12 +24,12 @@ function setUp() function testErrorMessage() { $this->validator->add('email', 'email'); - $this->validator->validate(array('email' => 'not_an_email')); + $this->validator->validate(array( 'email' => 'not_an_email' )); $messages = $this->validator->getMessages('email'); $this->assertEquals(1, count($messages)); - $this->assertEquals('!!!This input must be a valid email address', (string)$messages[0]); + $this->assertEquals('!!!This input must be a valid email address', (string) $messages[0]); } diff --git a/tests/src/HelperTest.php b/tests/src/HelperTest.php index 4267590..9df95c3 100755 --- a/tests/src/HelperTest.php +++ b/tests/src/HelperTest.php @@ -453,7 +453,7 @@ function testOfNotRegex() function testOfEqualToWithContext() { - $pool = array( + $pool = array( array( 'value', 'element_1', @@ -560,7 +560,7 @@ function testOfIp() function testOfSetMaxSize() { - $set = array( + $set = array( 'element_1' => 'value', 'element_2' => 'another_value', 'element_3' => array( @@ -584,7 +584,7 @@ function testOfSetMaxSize() function testOfSetMinSize() { - $set = array( + $set = array( 'element_1' => 'value', 'element_2' => 'another_value', 'element_3' => array( @@ -608,7 +608,7 @@ function testOfSetMinSize() function testOfSetSize() { - $set = array( + $set = array( 'element_1' => 'value', 'element_2' => 'another_value', 'element_3' => array( diff --git a/tests/src/Rule/AbstractValidatorTest.php b/tests/src/Rule/AbstractValidatorTest.php index 4719188..d4e356c 100755 --- a/tests/src/Rule/AbstractValidatorTest.php +++ b/tests/src/Rule/AbstractValidatorTest.php @@ -7,8 +7,8 @@ class FakeRule extends \Sirius\Validation\Rule\AbstractRule function validate($value, $valueIdentifier = null) { - $this->value = $value; - $this->success = (bool)$value && isset($this->context) && $this->context->getItemValue('key'); + $this->value = $value; + $this->success = (bool) $value && isset($this->context) && $this->context->getItemValue('key'); return $this->success; } @@ -29,7 +29,7 @@ function testErrorMessagePrototype() $this->assertTrue($this->rule->getErrorMessagePrototype() instanceof \Sirius\Validation\ErrorMessage); $proto = new \Sirius\Validation\ErrorMessage('Not valid'); $this->rule->setErrorMessagePrototype($proto); - $this->assertEquals('Not valid', (string)$this->rule->getErrorMessagePrototype()); + $this->assertEquals('Not valid', (string) $this->rule->getErrorMessagePrototype()); } function testMessageIsGeneratedCorrectly() @@ -37,12 +37,12 @@ function testMessageIsGeneratedCorrectly() $this->rule->setOption('label', 'Accept'); $this->rule->setMessageTemplate('Field "{label}" must be true, {value} was provided'); $this->rule->validate('false'); - $this->assertEquals('Field "Accept" must be true, false was provided', (string)$this->rule->getMessage()); + $this->assertEquals('Field "Accept" must be true, false was provided', (string) $this->rule->getMessage()); } function testNoMessageWhenValidationPasses() { - $this->rule->setContext(array('key' => true)); + $this->rule->setContext(array( 'key' => true )); $this->assertTrue($this->rule->validate(true)); $this->assertNull($this->rule->getMessage()); } @@ -50,14 +50,14 @@ function testNoMessageWhenValidationPasses() function testContext() { $this->assertFalse($this->rule->validate(true)); - $this->rule->setContext(array('key' => true)); + $this->rule->setContext(array( 'key' => true )); $this->assertTrue($this->rule->validate(true)); } function testErrorMessageTemplateIsUsed() { $this->rule->setMessageTemplate('Custom message'); - $this->assertEquals('Custom message', (string)$this->rule->getPotentialMessage()); + $this->assertEquals('Custom message', (string) $this->rule->getPotentialMessage()); } function testErrorThrownOnInvalidContext() diff --git a/tests/src/Rule/CallbackTest.php b/tests/src/Rule/CallbackTest.php index cb6a32b..998c2fd 100644 --- a/tests/src/Rule/CallbackTest.php +++ b/tests/src/Rule/CallbackTest.php @@ -29,17 +29,17 @@ function testGetUniqueIdForCallbacksAsStrings() function testGetUniqueIdForCallbacksAsArrays() { - $this->rule->setOption(Rule::OPTION_CALLBACK, array('Class', 'method')); + $this->rule->setOption(Rule::OPTION_CALLBACK, array( 'Class', 'method' )); $this->assertTrue(strpos($this->rule->getUniqueId(), '|Class::method') !== false); - $this->rule->setOption(Rule::OPTION_CALLBACK, array($this, 'setUp')); + $this->rule->setOption(Rule::OPTION_CALLBACK, array( $this, 'setUp' )); $this->assertTrue(strpos($this->rule->getUniqueId(), '->setUp') !== false); } function testGetUniqueIdForCallbacksWithArguments() { $this->rule->setOption(Rule::OPTION_CALLBACK, 'is_int'); - $this->rule->setOption(Rule::OPTION_ARGUMENTS, array('b' => 2, 'a' => 1)); + $this->rule->setOption(Rule::OPTION_ARGUMENTS, array( 'b' => 2, 'a' => 1 )); // arguments should be sorted by key so test for that too $this->assertTrue(strpos($this->rule->getUniqueId(), '|{"a":1,"b":2}') !== false); diff --git a/tests/src/Rule/File/ExtensionTest.php b/tests/src/Rule/File/ExtensionTest.php index a0f9b2c..60ac725 100644 --- a/tests/src/Rule/File/ExtensionTest.php +++ b/tests/src/Rule/File/ExtensionTest.php @@ -12,14 +12,14 @@ function setUp() function testExistingFiles() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; $this->assertTrue($this->validator->validate($file)); } function testMissingFiles() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; $this->assertFalse($this->validator->validate($file)); } @@ -33,11 +33,11 @@ function testSetOptionAsString() function testPotentialMessage() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg', 'png')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); $this->validator->validate('no_file.jpg'); $this->assertEquals( 'The file does not have an acceptable extension (JPG, PNG)', - (string)$this->validator->getPotentialMessage() + (string) $this->validator->getPotentialMessage() ); } } diff --git a/tests/src/Rule/File/ImageHeightTest.php b/tests/src/Rule/File/ImageHeightTest.php index e93b0b9..3c326b7 100644 --- a/tests/src/Rule/File/ImageHeightTest.php +++ b/tests/src/Rule/File/ImageHeightTest.php @@ -7,7 +7,7 @@ class ImageHeightTest extends \PHPUnit_Framework_TestCase function setUp() { - $this->validator = new ImageHeight(array('min' => 400)); + $this->validator = new ImageHeight(array( 'min' => 400 )); } function testMissingFiles() diff --git a/tests/src/Rule/File/ImageRatioTest.php b/tests/src/Rule/File/ImageRatioTest.php index 57d1313..d183a92 100644 --- a/tests/src/Rule/File/ImageRatioTest.php +++ b/tests/src/Rule/File/ImageRatioTest.php @@ -7,7 +7,7 @@ class ImageRatioTest extends \PHPUnit_Framework_TestCase function setUp() { - $this->validator = new ImageRatio(array('ratio' => 1)); + $this->validator = new ImageRatio(array( 'ratio' => 1 )); } function testMissingFiles() diff --git a/tests/src/Rule/File/ImageTest.php b/tests/src/Rule/File/ImageTest.php index ad1cc32..31012b6 100644 --- a/tests/src/Rule/File/ImageTest.php +++ b/tests/src/Rule/File/ImageTest.php @@ -18,14 +18,14 @@ function testMissingFiles() function testRealImage() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; $this->assertTrue($this->validator->validate($file)); } function testFakeImage() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'fake_jpeg_file.jpg'; $this->assertFalse($this->validator->validate($file)); } @@ -39,11 +39,11 @@ function testExtensionsAsString() function testPotentialMessage() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg', 'png')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); $this->validator->validate('no_file.jpg'); $this->assertEquals( 'The file is not a valid image (only JPG, PNG are allowed)', - (string)$this->validator->getPotentialMessage() + (string) $this->validator->getPotentialMessage() ); } } diff --git a/tests/src/Rule/File/ImageWidthTest.php b/tests/src/Rule/File/ImageWidthTest.php index 7d3602a..e49720f 100644 --- a/tests/src/Rule/File/ImageWidthTest.php +++ b/tests/src/Rule/File/ImageWidthTest.php @@ -7,7 +7,7 @@ class ImageWidthTest extends \PHPUnit_Framework_TestCase function setUp() { - $this->validator = new ImageWidth(array('min' => 500)); + $this->validator = new ImageWidth(array( 'min' => 500 )); } function testMissingFiles() diff --git a/tests/src/Rule/File/SizeTest.php b/tests/src/Rule/File/SizeTest.php index f0270b0..5511ae2 100644 --- a/tests/src/Rule/File/SizeTest.php +++ b/tests/src/Rule/File/SizeTest.php @@ -7,7 +7,7 @@ class SizeTest extends \PHPUnit_Framework_TestCase function setUp() { - $this->validator = new Size(array('size' => '1M')); + $this->validator = new Size(array( 'size' => '1M' )); } function testMissingFiles() diff --git a/tests/src/Rule/LessThanTest.php b/tests/src/Rule/LessThanTest.php index 9ef5726..090f506 100755 --- a/tests/src/Rule/LessThanTest.php +++ b/tests/src/Rule/LessThanTest.php @@ -24,7 +24,8 @@ function testValidationWithoutALimit() $this->assertTrue($this->rule->validate(0)); } - function testOptionNormalizationForHttpQueryString() { + function testOptionNormalizationForHttpQueryString() + { $this->rule = new Rule('max=100&inclusive=false'); $this->assertFalse($this->rule->validate(100)); @@ -32,12 +33,14 @@ function testOptionNormalizationForHttpQueryString() { $this->assertTrue($this->rule->validate(100)); } - function testOptionNormalizationForJsonString() { + function testOptionNormalizationForJsonString() + { $this->rule = new Rule('{"max": 100, "inclusive": false}'); $this->assertFalse($this->rule->validate(100)); } - function testOptionNormalizationForCsvString() { + function testOptionNormalizationForCsvString() + { $this->rule = new Rule('100,false'); $this->assertFalse($this->rule->validate(100)); diff --git a/tests/src/Rule/RequiredWithTest.php b/tests/src/Rule/RequiredWithTest.php index db953e0..6d25729 100644 --- a/tests/src/Rule/RequiredWithTest.php +++ b/tests/src/Rule/RequiredWithTest.php @@ -45,8 +45,8 @@ function testValidationWithDeepItems() $this->rule->setContext(new ArrayWrapper( array( 'lines' => array( - 0 => array('quantity' => 10, 'price' => 10), - 1 => array('quantity' => 20, 'price' => null), + 0 => array( 'quantity' => 10, 'price' => 10 ), + 1 => array( 'quantity' => 20, 'price' => null ), ) )) ); diff --git a/tests/src/Rule/RequiredWithoutTest.php b/tests/src/Rule/RequiredWithoutTest.php index 1a2666e..2aed988 100644 --- a/tests/src/Rule/RequiredWithoutTest.php +++ b/tests/src/Rule/RequiredWithoutTest.php @@ -45,8 +45,8 @@ function testValidationWithDeepItems() $this->rule->setContext(new ArrayWrapper( array( 'lines' => array( - 0 => array('quantity' => null, 'price' => null), - 1 => array('quantity' => 20, 'price' => null), + 0 => array( 'quantity' => null, 'price' => null ), + 1 => array( 'quantity' => 20, 'price' => null ), ) )) ); diff --git a/tests/src/Rule/Upload/ExtensionTest.php b/tests/src/Rule/Upload/ExtensionTest.php index 23c4a73..abff3ab 100644 --- a/tests/src/Rule/Upload/ExtensionTest.php +++ b/tests/src/Rule/Upload/ExtensionTest.php @@ -12,9 +12,9 @@ function setUp() function testExistingFiles() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); $fileName = 'real_jpeg_file.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -26,9 +26,9 @@ function testExistingFiles() function testMissingFiles() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); $fileName = 'file_that_does_not_exist.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -42,7 +42,7 @@ function testSetOptionAsString() { $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, 'jpg, GIF'); $fileName = 'real_jpeg_file.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -54,10 +54,10 @@ function testSetOptionAsString() function testPotentialMessage() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg', 'png')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); $this->assertEquals( 'The file does not have an acceptable extension (JPG, PNG)', - (string)$this->validator->getPotentialMessage() + (string) $this->validator->getPotentialMessage() ); } } diff --git a/tests/src/Rule/Upload/ImageHeightTest.php b/tests/src/Rule/Upload/ImageHeightTest.php index 8937d7f..139c75f 100644 --- a/tests/src/Rule/Upload/ImageHeightTest.php +++ b/tests/src/Rule/Upload/ImageHeightTest.php @@ -7,13 +7,13 @@ class ImageHeightTest extends \PHPUnit_Framework_TestCase function setUp() { - $this->validator = new ImageHeight(array('min' => 400)); + $this->validator = new ImageHeight(array( 'min' => 400 )); } function testMissingFiles() { $fileName = 'file_that_does_not_exist.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -26,7 +26,7 @@ function testMissingFiles() function testFile() { $fileName = 'real_jpeg_file.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -36,7 +36,7 @@ function testFile() $this->assertTrue($this->validator->validate($file)); $fileName = 'square_image.gif'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', diff --git a/tests/src/Rule/Upload/ImageRatioTest.php b/tests/src/Rule/Upload/ImageRatioTest.php index f34d079..9c10f43 100644 --- a/tests/src/Rule/Upload/ImageRatioTest.php +++ b/tests/src/Rule/Upload/ImageRatioTest.php @@ -7,13 +7,13 @@ class ImageRatioTest extends \PHPUnit_Framework_TestCase function setUp() { - $this->validator = new ImageRatio(array('ratio' => 1)); + $this->validator = new ImageRatio(array( 'ratio' => 1 )); } function testMissingFiles() { $fileName = 'file_that_does_not_exist.gif'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -26,7 +26,7 @@ function testMissingFiles() function testSquare() { $fileName = 'square_image.gif'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -39,7 +39,7 @@ function testSquare() function testAlmostSquare() { $fileName = 'almost_square_image.gif'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -57,7 +57,7 @@ function testRatioZero() { $this->validator->setOption(ImageRatio::OPTION_RATIO, 0); $fileName = 'almost_square_image.gif'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -71,7 +71,7 @@ function testInvalidRatio() { $this->validator->setOption(ImageRatio::OPTION_RATIO, 'abc'); $fileName = 'almost_square_image.gif'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -85,7 +85,7 @@ function testRatioAsString() { $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); $fileName = '4_by_3_image.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', diff --git a/tests/src/Rule/Upload/ImageTest.php b/tests/src/Rule/Upload/ImageTest.php index 4c2b99b..dbf01ee 100644 --- a/tests/src/Rule/Upload/ImageTest.php +++ b/tests/src/Rule/Upload/ImageTest.php @@ -13,7 +13,7 @@ function setUp() function testMissingFiles() { $fileName = 'file_that_does_not_exist.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -25,9 +25,9 @@ function testMissingFiles() function testRealImage() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); $fileName = 'real_jpeg_file.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -39,9 +39,9 @@ function testRealImage() function testFakeImage() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); $fileName = 'fake_jpeg_file.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -55,7 +55,7 @@ function testExtensionsAsString() { $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, 'GIF, jpg'); $fileName = 'real_jpeg_file.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -67,10 +67,10 @@ function testExtensionsAsString() function testPotentialMessage() { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array('jpg', 'png')); + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); $this->assertEquals( 'The file is not a valid image (only JPG, PNG are allowed)', - (string)$this->validator->getPotentialMessage() + (string) $this->validator->getPotentialMessage() ); } } diff --git a/tests/src/Rule/Upload/ImageWidthTest.php b/tests/src/Rule/Upload/ImageWidthTest.php index a7de83b..3f444be 100644 --- a/tests/src/Rule/Upload/ImageWidthTest.php +++ b/tests/src/Rule/Upload/ImageWidthTest.php @@ -7,13 +7,13 @@ class ImageWidthTest extends \PHPUnit_Framework_TestCase function setUp() { - $this->validator = new ImageWidth(array('min' => 500)); + $this->validator = new ImageWidth(array( 'min' => 500 )); } function testMissingFiles() { $fileName = 'file_that_does_not_exist.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -26,7 +26,7 @@ function testMissingFiles() function testFile() { $fileName = 'real_jpeg_file.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -36,7 +36,7 @@ function testFile() $this->assertTrue($this->validator->validate($file)); $fileName = 'square_image.gif'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', diff --git a/tests/src/Rule/Upload/SizeTest.php b/tests/src/Rule/Upload/SizeTest.php index 35546a9..20ed7a8 100644 --- a/tests/src/Rule/Upload/SizeTest.php +++ b/tests/src/Rule/Upload/SizeTest.php @@ -7,13 +7,13 @@ class SizeTest extends \PHPUnit_Framework_TestCase function setUp() { - $this->validator = new Size(array('size' => '1M')); + $this->validator = new Size(array( 'size' => '1M' )); } function testMissingFiles() { $fileName = 'file_that_does_not_exist.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -26,7 +26,7 @@ function testMissingFiles() function testFile() { $fileName = 'real_jpeg_file.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', @@ -43,7 +43,7 @@ function testFile() function testSizeAsNumber() { $fileName = 'real_jpeg_file.jpg'; - $file = array( + $file = array( 'name' => $fileName, 'type' => 'not_required', 'size' => 'not_required', diff --git a/tests/src/RuleFactoryTest.php b/tests/src/RuleFactoryTest.php index 95611a1..ec43fe8 100644 --- a/tests/src/RuleFactoryTest.php +++ b/tests/src/RuleFactoryTest.php @@ -9,7 +9,7 @@ class TestingCustomRule extends AbstractRule function validate($value, $valueIdentifier = null) { - return (bool)($value % 2); + return (bool) ($value % 2); } } @@ -29,7 +29,7 @@ function testRegistrationOfValidatorClasses() $this->assertTrue($validator instanceof TestingCustomRule); $this->assertTrue($validator->validate(3)); $this->assertFalse($validator->validate(4)); - $this->assertEquals('Value is not valid', (string)$validator->getMessage()); + $this->assertEquals('Value is not valid', (string) $validator->getMessage()); } function testCustomErrorMessages() @@ -39,11 +39,11 @@ function testCustomErrorMessages() $validatorWithLabel = $this->ruleFactory->createRule('even', null, null, 'Number'); $validatorWithLabel->validate(4); - $this->assertEquals('Number should be even', (string)$validatorWithLabel->getMessage()); + $this->assertEquals('Number should be even', (string) $validatorWithLabel->getMessage()); $validator = $validator = $this->ruleFactory->createRule('even'); $validator->validate(4); - $this->assertEquals('This should be even', (string)$validator->getMessage()); + $this->assertEquals('This should be even', (string) $validator->getMessage()); } } diff --git a/tests/src/Util/ArrTest.php b/tests/src/Util/ArrTest.php index a6461a4..da5f75b 100644 --- a/tests/src/Util/ArrTest.php +++ b/tests/src/Util/ArrTest.php @@ -43,7 +43,7 @@ function testOfArraySetByPath() $this->assertEquals(Arr::getByPath($this->data, 'email'), 'my@domain.com'); $this->data = Arr::setBySelector($this->data, 'newsletters[offers]', true); - $this->assertEquals(Arr::getByPath($this->data, 'newsletters'), array('offers' => true)); + $this->assertEquals(Arr::getByPath($this->data, 'newsletters'), array( 'offers' => true )); $this->data = Arr::setBySelector($this->data, 'addresses[*][state]', 'California'); $this->assertEquals(Arr::getByPath($this->data, 'addresses[shipping][state]'), 'California'); $this->assertEquals(Arr::getByPath($this->data, 'addresses[billing][state]'), 'California'); @@ -92,8 +92,8 @@ function testOfArrayGetBySelectorUsingPath() { $arr = array( 'recipients' => array( - array('name' => 'John'), - array('name' => 'Marry', 'email' => 'marry@gmail.com') + array( 'name' => 'John' ), + array( 'name' => 'Marry', 'email' => 'marry@gmail.com' ) ) ); $this->assertEquals( @@ -114,7 +114,7 @@ function testOfArrayGetBySelectorWithEndingSelector() { $arr = array( 'lines' => array( - 'quantities' => array(1, 2, 3) + 'quantities' => array( 1, 2, 3 ) ) ); $this->assertEquals( @@ -131,7 +131,7 @@ function testOfArrayGetBySelectorWithWrongSelector() { $arr = array( 'lines' => array( - 'quantities' => array(1, 2, 3) + 'quantities' => array( 1, 2, 3 ) ) ); $this->assertEquals(array(), Arr::getBySelector($arr, 'recipients[*]')); From a4a69ed3551765d75ded498f274df8d18faa6613 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 11 Sep 2015 16:27:53 +0300 Subject: [PATCH 014/112] Added methods to retrieve the error message properties --- src/ErrorMessage.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/ErrorMessage.php b/src/ErrorMessage.php index db7a2b5..d85c8c8 100755 --- a/src/ErrorMessage.php +++ b/src/ErrorMessage.php @@ -23,6 +23,11 @@ public function setTemplate($template) return $this; } + public function getTemplate() + { + return $this->template; + } + public function setVariables($variables = array()) { foreach ($variables as $k => $v) { @@ -32,6 +37,11 @@ public function setVariables($variables = array()) return $this; } + public function getVariables() + { + return $this->variables; + } + public function __toString() { $result = $this->template; From 264fa166c92c8ec1bfdc81173400326e6d076c94 Mon Sep 17 00:00:00 2001 From: userlond Date: Sun, 8 Nov 2015 09:58:20 +0700 Subject: [PATCH 015/112] Update installation.md Fixed packagist name --- docs/installation.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/installation.md b/docs/installation.md index 86f9f0b..7dc2d9c 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -8,7 +8,7 @@ title: Installating Sirius\Validation Sirius\Validation is available on [Packagist](https://packagist.org/packages/siriusphp/validation) so you can use ``` -composer require sirius/validation +composer require siriusphp/validation ``` Make sure to include the Composer autoload file in your project @@ -18,4 +18,4 @@ require 'vendor/autoload.php'; ## Downloading a `.zip` file -This project is also available for download as a `.zip` file on GitHub. Visit the [releases page](https://github.com/siriusphp/validation/releases), select the version you want, and click the "Source code (zip)" download button. \ No newline at end of file +This project is also available for download as a `.zip` file on GitHub. Visit the [releases page](https://github.com/siriusphp/validation/releases), select the version you want, and click the "Source code (zip)" download button. From 6bb9e0ab857b367c5cc68a498f326b455791a2b8 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Sun, 22 Nov 2015 22:46:16 +0200 Subject: [PATCH 016/112] Docs changes --- docs/couscous.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/couscous.yml b/docs/couscous.yml index 049ec4e..fad4112 100644 --- a/docs/couscous.yml +++ b/docs/couscous.yml @@ -13,6 +13,8 @@ exclude: # Base URL of the published website (no "/" at the end!) # You are advised to set and use this variable to write your links in the HTML layouts baseUrl: http://www.sirius.ro/php/sirius/validation +paypal: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=SGXDKNJCXFPJU +gacode: UA-535999-18 projectName: Sirius\Validation title: Sirius\Validation From 52501e4813ae3eada5e447be54095bd6ab393bd3 Mon Sep 17 00:00:00 2001 From: Dan Date: Fri, 22 Jan 2016 16:23:25 +0000 Subject: [PATCH 017/112] Fixed the autoload call causing issues with Magento Varien Autoloader --- src/RuleFactory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/RuleFactory.php b/src/RuleFactory.php index 2565645..435c7b1 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -215,7 +215,7 @@ protected function construcRuleByNameAndOptions($name, $options) $name = $this->validatorsMap[strtolower($name)]; } // try if the validator is the name of a class in the package - if (class_exists('\Sirius\Validation\Rule\\' . $name)) { + if (class_exists('\Sirius\Validation\Rule\\' . $name, false)) { $name = '\Sirius\Validation\Rule\\' . $name; } // at this point we should have a class that can be instanciated From f98da573e9c0efe5c607a7dfde1a7cccb15310c4 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Sat, 23 Jan 2016 19:27:09 +0200 Subject: [PATCH 018/112] Update composer.json --- composer.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/composer.json b/composer.json index e8dad58..ba0087e 100755 --- a/composer.json +++ b/composer.json @@ -20,8 +20,7 @@ "php": ">=5.3" }, "require-dev": { - "phpunit/phpunit": "3.7", - "satooshi/php-coveralls": "dev-master" + "phpunit/phpunit": "3.7" }, "autoload": { "psr-4": { From 478c5ae365abb526484cf4b4dd1df46a70e763be Mon Sep 17 00:00:00 2001 From: Filis Date: Sun, 17 Apr 2016 17:51:45 +0200 Subject: [PATCH 019/112] comma added --- docs/simple_example.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/simple_example.md b/docs/simple_example.md index 1f45e6b..4f5f276 100644 --- a/docs/simple_example.md +++ b/docs/simple_example.md @@ -22,7 +22,7 @@ $validator->add( 'email:Your email' => 'required | email', // validators can have options - 'message:Your message' => 'required | minlength(10)' + 'message:Your message' => 'required | minlength(10)', // and you can overwrite the default error message 'phone:Phone' => 'regex(/your_regex_here/)(This field must be a valid US phone number)' @@ -47,4 +47,4 @@ if ($validator->validate($_POST)) { } ``` -Easy-peasy, right? \ No newline at end of file +Easy-peasy, right? From be7e2bc467135fe804199aabfbfa84971df8d3a6 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Sat, 23 Jul 2016 09:09:10 +0300 Subject: [PATCH 020/112] Fixes issue with rules RequiredWhen, RequiredWith and RequiredWithouth not returning false on empty strings --- src/Rule/RequiredWhen.php | 2 +- src/Rule/RequiredWith.php | 2 +- src/Rule/RequiredWithout.php | 2 +- tests/src/Rule/RequiredWhenTest.php | 4 ++++ tests/src/Rule/RequiredWithTest.php | 2 ++ tests/src/Rule/RequiredWithoutTest.php | 3 +++ 6 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/Rule/RequiredWhen.php b/src/Rule/RequiredWhen.php index 0964d39..5e2edcc 100644 --- a/src/Rule/RequiredWhen.php +++ b/src/Rule/RequiredWhen.php @@ -53,7 +53,7 @@ public function validate($value, $valueIdentifier = null) $itemRule = $this->getItemRule(); if ($itemRule->validate($relatedItemValue, $relatedItemPath)) { - $this->success = ($value !== null || trim($value) !== ''); + $this->success = ($value !== null && trim($value) !== ''); } else { $this->success = true; } diff --git a/src/Rule/RequiredWith.php b/src/Rule/RequiredWith.php index 3eaccfb..9e01b5a 100644 --- a/src/Rule/RequiredWith.php +++ b/src/Rule/RequiredWith.php @@ -20,7 +20,7 @@ public function validate($value, $valueIdentifier = null) $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; if (isset($this->options[self::OPTION_ITEM]) && $relatedItemValue !== null) { - $this->success = ($value !== null || trim($value) !== ''); + $this->success = ($value !== null && trim($value) !== ''); } else { $this->success = true; } diff --git a/src/Rule/RequiredWithout.php b/src/Rule/RequiredWithout.php index b6bc18e..e76c53d 100644 --- a/src/Rule/RequiredWithout.php +++ b/src/Rule/RequiredWithout.php @@ -20,7 +20,7 @@ public function validate($value, $valueIdentifier = null) $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; if (isset($this->options[self::OPTION_ITEM]) && $relatedItemValue === null) { - $this->success = ($value !== null || trim($value) !== ''); + $this->success = ($value !== null && trim($value) !== ''); } else { $this->success = true; } diff --git a/tests/src/Rule/RequiredWhenTest.php b/tests/src/Rule/RequiredWhenTest.php index aa5f975..bb1bf71 100644 --- a/tests/src/Rule/RequiredWhenTest.php +++ b/tests/src/Rule/RequiredWhenTest.php @@ -26,6 +26,7 @@ function testValidationWithItemValid() ); $this->assertTrue($this->rule->validate('abc')); $this->assertFalse($this->rule->validate(null)); + $this->assertFalse($this->rule->validate('')); } function testValidationWithItemNotValid() @@ -41,6 +42,7 @@ function testValidationWithItemNotValid() ); $this->assertTrue($this->rule->validate('abc')); $this->assertTrue($this->rule->validate(null)); + $this->assertTrue($this->rule->validate('')); } function testValidationWithoutItem() @@ -55,6 +57,7 @@ function testValidationWithoutItem() ); $this->assertTrue($this->rule->validate('abc')); $this->assertTrue($this->rule->validate(null)); + $this->assertTrue($this->rule->validate('')); } function testItemRuleSetAsRuleObject() @@ -70,6 +73,7 @@ function testItemRuleSetAsRuleObject() ); $this->assertTrue($this->rule->validate('abc')); $this->assertFalse($this->rule->validate(null)); + $this->assertFalse($this->rule->validate('')); } function testExceptionThrownOnInvalidItemRule() diff --git a/tests/src/Rule/RequiredWithTest.php b/tests/src/Rule/RequiredWithTest.php index 6d25729..8e0fd00 100644 --- a/tests/src/Rule/RequiredWithTest.php +++ b/tests/src/Rule/RequiredWithTest.php @@ -30,6 +30,7 @@ function testValidationWithItemPresent() $this->rule->setOption(Rule::OPTION_ITEM, 'item_1'); $this->assertTrue($this->rule->validate('abc')); $this->assertFalse($this->rule->validate(null)); + $this->assertFalse($this->rule->validate('')); } function testValidationWithoutItemPresent() @@ -52,6 +53,7 @@ function testValidationWithDeepItems() ); $this->assertTrue($this->rule->validate(10, 'lines[0][price]')); $this->assertFalse($this->rule->validate(null, 'lines[1][price]')); + $this->assertFalse($this->rule->validate('', 'lines[1][price]')); } } diff --git a/tests/src/Rule/RequiredWithoutTest.php b/tests/src/Rule/RequiredWithoutTest.php index 2aed988..788e9c0 100644 --- a/tests/src/Rule/RequiredWithoutTest.php +++ b/tests/src/Rule/RequiredWithoutTest.php @@ -30,6 +30,7 @@ function testValidationWithoutItemPresent() $this->rule->setOption(Rule::OPTION_ITEM, 'item_2'); $this->assertTrue($this->rule->validate('abc')); $this->assertFalse($this->rule->validate(null)); + $this->assertFalse($this->rule->validate('')); } function testValidationWithItemPresent() @@ -37,6 +38,7 @@ function testValidationWithItemPresent() $this->rule->setOption(Rule::OPTION_ITEM, 'item_1'); $this->assertTrue($this->rule->validate('abc')); $this->assertTrue($this->rule->validate(null)); + $this->assertTrue($this->rule->validate('')); } function testValidationWithDeepItems() @@ -52,5 +54,6 @@ function testValidationWithDeepItems() ); $this->assertFalse($this->rule->validate(null, 'lines[0][price]')); $this->assertTrue($this->rule->validate(null, 'lines[1][price]')); + $this->assertTrue($this->rule->validate('', 'lines[1][price]')); } } From 724d4592f73aa9452a8722464a295c4ced8c1570 Mon Sep 17 00:00:00 2001 From: Vincenzo Ciaccio Date: Sun, 27 Nov 2016 18:26:16 +0000 Subject: [PATCH 021/112] fixed bug on multipleAdd if rule is not array structure --- src/Validator.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Validator.php b/src/Validator.php index a97d1b1..38fda3c 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -231,7 +231,8 @@ public function addMultiple($selectorRulesCollection) // a single rule was passed for the $valueSelector if ( ! is_array($rules)) { - return $this->add($selector, $rules); + $this->add($selector, $rules); + continue; } // multiple rules were passed for the same $valueSelector From 183a666cf3eba25f829109076e975ff769f293a5 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 7 Dec 2016 08:03:42 +0200 Subject: [PATCH 022/112] Update readme.md --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 43e0fb7..ac86c0d 100755 --- a/readme.md +++ b/readme.md @@ -61,7 +61,7 @@ $validator->add('shipping_address[city]:City', 'MyApp\Validator\City'); // uses ##Links -- [documentation](http://www.sirius.ro/php/sirius/validation/) +- [documentation](http://sirius.ro/php/sirius/validation/) - [changelog](CHANGELOG.md) ##Known issues From 8cd9f7a6df5b9ca1e563618641e0804e78fd353d Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 25 Jan 2017 17:42:29 +0200 Subject: [PATCH 023/112] Added php7 ready badge --- readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/readme.md b/readme.md index ac86c0d..bd77943 100755 --- a/readme.md +++ b/readme.md @@ -4,6 +4,7 @@ [![Latest Version](https://img.shields.io/packagist/v/siriusphp/validation.svg?style=flat-square)](https://github.com/siriusphp/validation/releases) [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/siriusphp/validation/blob/master/LICENSE) [![Build Status](https://img.shields.io/travis/siriusphp/validation/master.svg?style=flat-square)](https://travis-ci.org/siriusphp/validation) +[![PHP 7 ready](http://php7ready.timesplinter.ch/siriusphp/validation/master/badge.svg)](https://travis-ci.org/siriusphp/validation) [![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/siriusphp/validation.svg?style=flat-square)](https://scrutinizer-ci.com/g/siriusphp/validation/code-structure) [![Quality Score](https://img.shields.io/scrutinizer/g/siriusphp/validation.svg?style=flat-square)](https://scrutinizer-ci.com/g/siriusphp/validation) [![Total Downloads](https://img.shields.io/packagist/dt/siriusphp/validation.svg?style=flat-square)](https://packagist.org/packages/siriusphp/validation) From 9bbb8c6729de8e32072c29f76fe07b08f145a4d4 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 24 Feb 2017 19:31:22 +0200 Subject: [PATCH 024/112] Fixed coding standard violations, added PHPCS to Travis --- .gitignore | 4 ++ .travis.yml | 2 + composer.json | 66 +++++++++++++++++----------- phpmd.xml | 28 ++++++++++++ src/DataWrapper/ArrayWrapper.php | 3 +- src/DataWrapper/WrapperInterface.php | 1 - src/Helper.php | 7 ++- src/Rule/AbstractRule.php | 37 ++++++++++------ src/Rule/AbstractStringRule.php | 9 ++-- src/Rule/Alpha.php | 1 - src/Rule/AlphaNumHyphen.php | 1 - src/Rule/AlphaNumeric.php | 1 - src/Rule/ArrayLength.php | 7 ++- src/Rule/ArrayMaxLength.php | 3 +- src/Rule/ArrayMinLength.php | 3 +- src/Rule/Between.php | 7 ++- src/Rule/Callback.php | 7 ++- src/Rule/Date.php | 17 ++++--- src/Rule/DateTime.php | 1 - src/Rule/Email.php | 1 - src/Rule/EmailDomain.php | 1 - src/Rule/Equal.php | 1 - src/Rule/File/Extension.php | 9 ++-- src/Rule/File/Image.php | 3 +- src/Rule/File/ImageHeight.php | 6 ++- src/Rule/File/ImageRatio.php | 2 +- src/Rule/File/ImageWidth.php | 6 ++- src/Rule/File/Size.php | 4 +- src/Rule/FullName.php | 1 - src/Rule/GreaterThan.php | 3 +- src/Rule/InList.php | 3 +- src/Rule/Integer.php | 1 - src/Rule/IpAddress.php | 1 - src/Rule/Length.php | 7 ++- src/Rule/LessThan.php | 3 +- src/Rule/Match.php | 1 - src/Rule/MaxLength.php | 3 +- src/Rule/MinLength.php | 3 +- src/Rule/NotInList.php | 3 +- src/Rule/NotRegex.php | 1 - src/Rule/Number.php | 1 - src/Rule/Regex.php | 1 - src/Rule/Required.php | 1 - src/Rule/RequiredWhen.php | 9 ++-- src/Rule/Time.php | 2 - src/Rule/Upload/Extension.php | 9 ++-- src/Rule/Upload/Image.php | 3 +- src/Rule/Upload/ImageHeight.php | 6 ++- src/Rule/Upload/ImageRatio.php | 2 +- src/Rule/Upload/ImageWidth.php | 6 ++- src/Rule/Upload/Size.php | 4 +- src/Rule/Url.php | 1 - src/Rule/Website.php | 9 ++-- src/RuleCollection.php | 3 -- src/RuleFactory.php | 13 +++--- src/Util/Arr.php | 16 +++---- src/Validator.php | 64 +++++++++++++++------------ src/ValidatorInterface.php | 1 - src/ValueValidator.php | 53 ++++++++++++---------- tests/src/HelperTest.php | 6 +-- 60 files changed, 262 insertions(+), 216 deletions(-) create mode 100644 phpmd.xml diff --git a/.gitignore b/.gitignore index c5048e4..77ee47a 100755 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,7 @@ composer.lock website/ docs/.couscous docs/couscous.phar +php-cs-fixer.phar +phpcbf.phar +phpcs.phar +phpmd.phar diff --git a/.travis.yml b/.travis.yml index 37fecbf..6dbf7ea 100755 --- a/.travis.yml +++ b/.travis.yml @@ -13,11 +13,13 @@ matrix: - php: 5.3 before_script: + - wget -c https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar - composer self-update - composer install --prefer-source script: - mkdir -p build/logs + - composer run-script phpcs - cd tests - phpunit diff --git a/composer.json b/composer.json index ba0087e..045340c 100755 --- a/composer.json +++ b/composer.json @@ -1,30 +1,44 @@ { - "name": "siriusphp/validation", - "description": "Data validation library. Validate arrays, array objects, domain models etc using a simple API. Easily add your own validators on top of the already dozens built-in validation rules", - "type": "library", - "license": "MIT", - "keywords": [ - "form", - "validation", - "sanitization", - "security", - "modeling" + "name": "siriusphp/validation", + "description": "Data validation library. Validate arrays, array objects, domain models etc using a simple API. Easily add your own validators on top of the already dozens built-in validation rules", + "type": "library", + "license": "MIT", + "keywords": [ + "form", + "validation", + "sanitization", + "security", + "modeling" + ], + "authors": [ + { + "name": "Adrian Miu", + "email": "adrian@adrianmiu.ro" + } + ], + "require": { + "php": ">=5.3" + }, + "require-dev": { + "phpunit/phpunit": "3.7" + }, + "autoload": { + "psr-4": { + "Sirius\\Validation\\": "src/" + } + }, + "scripts": { + "phpcs": [ + "php phpcs.phar --standard=PSR2 ./src" ], - "authors": [ - { - "name": "Adrian Miu", - "email": "adrian@adrianmiu.ro" - } + "phpmd": [ + "php phpmd.phar ./src xml phpmd.xml" ], - "require": { - "php": ">=5.3" - }, - "require-dev": { - "phpunit/phpunit": "3.7" - }, - "autoload": { - "psr-4": { - "Sirius\\Validation\\": "src/" - } - } + "phpcbf": [ + "php phpcbf.phar ./src --standard=PSR2 -w" + ], + "phpcsfix": [ + "php php-cs-fixer.phar fix ./src --rules=@PSR2" + ] + } } diff --git a/phpmd.xml b/phpmd.xml new file mode 100644 index 0000000..9294e77 --- /dev/null +++ b/phpmd.xml @@ -0,0 +1,28 @@ + + + Sirius PMD ruleset + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/DataWrapper/ArrayWrapper.php b/src/DataWrapper/ArrayWrapper.php index 5ae78e4..f64ad94 100644 --- a/src/DataWrapper/ArrayWrapper.php +++ b/src/DataWrapper/ArrayWrapper.php @@ -27,7 +27,7 @@ public function __construct($data = array()) $data = $data->toArray(); } } - if ( ! is_array($data)) { + if (! is_array($data)) { throw new \InvalidArgumentException('Data passed to validator is not an array or an ArrayObject'); } $this->data = $data; @@ -42,5 +42,4 @@ public function getItemsBySelector($selector) { return Arr::getBySelector($this->data, $selector); } - } diff --git a/src/DataWrapper/WrapperInterface.php b/src/DataWrapper/WrapperInterface.php index 331201b..5c0b24c 100644 --- a/src/DataWrapper/WrapperInterface.php +++ b/src/DataWrapper/WrapperInterface.php @@ -22,5 +22,4 @@ public function getItemValue($item); * @return array */ public function getItemsBySelector($selector); - } diff --git a/src/Helper.php b/src/Helper.php index ec09ae5..413d4bf 100755 --- a/src/Helper.php +++ b/src/Helper.php @@ -5,7 +5,6 @@ class Helper { - protected static $methods = array(); public static function addMethod($ruleName, $callback) @@ -199,7 +198,7 @@ public static function setSize($value, $min, $max) return $validator->validate($value); } - public static function in($value, $values) + public static function inList($value, $values) { $validator = new Rule\InList( array( @@ -210,7 +209,7 @@ public static function in($value, $values) return $validator->validate($value); } - public static function notIn($value, $values) + public static function notInList($value, $values) { $validator = new Rule\NotInList( array( @@ -306,7 +305,7 @@ public static function url($value) * * @return bool */ - public static function ip($value) + public static function ipAddress($value) { $validator = new Rule\IpAddress(); diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index 6a6ac57..71676a3 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -83,7 +83,7 @@ public function __construct($options = array()) */ protected function normalizeOptions($options) { - if ( ! $options) { + if (! $options) { return array(); } @@ -103,7 +103,7 @@ protected function normalizeOptions($options) } } - if ( ! is_array($result)) { + if (! is_array($result)) { throw new \InvalidArgumentException('Validator options should be an array, JSON string or query string'); } @@ -156,17 +156,22 @@ protected function convertBooleanStrings($v) */ protected function parseCsvString($str) { - if ( ! isset($this->optionsIndexMap) || ! is_array($this->optionsIndexMap) || empty($this->optionsIndexMap)) { - throw new \InvalidArgumentException(sprintf('Class %s is missing the `optionsIndexMap` property', - get_class($this))); + if (! isset($this->optionsIndexMap) || ! is_array($this->optionsIndexMap) || empty($this->optionsIndexMap)) { + throw new \InvalidArgumentException(sprintf( + 'Class %s is missing the `optionsIndexMap` property', + get_class($this) + )); } $options = explode(',', $str); $result = array(); foreach ($options as $k => $v) { - if ( ! isset($this->optionsIndexMap[$k])) { - throw new \InvalidArgumentException(sprintf('Class %s does not have the index %d configured in the `optionsIndexMap` property', - get_class($this), $k)); + if (! isset($this->optionsIndexMap[$k])) { + throw new \InvalidArgumentException(sprintf( + 'Class %s does not have the index %d configured in the `optionsIndexMap` property', + get_class($this), + $k + )); } $result[$this->optionsIndexMap[$k]] = $v; } @@ -250,9 +255,10 @@ public function setContext($context = null) if (is_array($context)) { $context = new ArrayWrapper($context); } - if ( ! is_object($context) || ! $context instanceof WrapperInterface) { + if (! is_object($context) || ! $context instanceof WrapperInterface) { throw new \InvalidArgumentException( - 'Validator context must be either an array or an instance of Sirius\Validator\DataWrapper\WrapperInterface' + 'Validator context must be either an array or an instance + of Sirius\Validator\DataWrapper\WrapperInterface' ); } $this->context = $context; @@ -299,7 +305,7 @@ public function getMessageTemplate() * * @return mixed */ - abstract function validate($value, $valueIdentifier = null); + abstract public function validate($value, $valueIdentifier = null); /** * Sets the error message prototype that will be used when returning the error message @@ -326,7 +332,7 @@ public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype) */ public function getErrorMessagePrototype() { - if ( ! $this->errorMessagePrototype) { + if (! $this->errorMessagePrototype) { $this->errorMessagePrototype = new ErrorMessage(); } @@ -405,8 +411,11 @@ protected function getRelatedValueIdentifier($valueIdentifier, $relatedItem) } $relatedValueIdentifier = implode('][', $relatedValueIdentifierParts) . ']'; - $relatedValueIdentifier = str_replace($relatedValueIdentifierParts[0] . ']', $relatedValueIdentifierParts[0], - $relatedValueIdentifier); + $relatedValueIdentifier = str_replace( + $relatedValueIdentifierParts[0] . ']', + $relatedValueIdentifierParts[0], + $relatedValueIdentifier + ); return $relatedValueIdentifier; } diff --git a/src/Rule/AbstractStringRule.php b/src/Rule/AbstractStringRule.php index 80b68c2..ba9ff4c 100644 --- a/src/Rule/AbstractStringRule.php +++ b/src/Rule/AbstractStringRule.php @@ -4,15 +4,16 @@ abstract class AbstractStringRule extends AbstractRule { - protected function getStringLength($str) { if (function_exists('mb_strlen')) { - return mb_strlen($str, + return mb_strlen( + $str, (isset($this->options['encoding']) && $this->options['encoding']) ? - $this->options['encoding'] : mb_internal_encoding()); + $this->options['encoding'] : mb_internal_encoding() + ); } return strlen($str); } -} \ No newline at end of file +} diff --git a/src/Rule/Alpha.php b/src/Rule/Alpha.php index ab4b799..60d901f 100755 --- a/src/Rule/Alpha.php +++ b/src/Rule/Alpha.php @@ -3,7 +3,6 @@ class Alpha extends AbstractRule { - const MESSAGE = 'This input can contain only letters'; const LABELED_MESSAGE = '{label} can contain only letters'; diff --git a/src/Rule/AlphaNumHyphen.php b/src/Rule/AlphaNumHyphen.php index 212f082..b6cd55b 100755 --- a/src/Rule/AlphaNumHyphen.php +++ b/src/Rule/AlphaNumHyphen.php @@ -3,7 +3,6 @@ class AlphaNumHyphen extends AbstractRule { - const MESSAGE = 'This input must contain only letters, digits, spaces, hyphens and underscores'; const LABELED_MESSAGE = '{label} must contain only letters, digits, spaces, hyphens and underscores'; diff --git a/src/Rule/AlphaNumeric.php b/src/Rule/AlphaNumeric.php index 14b6596..e663bf6 100755 --- a/src/Rule/AlphaNumeric.php +++ b/src/Rule/AlphaNumeric.php @@ -3,7 +3,6 @@ class AlphaNumeric extends AbstractRule { - const MESSAGE = 'This input must contain only letters and digits'; const LABELED_MESSAGE = '{label} must contain only letters and digits'; diff --git a/src/Rule/ArrayLength.php b/src/Rule/ArrayLength.php index 8b159c0..a3c8816 100755 --- a/src/Rule/ArrayLength.php +++ b/src/Rule/ArrayLength.php @@ -3,7 +3,6 @@ class ArrayLength extends AbstractRule { - const OPTION_MIN = 'min'; const OPTION_MAX = 'max'; @@ -29,9 +28,9 @@ public function validate($value, $valueIdentifier = null) $minValidator->setOption('min', $this->options['min']); } $this->success = $minValidator->validate($value, $valueIdentifier) && $maxValidator->validate( - $value, - $valueIdentifier - ); + $value, + $valueIdentifier + ); return $this->success; } diff --git a/src/Rule/ArrayMaxLength.php b/src/Rule/ArrayMaxLength.php index 868e24f..8875c19 100755 --- a/src/Rule/ArrayMaxLength.php +++ b/src/Rule/ArrayMaxLength.php @@ -3,7 +3,6 @@ class ArrayMaxLength extends AbstractRule { - const OPTION_MAX = 'max'; const MESSAGE = 'This input should contain less than {min} items'; @@ -19,7 +18,7 @@ class ArrayMaxLength extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! isset($this->options['max'])) { + if (! isset($this->options['max'])) { $this->success = true; } else { $this->success = is_array($value) && count($value) <= $this->options['max']; diff --git a/src/Rule/ArrayMinLength.php b/src/Rule/ArrayMinLength.php index b64ab08..77bf840 100755 --- a/src/Rule/ArrayMinLength.php +++ b/src/Rule/ArrayMinLength.php @@ -3,7 +3,6 @@ class ArrayMinLength extends AbstractRule { - const OPTION_MIN = 'min'; const MESSAGE = 'This input should contain at least {min} items'; @@ -18,7 +17,7 @@ class ArrayMinLength extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! isset($this->options['min'])) { + if (! isset($this->options['min'])) { $this->success = true; } else { $this->success = is_array($value) && count($value) >= $this->options['min']; diff --git a/src/Rule/Between.php b/src/Rule/Between.php index b1f392c..f029c55 100755 --- a/src/Rule/Between.php +++ b/src/Rule/Between.php @@ -3,7 +3,6 @@ class Between extends AbstractRule { - const OPTION_MIN = 'min'; const OPTION_MAX = 'max'; @@ -29,9 +28,9 @@ public function validate($value, $valueIdentifier = null) $maxValidator->setOption('min', $this->options['min']); } $this->success = $minValidator->validate($value, $valueIdentifier) && $maxValidator->validate( - $value, - $valueIdentifier - ); + $value, + $valueIdentifier + ); return $this->success; } diff --git a/src/Rule/Callback.php b/src/Rule/Callback.php index e4ce532..d6df15f 100755 --- a/src/Rule/Callback.php +++ b/src/Rule/Callback.php @@ -3,7 +3,6 @@ class Callback extends AbstractRule { - const OPTION_CALLBACK = 'callback'; const OPTION_ARGUMENTS = 'arguments'; @@ -23,8 +22,8 @@ public function getUniqueId() $uniqueId .= '|' . implode('::', $this->options['callback']); } elseif (is_object($this->options['callback'][0])) { $uniqueId .= '|' . spl_object_hash( - $this->options['callback'][0] - ) . '->' . $this->options['callback'][1]; + $this->options['callback'][0] + ) . '->' . $this->options['callback'][1]; } } elseif (is_object($this->options['callback']) && $this->options['callback'] instanceof \Closure) { $uniqueId .= '|' . spl_object_hash($this->options['callback']); @@ -42,7 +41,7 @@ public function getUniqueId() public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! isset($this->options['callback']) || ! is_callable($this->options['callback'])) { + if (! isset($this->options['callback']) || ! is_callable($this->options['callback'])) { $this->success = true; } else { $args = (isset($this->options['arguments'])) ? (array) $this->options['arguments'] : array(); diff --git a/src/Rule/Date.php b/src/Rule/Date.php index 36e730e..4eba3e4 100644 --- a/src/Rule/Date.php +++ b/src/Rule/Date.php @@ -3,7 +3,6 @@ class Date extends AbstractRule { - const OPTION_FORMAT = 'format'; const MESSAGE = 'This input must be a date having the format {format}'; @@ -21,8 +20,10 @@ class Date extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - $this->success = $value == date($this->options['format'], - $this->getTimestampFromFormatedString($value, $this->options['format'])); + $this->success = $value == date( + $this->options['format'], + $this->getTimestampFromFormatedString($value, $this->options['format']) + ); return $this->success; } @@ -31,7 +32,13 @@ protected function getTimestampFromFormatedString($string, $format) { $result = date_parse_from_format($format, $string); - return mktime((int) $result['hour'], (int) $result['minute'], (int) $result['second'], (int) $result['month'], - (int) $result['day'], (int) $result['year']); + return mktime( + (int) $result['hour'], + (int) $result['minute'], + (int) $result['second'], + (int) $result['month'], + (int) $result['day'], + (int) $result['year'] + ); } } diff --git a/src/Rule/DateTime.php b/src/Rule/DateTime.php index a48e7f7..d8b6391 100644 --- a/src/Rule/DateTime.php +++ b/src/Rule/DateTime.php @@ -3,7 +3,6 @@ class DateTime extends Date { - const MESSAGE = 'This input must be a date having the format {format}'; const LABELED_MESSAGE = '{label} must be a date having the format {format}'; diff --git a/src/Rule/Email.php b/src/Rule/Email.php index a86ac92..8d7d324 100755 --- a/src/Rule/Email.php +++ b/src/Rule/Email.php @@ -3,7 +3,6 @@ class Email extends AbstractRule { - const MESSAGE = 'This input must be a valid email address'; const LABELED_MESSAGE = '{label} must be a valid email address'; diff --git a/src/Rule/EmailDomain.php b/src/Rule/EmailDomain.php index 5c2113c..b851eaa 100755 --- a/src/Rule/EmailDomain.php +++ b/src/Rule/EmailDomain.php @@ -3,7 +3,6 @@ class EmailDomain extends AbstractRule { - const MESSAGE = 'This the email address does not belong to a valid domain'; const LABELED_MESSAGE = '{label} does not belong to a valid domain'; diff --git a/src/Rule/Equal.php b/src/Rule/Equal.php index d931162..87684e5 100644 --- a/src/Rule/Equal.php +++ b/src/Rule/Equal.php @@ -3,7 +3,6 @@ class Equal extends AbstractRule { - const OPTION_VALUE = 'value'; const MESSAGE = 'This input is not equal to {value}'; diff --git a/src/Rule/File/Extension.php b/src/Rule/File/Extension.php index 66a4a69..df31238 100644 --- a/src/Rule/File/Extension.php +++ b/src/Rule/File/Extension.php @@ -6,7 +6,6 @@ class Extension extends AbstractRule { - const OPTION_ALLOWED_EXTENSIONS = 'allowed'; const MESSAGE = 'The file does not have an acceptable extension ({file_extensions})'; @@ -33,14 +32,14 @@ public function setOption($name, $value) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! file_exists($value)) { + if (! file_exists($value)) { $this->success = false; } else { $extension = strtolower(substr($value, strrpos($value, '.') + 1, 10)); $this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array( - $extension, - $this->options[self::OPTION_ALLOWED_EXTENSIONS] - ); + $extension, + $this->options[self::OPTION_ALLOWED_EXTENSIONS] + ); } return $this->success; diff --git a/src/Rule/File/Image.php b/src/Rule/File/Image.php index bdca3e2..aa57e9a 100644 --- a/src/Rule/File/Image.php +++ b/src/Rule/File/Image.php @@ -6,7 +6,6 @@ class Image extends AbstractRule { - const OPTION_ALLOWED_IMAGES = 'allowed'; const MESSAGE = 'The file is not a valid image (only {image_types} are allowed)'; @@ -43,7 +42,7 @@ public function setOption($name, $value) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! file_exists($value)) { + if (! file_exists($value)) { $this->success = false; } else { $imageInfo = getimagesize($value); diff --git a/src/Rule/File/ImageHeight.php b/src/Rule/File/ImageHeight.php index e93e5ab..7e4a6e7 100644 --- a/src/Rule/File/ImageHeight.php +++ b/src/Rule/File/ImageHeight.php @@ -20,12 +20,14 @@ class ImageHeight extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! file_exists($value)) { + if (!file_exists($value)) { $this->success = false; } else { $imageInfo = getimagesize($value); $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; - $this->success = $height && $height <= $this->options[self::OPTION_MAX] && $height >= $this->options[self::OPTION_MIN]; + $this->success = $height && + $height <= $this->options[self::OPTION_MAX] && + $height >= $this->options[self::OPTION_MIN]; } return $this->success; diff --git a/src/Rule/File/ImageRatio.php b/src/Rule/File/ImageRatio.php index 8c76455..e058721 100644 --- a/src/Rule/File/ImageRatio.php +++ b/src/Rule/File/ImageRatio.php @@ -38,7 +38,7 @@ public function validate($value, $valueIdentifier = null) { $this->value = $value; $ratio = $this->normalizeRatio($this->options[self::OPTION_RATIO]); - if ( ! file_exists($value)) { + if (! file_exists($value)) { $this->success = false; } elseif ($ratio == 0) { $this->success = true; diff --git a/src/Rule/File/ImageWidth.php b/src/Rule/File/ImageWidth.php index 8d2ad0e..8d3cfed 100644 --- a/src/Rule/File/ImageWidth.php +++ b/src/Rule/File/ImageWidth.php @@ -20,12 +20,14 @@ class ImageWidth extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! file_exists($value)) { + if (! file_exists($value)) { $this->success = false; } else { $imageInfo = getimagesize($value); $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; - $this->success = $width && $width <= $this->options[self::OPTION_MAX] && $width >= $this->options[self::OPTION_MIN]; + $this->success = $width && + $width <= $this->options[self::OPTION_MAX] && + $width >= $this->options[self::OPTION_MIN]; } return $this->success; diff --git a/src/Rule/File/Size.php b/src/Rule/File/Size.php index 0a03ade..0312ccc 100644 --- a/src/Rule/File/Size.php +++ b/src/Rule/File/Size.php @@ -19,7 +19,7 @@ protected function normalizeSize($size) { $units = array( 'B' => 0, 'K' => 1, 'M' => 2, 'G' => 3 ); $unit = strtoupper(substr($size, strlen($size) - 1, 1)); - if ( ! isset($units[$unit])) { + if (! isset($units[$unit])) { $normalizedSize = filter_var($size, FILTER_SANITIZE_NUMBER_INT); } else { $size = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); @@ -32,7 +32,7 @@ protected function normalizeSize($size) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! file_exists($value)) { + if (! file_exists($value)) { $this->success = false; } else { $fileSize = @filesize($value); diff --git a/src/Rule/FullName.php b/src/Rule/FullName.php index 95d0b1b..2b96145 100755 --- a/src/Rule/FullName.php +++ b/src/Rule/FullName.php @@ -3,7 +3,6 @@ class FullName extends AbstractRule { - const MESSAGE = 'This input is not a valid full name (first name and last name)'; const LABELED_MESSAGE = '{label} is not a valid full name (first name and last name)'; diff --git a/src/Rule/GreaterThan.php b/src/Rule/GreaterThan.php index d665fbe..182e2b4 100755 --- a/src/Rule/GreaterThan.php +++ b/src/Rule/GreaterThan.php @@ -3,7 +3,6 @@ class GreaterThan extends AbstractRule { - const OPTION_MIN = 'min'; const OPTION_INCLUSIVE = 'inclusive'; @@ -22,7 +21,7 @@ class GreaterThan extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! isset($this->options['min'])) { + if (! isset($this->options['min'])) { $this->success = true; } else { if ($this->options['inclusive']) { diff --git a/src/Rule/InList.php b/src/Rule/InList.php index fead6a1..5975a51 100755 --- a/src/Rule/InList.php +++ b/src/Rule/InList.php @@ -4,7 +4,6 @@ class InList extends AbstractRule { - const OPTION_LIST = 'list'; const MESSAGE = 'This input is not one of the accepted values'; @@ -17,7 +16,7 @@ class InList extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! isset($this->options['list'])) { + if (! isset($this->options['list'])) { $this->success = true; } else { if (is_array($this->options['list'])) { diff --git a/src/Rule/Integer.php b/src/Rule/Integer.php index 264922e..158cb3d 100644 --- a/src/Rule/Integer.php +++ b/src/Rule/Integer.php @@ -3,7 +3,6 @@ class Integer extends AbstractRule { - const MESSAGE = 'This input must be an integer number'; const LABELED_MESSAGE = '{label} must be an integer number'; diff --git a/src/Rule/IpAddress.php b/src/Rule/IpAddress.php index d5a5077..855b384 100755 --- a/src/Rule/IpAddress.php +++ b/src/Rule/IpAddress.php @@ -3,7 +3,6 @@ class IpAddress extends AbstractRule { - const MESSAGE = 'This input is not a valid IP address'; const LABELED_MESSAGE = '{label} is not a valid IP address'; diff --git a/src/Rule/Length.php b/src/Rule/Length.php index 9e9d749..87bcc55 100755 --- a/src/Rule/Length.php +++ b/src/Rule/Length.php @@ -3,7 +3,6 @@ class Length extends AbstractRule { - const OPTION_MIN = 'min'; const OPTION_MAX = 'max'; const OPTION_ENCODING = 'encoding'; @@ -31,9 +30,9 @@ public function validate($value, $valueIdentifier = null) $minValidator->setOption('min', $this->options['min']); } $this->success = $minValidator->validate($value, $valueIdentifier) && $maxValidator->validate( - $value, - $valueIdentifier - ); + $value, + $valueIdentifier + ); return $this->success; } diff --git a/src/Rule/LessThan.php b/src/Rule/LessThan.php index 450407b..4fcd406 100755 --- a/src/Rule/LessThan.php +++ b/src/Rule/LessThan.php @@ -3,7 +3,6 @@ class LessThan extends AbstractRule { - const OPTION_MAX = 'max'; const OPTION_INCLUSIVE = 'inclusive'; @@ -22,7 +21,7 @@ class LessThan extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! isset($this->options['max'])) { + if (! isset($this->options['max'])) { $this->success = true; } else { if ($this->options['inclusive']) { diff --git a/src/Rule/Match.php b/src/Rule/Match.php index 3360efe..61c8c2f 100644 --- a/src/Rule/Match.php +++ b/src/Rule/Match.php @@ -3,7 +3,6 @@ class Match extends AbstractRule { - const OPTION_ITEM = 'item'; const MESSAGE = 'This input does not match {item}'; diff --git a/src/Rule/MaxLength.php b/src/Rule/MaxLength.php index 613483a..ef796b2 100755 --- a/src/Rule/MaxLength.php +++ b/src/Rule/MaxLength.php @@ -3,7 +3,6 @@ class MaxLength extends AbstractStringRule { - const OPTION_MAX = 'max'; const OPTION_ENCODING = 'encoding'; @@ -20,7 +19,7 @@ class MaxLength extends AbstractStringRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! isset($this->options['max'])) { + if (! isset($this->options['max'])) { $this->success = true; } else { $this->success = $this->getStringLength($value) <= $this->options['max']; diff --git a/src/Rule/MinLength.php b/src/Rule/MinLength.php index 72372d9..e470a39 100755 --- a/src/Rule/MinLength.php +++ b/src/Rule/MinLength.php @@ -3,7 +3,6 @@ class MinLength extends AbstractStringRule { - const OPTION_MIN = 'min'; const OPTION_ENCODING = 'encoding'; @@ -20,7 +19,7 @@ class MinLength extends AbstractStringRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! isset($this->options['min'])) { + if (! isset($this->options['min'])) { $this->success = true; } else { $this->success = $this->getStringLength($value) >= $this->options['min']; diff --git a/src/Rule/NotInList.php b/src/Rule/NotInList.php index fe2057f..00c5167 100755 --- a/src/Rule/NotInList.php +++ b/src/Rule/NotInList.php @@ -3,7 +3,6 @@ class NotInList extends InList { - const OPTION_LIST = 'list'; const MESSAGE = 'This input is one of the forbidden values'; @@ -16,7 +15,7 @@ class NotInList extends InList public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! isset($this->options['list'])) { + if (! isset($this->options['list'])) { $this->success = true; } else { if (is_array($this->options['list'])) { diff --git a/src/Rule/NotRegex.php b/src/Rule/NotRegex.php index 0930d12..abdfb9d 100755 --- a/src/Rule/NotRegex.php +++ b/src/Rule/NotRegex.php @@ -3,7 +3,6 @@ class NotRegex extends Regex { - const MESSAGE = 'This input should not match the regular expression {pattern}'; const LABELED_MESSAGE = '{label} Tshould not match the regular expression {pattern}'; diff --git a/src/Rule/Number.php b/src/Rule/Number.php index 235b920..e7d8d94 100644 --- a/src/Rule/Number.php +++ b/src/Rule/Number.php @@ -3,7 +3,6 @@ class Number extends AbstractRule { - const MESSAGE = 'This input must be a number'; const LABELED_MESSAGE = '{label} must be a number'; diff --git a/src/Rule/Regex.php b/src/Rule/Regex.php index 9c25355..1867b4e 100755 --- a/src/Rule/Regex.php +++ b/src/Rule/Regex.php @@ -3,7 +3,6 @@ class Regex extends AbstractRule { - const OPTION_PATTERN = 'pattern'; const MESSAGE = 'This input does not match the regular expression {pattern}'; diff --git a/src/Rule/Required.php b/src/Rule/Required.php index 55fe1c8..7f9012b 100755 --- a/src/Rule/Required.php +++ b/src/Rule/Required.php @@ -3,7 +3,6 @@ class Required extends AbstractRule { - const MESSAGE = 'This field is required'; const LABELED_MESSAGE = '{label} is required'; diff --git a/src/Rule/RequiredWhen.php b/src/Rule/RequiredWhen.php index 5e2edcc..2cf9b2c 100644 --- a/src/Rule/RequiredWhen.php +++ b/src/Rule/RequiredWhen.php @@ -14,7 +14,9 @@ public function getItemRule() { /* @var $rule AbstractValidator */ $rule = false; - $ruleOptions = (isset($this->options[self::OPTION_RULE_OPTIONS])) ? (array) $this->options[self::OPTION_RULE_OPTIONS] : array(); + $ruleOptions = (isset($this->options[self::OPTION_RULE_OPTIONS])) ? + (array) $this->options[self::OPTION_RULE_OPTIONS] : + array(); if (is_string($this->options[self::OPTION_RULE])) { $ruleClass = $this->options[self::OPTION_RULE]; @@ -29,7 +31,7 @@ public function getItemRule() ) { $rule = $this->options[self::OPTION_RULE]; } - if ( ! $rule) { + if (! $rule) { throw new \InvalidArgumentException( 'Validator for the other item is not valid or cannot be constructed based on the data provided' ); @@ -44,10 +46,9 @@ public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! isset($this->options[self::OPTION_ITEM])) { + if (! isset($this->options[self::OPTION_ITEM])) { $this->success = true; } else { - $relatedItemPath = $this->getRelatedValueIdentifier($valueIdentifier, $this->options[self::OPTION_ITEM]); $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; diff --git a/src/Rule/Time.php b/src/Rule/Time.php index de8ad09..b2d9c7d 100644 --- a/src/Rule/Time.php +++ b/src/Rule/Time.php @@ -4,12 +4,10 @@ class Time extends Date { - const MESSAGE = 'This input must be a time having the format {format}'; const LABELED_MESSAGE = '{label} must be a time having the format {format}'; protected $options = array( 'format' => 'H:i:s' ); - } diff --git a/src/Rule/Upload/Extension.php b/src/Rule/Upload/Extension.php index 91eaac8..f68785e 100644 --- a/src/Rule/Upload/Extension.php +++ b/src/Rule/Upload/Extension.php @@ -6,7 +6,6 @@ class Extension extends AbstractRule { - const OPTION_ALLOWED_EXTENSIONS = 'allowed'; const MESSAGE = 'The file does not have an acceptable extension ({file_extensions})'; @@ -33,14 +32,14 @@ public function setOption($name, $value) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { + if (! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { $this->success = false; } else { $extension = strtolower(substr($value['name'], strrpos($value['name'], '.') + 1, 10)); $this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array( - $extension, - $this->options[self::OPTION_ALLOWED_EXTENSIONS] - ); + $extension, + $this->options[self::OPTION_ALLOWED_EXTENSIONS] + ); } return $this->success; diff --git a/src/Rule/Upload/Image.php b/src/Rule/Upload/Image.php index 16a33b6..0e91eaf 100644 --- a/src/Rule/Upload/Image.php +++ b/src/Rule/Upload/Image.php @@ -6,7 +6,6 @@ class Image extends AbstractRule { - const OPTION_ALLOWED_IMAGES = 'allowed'; const MESSAGE = 'The file is not a valid image (only {image_types} are allowed)'; @@ -43,7 +42,7 @@ public function setOption($name, $value) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { + if (! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { $this->success = false; } else { $imageInfo = getimagesize($value['tmp_name']); diff --git a/src/Rule/Upload/ImageHeight.php b/src/Rule/Upload/ImageHeight.php index 4ce2c07..10ef4c2 100644 --- a/src/Rule/Upload/ImageHeight.php +++ b/src/Rule/Upload/ImageHeight.php @@ -20,12 +20,14 @@ class ImageHeight extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { + if (!is_array($value) || !isset($value['tmp_name']) || !file_exists($value['tmp_name'])) { $this->success = false; } else { $imageInfo = getimagesize($value['tmp_name']); $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; - $this->success = $height && $height <= $this->options[self::OPTION_MAX] && $height >= $this->options[self::OPTION_MIN]; + $this->success = $height && + $height <= $this->options[self::OPTION_MAX] && + $height >= $this->options[self::OPTION_MIN]; } return $this->success; diff --git a/src/Rule/Upload/ImageRatio.php b/src/Rule/Upload/ImageRatio.php index df9ac77..d121f80 100644 --- a/src/Rule/Upload/ImageRatio.php +++ b/src/Rule/Upload/ImageRatio.php @@ -38,7 +38,7 @@ public function validate($value, $valueIdentifier = null) { $this->value = $value; $ratio = $this->normalizeRatio($this->options[self::OPTION_RATIO]); - if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { + if (! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { $this->success = false; } elseif ($ratio == 0) { $this->success = true; diff --git a/src/Rule/Upload/ImageWidth.php b/src/Rule/Upload/ImageWidth.php index 1f6a08c..1aa4180 100644 --- a/src/Rule/Upload/ImageWidth.php +++ b/src/Rule/Upload/ImageWidth.php @@ -20,12 +20,14 @@ class ImageWidth extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { + if (!is_array($value) || !isset($value['tmp_name']) || !file_exists($value['tmp_name'])) { $this->success = false; } else { $imageInfo = getimagesize($value['tmp_name']); $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; - $this->success = $width && $width <= $this->options[self::OPTION_MAX] && $width >= $this->options[self::OPTION_MIN]; + $this->success = $width && + $width <= $this->options[self::OPTION_MAX] && + $width >= $this->options[self::OPTION_MIN]; } return $this->success; diff --git a/src/Rule/Upload/Size.php b/src/Rule/Upload/Size.php index 6eedd08..d746a22 100644 --- a/src/Rule/Upload/Size.php +++ b/src/Rule/Upload/Size.php @@ -19,7 +19,7 @@ protected function normalizeSize($size) { $units = array( 'B' => 0, 'K' => 1, 'M' => 2, 'G' => 3 ); $unit = strtoupper(substr($size, strlen($size) - 1, 1)); - if ( ! isset($units[$unit])) { + if (! isset($units[$unit])) { $normalizedSize = filter_var($size, FILTER_SANITIZE_NUMBER_INT); } else { $size = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); @@ -32,7 +32,7 @@ protected function normalizeSize($size) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if ( ! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { + if (! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { $this->success = false; } else { $fileSize = @filesize($value['tmp_name']); diff --git a/src/Rule/Url.php b/src/Rule/Url.php index 463e010..ed460e6 100755 --- a/src/Rule/Url.php +++ b/src/Rule/Url.php @@ -3,7 +3,6 @@ class Url extends AbstractRule { - const MESSAGE = 'This input is not a valid URL'; const LABELED_MESSAGE = '{label} is not a valid URL'; diff --git a/src/Rule/Website.php b/src/Rule/Website.php index abfa848..8bfc32f 100755 --- a/src/Rule/Website.php +++ b/src/Rule/Website.php @@ -3,7 +3,6 @@ class Website extends AbstractRule { - const WEBSITE_REGEX = '@^((http|https)\:)//.+$@i'; const MESSAGE = 'This input must be a valid website address'; @@ -14,10 +13,10 @@ public function validate($value, $valueIdentifier = null) $this->value = $value; $this->success = (substr($value, 0, 2) == '//') || (preg_match(static::WEBSITE_REGEX, $value) && filter_var( - $value, - FILTER_VALIDATE_URL, - FILTER_FLAG_HOST_REQUIRED - )); + $value, + FILTER_VALIDATE_URL, + FILTER_FLAG_HOST_REQUIRED + )); return $this->success; } diff --git a/src/RuleCollection.php b/src/RuleCollection.php index 42dfd53..d26d35d 100644 --- a/src/RuleCollection.php +++ b/src/RuleCollection.php @@ -4,8 +4,6 @@ class RuleCollection extends \SplObjectStorage { - - public function attach($rule, $data = null) { if ($this->contains($rule)) { @@ -33,5 +31,4 @@ public function getHash($rule) /* @var $rule Rule\AbstractValidator */ return $rule->getUniqueId(); } - } diff --git a/src/RuleFactory.php b/src/RuleFactory.php index 435c7b1..8d2adec 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -28,7 +28,7 @@ class RuleFactory /** * Constructor */ - function __construct() + public function __construct() { $this->registerDefaultRules(); } @@ -139,8 +139,8 @@ public function createRule($name, $options = null, $messageTemplate = null, $lab $validator = $this->construcRuleByNameAndOptions($name, $options); // no message template, try to get it from the registry - if ( ! $messageTemplate) { - $messageTemplate = $this->getSuggestedMessageTemplate($name, ! ! $label); + if (!$messageTemplate) { + $messageTemplate = $this->getSuggestedMessageTemplate($name, !!$label); } if (is_string($messageTemplate) && $messageTemplate !== '') { @@ -187,7 +187,9 @@ protected function getSuggestedMessageTemplate($name, $withLabel) { $noLabelMessage = is_string($name) && isset($this->errorMessages[$name]) ? $this->errorMessages[$name] : null; if ($withLabel) { - return is_string($name) && isset($this->labeledErrorMessages[$name]) ? $this->labeledErrorMessages[$name] : $noLabelMessage; + return is_string($name) && isset($this->labeledErrorMessages[$name]) ? + $this->labeledErrorMessages[$name] : + $noLabelMessage; } return $noLabelMessage; @@ -224,7 +226,7 @@ protected function construcRuleByNameAndOptions($name, $options) } } - if ( ! isset($validator)) { + if (!isset($validator)) { throw new \InvalidArgumentException( sprintf('Impossible to determine the validator based on the name: %s', (string) $name) ); @@ -232,5 +234,4 @@ protected function construcRuleByNameAndOptions($name, $options) return $validator; } - } diff --git a/src/Util/Arr.php b/src/Util/Arr.php index c7b9cca..ac555e5 100644 --- a/src/Util/Arr.php +++ b/src/Util/Arr.php @@ -24,9 +24,9 @@ protected static function getSelectorParts($selector) $firstClose = strpos($selector, ']'); $container = substr($selector, 0, $firstOpen); $subselector = substr($selector, $firstOpen + 1, $firstClose - $firstOpen - 1) . substr( - $selector, - $firstClose + 1 - ); + $selector, + $firstClose + 1 + ); return array( $container, $subselector ); } @@ -46,7 +46,7 @@ protected static function getSelectorParts($selector) public static function getByPath($array, $path = self::PATH_ROOT) { $path = trim($path); - if ( ! $path || $path == self::PATH_ROOT) { + if (! $path || $path == self::PATH_ROOT) { return $array; } // fix the path in case it was provided as `[item][subitem]` @@ -82,11 +82,11 @@ public static function setBySelector($array, $selector, $value, $overwrite = fal // make sure the array is an array in case we got here through a subsequent call // so arraySetElementBySelector(array(), 'item[subitem]', 'value'); // will call arraySetElementBySelector(null, 'subitem', 'value'); - if ( ! is_array($array)) { + if (! is_array($array)) { $array = array(); } list($container, $subselector) = self::getSelectorParts($selector); - if ( ! $subselector) { + if (! $subselector) { if ($container !== '*') { if ($overwrite === true || ! array_key_exists($container, $array)) { $array[$container] = $value; @@ -136,11 +136,11 @@ public static function getBySelector($array, $selector) list($preffix, $suffix) = explode('[*]', $selector, 2); $base = self::getByPath($array, $preffix); - if ( ! is_array($base)) { + if (! is_array($base)) { $base = array(); } // we don't have a suffix, the selector was something like path[subpath][*] - if ( ! $suffix) { + if (! $suffix) { foreach ($base as $k => $v) { $result["{$preffix}[{$k}]"] = $v; } diff --git a/src/Validator.php b/src/Validator.php index 38fda3c..1cbddeb 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -5,7 +5,6 @@ class Validator implements ValidatorInterface { - const RULE_REQUIRED = 'required'; const RULE_REQUIRED_WITH = 'requiredwith'; @@ -127,11 +126,11 @@ class Validator implements ValidatorInterface public function __construct(RuleFactory $ruleFactory = null, ErrorMessage $errorMessagePrototype = null) { - if ( ! $ruleFactory) { + if (!$ruleFactory) { $ruleFactory = new RuleFactory(); } $this->ruleFactory = $ruleFactory; - if ( ! $errorMessagePrototype) { + if (!$errorMessagePrototype) { $errorMessagePrototype = new ErrorMessage(); } $this->errorMessagePrototype = $errorMessagePrototype; @@ -172,21 +171,27 @@ public function getErroMessagePrototype() } /** - * @example // add multiple rules at once - * $validator->add(array( - * 'field_a' => 'required', - * 'field_b' => array('required', array('email', null, '{label} must be an email', 'Field B')), - * )); - * // add multiple rules using arrays - * $validator->add('field', array('required', 'email')); - * // add multiple rules using a string - * $validator->add('field', 'required | email'); - * // add validator with options - * $validator->add('field:Label', 'minlength', array('min' => 2), '{label} should have at least {min} characters'); - * // add validator with string and parameters as JSON string - * $validator->add('field:Label', 'minlength({"min": 2})({label} should have at least {min} characters)'); - * // add validator with string and parameters as query string - * $validator->add('field:label', 'minlength(min=2)({label} should have at least {min} characters)'); + * @example + * // add multiple rules at once + * $validator->add(array( + * 'field_a' => 'required', + * 'field_b' => array('required', array('email', null, '{label} must be an email', 'Field B')), + * )); + * + * // add multiple rules using arrays + * $validator->add('field', array('required', 'email')); + * + * // add multiple rules using a string + * $validator->add('field', 'required | email'); + * + * // add validator with options + * $validator->add('field:Label', 'minlength', array('min' => 2), '{label} should have at least {min} characters'); + * + * // add validator with string and parameters as JSON string + * $validator->add('field:Label', 'minlength({"min": 2})({label} should have at least {min} characters)'); + * + * // add validator with string and parameters as query string + * $validator->add('field:label', 'minlength(min=2)({label} should have at least {min} characters)'); * * @param string $selector * @param string|callback $name @@ -202,7 +207,7 @@ public function add($selector, $name = null, $options = null, $messageTemplate = { // the $selector is an associative array with $selector => $rules if (func_num_args() == 1) { - if ( ! is_array($selector)) { + if (!is_array($selector)) { throw new \InvalidArgumentException('If $selector is the only argument it must be an array'); } @@ -228,9 +233,8 @@ public function add($selector, $name = null, $options = null, $messageTemplate = public function addMultiple($selectorRulesCollection) { foreach ($selectorRulesCollection as $selector => $rules) { - // a single rule was passed for the $valueSelector - if ( ! is_array($rules)) { + if (! is_array($rules)) { $this->add($selector, $rules); continue; } @@ -269,7 +273,7 @@ public function addMultiple($selectorRulesCollection) */ public function remove($selector, $name = true, $options = null) { - if ( ! array_key_exists($selector, $this->rules)) { + if (!array_key_exists($selector, $this->rules)) { return $this; } /* @var $collection \Sirius\Validation\ValueValidator */ @@ -290,7 +294,7 @@ public function remove($selector, $name = true, $options = null) public function getDataWrapper($data = null) { // if $data is set reconstruct the data wrapper - if ( ! $this->dataWrapper || $data) { + if (!$this->dataWrapper || $data) { $this->dataWrapper = new DataWrapper\ArrayWrapper($data); } @@ -327,7 +331,7 @@ public function validate($data = null) foreach ($this->rules as $selector => $valueValidator) { foreach ($this->getDataWrapper()->getItemsBySelector($selector) as $valueIdentifier => $value) { /* @var $valueValidator \Sirius\Validation\ValueValidator */ - if ( ! $valueValidator->validate($value, $valueIdentifier, $this->getDataWrapper())) { + if (!$valueValidator->validate($value, $valueIdentifier, $this->getDataWrapper())) { foreach ($valueValidator->getMessages() as $message) { $this->addMessage($valueIdentifier, $message); } @@ -351,7 +355,7 @@ public function addMessage($item, $message = null) if ($message === null || $message === '') { return $this; } - if ( ! array_key_exists($item, $this->messages)) { + if (!array_key_exists($item, $this->messages)) { $this->messages[$item] = array(); } $this->messages[$item][] = $message; @@ -405,10 +409,12 @@ public function getRules() */ protected function ensureSelectorRulesExist($selector, $label = null) { - if ( ! isset($this->rules[$selector])) { - $this->rules[$selector] = new ValueValidator($this->getRuleFactory(), $this->getErroMessagePrototype(), - $label); + if (!isset($this->rules[$selector])) { + $this->rules[$selector] = new ValueValidator( + $this->getRuleFactory(), + $this->getErroMessagePrototype(), + $label + ); } } - } diff --git a/src/ValidatorInterface.php b/src/ValidatorInterface.php index 104f070..591cd1f 100644 --- a/src/ValidatorInterface.php +++ b/src/ValidatorInterface.php @@ -4,7 +4,6 @@ interface ValidatorInterface { - public function add($selector, $name = null, $options = null, $messageTemplate = null, $label = null); public function remove($selector, $name = true, $options = null); diff --git a/src/ValueValidator.php b/src/ValueValidator.php index ba42a93..91ba3fe 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -43,13 +43,16 @@ class ValueValidator protected $label; - function __construct(RuleFactory $ruleFactory = null, ErrorMessage $errorMessagePrototype = null, $label = null) - { - if ( ! $ruleFactory) { + public function __construct( + RuleFactory $ruleFactory = null, + ErrorMessage $errorMessagePrototype = null, + $label = null + ) { + if (!$ruleFactory) { $ruleFactory = new RuleFactory(); } $this->ruleFactory = $ruleFactory; - if ( ! $errorMessagePrototype) { + if (!$errorMessagePrototype) { $errorMessagePrototype = new ErrorMessage(); } $this->errorMessagePrototype = $errorMessagePrototype; @@ -69,19 +72,24 @@ public function setLabel($label = null) /** * Add 1 or more validation rules * - * @example // add multiple rules at once - * $validator->add(array( - * 'required', - * array('required', array('email', null, '{label} must be an email', 'Field B')), - * )); - * // add multiple rules using a string - * $validator->add('required | email'); - * // add validator with options - * $validator->add('minlength', array('min' => 2), '{label} should have at least {min} characters', 'Field label'); - * // add validator with string and parameters as JSON string - * $validator->add('minlength({"min": 2})({label} should have at least {min} characters)(Field label)'); - * // add validator with string and parameters as query string - * $validator->add('minlength(min=2)({label} should have at least {min} characters)(Field label)'); + * @example + * // add multiple rules at once + * $validator->add(array( + * 'required', + * array('required', array('email', null, '{label} must be an email', 'Field B')), + * )); + * + * // add multiple rules using a string + * $validator->add('required | email'); + * + * // add validator with options + * $validator->add('minlength', array('min' => 2), '{label} should have at least {min} characters', 'Field label'); + * + * // add validator with string and parameters as JSON string + * $validator->add('minlength({"min": 2})({label} should have at least {min} characters)(Field label)'); + * + * // add validator with string and parameters as query string + * $validator->add('minlength(min=2)({label} should have at least {min} characters)(Field label)'); * * @param string|callback $name * @param string|array $options @@ -92,7 +100,7 @@ public function setLabel($label = null) */ public function add($name, $options = null, $messageTemplate = null, $label = null) { - if (is_array($name) && ! is_callable($name)) { + if (is_array($name) && !is_callable($name)) { return $this->addMultiple($name); } if (is_string($name)) { @@ -102,12 +110,12 @@ public function add($name, $options = null, $messageTemplate = null, $label = nu } // rule was supplied like this 'length(2,10)(error message template)(label)' if (strpos($name, '(') !== false) { - list ($name, $options, $messageTemplate, $label) = $this->parseRule($name); + list($name, $options, $messageTemplate, $label) = $this->parseRule($name); } } // check for the default label - if ( ! $label && $this->label) { + if (!$label && $this->label) { $label = $this->label; } @@ -240,14 +248,14 @@ public function validate($value, $valueIdentifier = null, DataWrapper\WrapperInt } } - if ( ! $isRequired && $value === null) { + if (!$isRequired && $value === null) { return true; } /* @var $rule \Sirius\Validation\Rule\AbstractValidator */ foreach ($this->rules as $rule) { $rule->setContext($context); - if ( ! $rule->validate($value, $valueIdentifier)) { + if (!$rule->validate($value, $valueIdentifier)) { $this->addMessage($rule->getMessage()); } // if field is required and we have an error, @@ -276,5 +284,4 @@ public function getRules() { return $this->rules; } - } diff --git a/tests/src/HelperTest.php b/tests/src/HelperTest.php index 9df95c3..c689097 100755 --- a/tests/src/HelperTest.php +++ b/tests/src/HelperTest.php @@ -384,7 +384,7 @@ function testOfIn() ) ); foreach ($pool as $sample) { - $this->assertSame(Helper::in($sample[0], $sample[1]), $sample[2]); + $this->assertSame(Helper::inList($sample[0], $sample[1]), $sample[2]); } } @@ -409,7 +409,7 @@ function testOfNotIn() ) ); foreach ($pool as $sample) { - $this->assertSame(Helper::notIn($sample[0], $sample[1]), $sample[2]); + $this->assertSame(Helper::notInList($sample[0], $sample[1]), $sample[2]); } } @@ -554,7 +554,7 @@ function testOfIp() ); foreach ($pool as $sample) { - $this->assertSame(Helper::ip($sample[0]), $sample[1]); + $this->assertSame(Helper::ipAddress($sample[0]), $sample[1]); } } From e5033df2fbdd41188d514b79f20896fd9adddc6c Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 24 Feb 2017 19:44:52 +0200 Subject: [PATCH 025/112] Fixed issue with $optionsIndexMap not being defined in the AbstractRule class --- src/Rule/AbstractRule.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index 71676a3..974349f 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -59,6 +59,13 @@ abstract class AbstractRule */ protected $errorMessagePrototype; + /** + * Options map in case the options are passed as list instead of associative array + * + * @var array + */ + protected $optionsIndexMap = array(); + public function __construct($options = array()) { $options = $this->normalizeOptions($options); @@ -129,7 +136,7 @@ protected function parseHttpQueryString($str) * * @param $v * - * @return bool + * @return bool|array */ protected function convertBooleanStrings($v) { From b7a0b635557d09b487b6b2577910badd1ca8036e Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 24 Feb 2017 19:45:05 +0200 Subject: [PATCH 026/112] Allow travis failure for PHP 5.4 --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 6dbf7ea..8528777 100755 --- a/.travis.yml +++ b/.travis.yml @@ -11,6 +11,7 @@ php: matrix: allow_failures: - php: 5.3 + - php: 5.4 before_script: - wget -c https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar From 18e07b536fcd4f22793ce09e33b3e9110e427ceb Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 24 Feb 2017 19:50:51 +0200 Subject: [PATCH 027/112] CS fix --- src/Rule/AbstractRule.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index 974349f..d79e002 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -61,7 +61,7 @@ abstract class AbstractRule /** * Options map in case the options are passed as list instead of associative array - * + * * @var array */ protected $optionsIndexMap = array(); From 08c1c96f48d3b2e193aa9b0e993d857f9f44bcdb Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 24 Feb 2017 20:19:32 +0200 Subject: [PATCH 028/112] HVVM build fails due to PHPCS, allow it to fail --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 8528777..0c1a459 100755 --- a/.travis.yml +++ b/.travis.yml @@ -12,6 +12,7 @@ matrix: allow_failures: - php: 5.3 - php: 5.4 + - php: hhvm before_script: - wget -c https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar From a6ccedacc97665e76a27149f5faf057b807b8ad8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gell=C3=A9rt=20Guzmics?= Date: Tue, 7 Mar 2017 16:28:53 +0100 Subject: [PATCH 029/112] Fixed the issue where the uploaded file was always rejected even when had the UPLOAD_ERR_NO_FILE flag. It is changed accordingly, so the Upload rules doesn't fail when there is no file uploaded. It only do so, if the Upload\Required rule is added. --- composer.json | 2 +- src/Rule/Upload/Extension.php | 8 ++- src/Rule/Upload/Image.php | 8 ++- src/Rule/Upload/ImageHeight.php | 8 ++- src/Rule/Upload/ImageRatio.php | 10 ++- src/Rule/Upload/ImageWidth.php | 8 ++- src/Rule/Upload/Required.php | 31 +++++++++ src/Rule/Upload/Size.php | 8 ++- tests/src/Rule/Upload/ExtensionTest.php | 12 ++++ tests/src/Rule/Upload/ImageHeightTest.php | 12 ++++ tests/src/Rule/Upload/ImageRatioTest.php | 12 ++++ tests/src/Rule/Upload/ImageTest.php | 12 ++++ tests/src/Rule/Upload/ImageWidthTest.php | 12 ++++ tests/src/Rule/Upload/RequiredTest.php | 83 +++++++++++++++++++++++ tests/src/Rule/Upload/SizeTest.php | 12 ++++ 15 files changed, 230 insertions(+), 8 deletions(-) create mode 100644 src/Rule/Upload/Required.php create mode 100644 tests/src/Rule/Upload/RequiredTest.php diff --git a/composer.json b/composer.json index 045340c..98d68f2 100755 --- a/composer.json +++ b/composer.json @@ -20,7 +20,7 @@ "php": ">=5.3" }, "require-dev": { - "phpunit/phpunit": "3.7" + "phpunit/phpunit": "^3.7" }, "autoload": { "psr-4": { diff --git a/src/Rule/Upload/Extension.php b/src/Rule/Upload/Extension.php index f68785e..bdf580b 100644 --- a/src/Rule/Upload/Extension.php +++ b/src/Rule/Upload/Extension.php @@ -32,8 +32,14 @@ public function setOption($name, $value) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { + if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; + } else if(! file_exists($value['tmp_name'])) { + if($value['error'] === UPLOAD_ERR_NO_FILE ){ + $this->success = true; + }else{ + $this->success = false; + } } else { $extension = strtolower(substr($value['name'], strrpos($value['name'], '.') + 1, 10)); $this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array( diff --git a/src/Rule/Upload/Image.php b/src/Rule/Upload/Image.php index 0e91eaf..f5934f6 100644 --- a/src/Rule/Upload/Image.php +++ b/src/Rule/Upload/Image.php @@ -42,8 +42,14 @@ public function setOption($name, $value) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { + if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; + } else if(! file_exists($value['tmp_name'])) { + if($value['error'] === UPLOAD_ERR_NO_FILE ){ + $this->success = true; + }else{ + $this->success = false; + } } else { $imageInfo = getimagesize($value['tmp_name']); $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; diff --git a/src/Rule/Upload/ImageHeight.php b/src/Rule/Upload/ImageHeight.php index 10ef4c2..1b63e23 100644 --- a/src/Rule/Upload/ImageHeight.php +++ b/src/Rule/Upload/ImageHeight.php @@ -20,8 +20,14 @@ class ImageHeight extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!is_array($value) || !isset($value['tmp_name']) || !file_exists($value['tmp_name'])) { + if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; + } else if(! file_exists($value['tmp_name'])) { + if($value['error'] === UPLOAD_ERR_NO_FILE ){ + $this->success = true; + }else{ + $this->success = false; + } } else { $imageInfo = getimagesize($value['tmp_name']); $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; diff --git a/src/Rule/Upload/ImageRatio.php b/src/Rule/Upload/ImageRatio.php index d121f80..b08b073 100644 --- a/src/Rule/Upload/ImageRatio.php +++ b/src/Rule/Upload/ImageRatio.php @@ -38,9 +38,15 @@ public function validate($value, $valueIdentifier = null) { $this->value = $value; $ratio = $this->normalizeRatio($this->options[self::OPTION_RATIO]); - if (! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { + if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; - } elseif ($ratio == 0) { + } else if(! file_exists($value['tmp_name'])) { + if($value['error'] === UPLOAD_ERR_NO_FILE ){ + $this->success = true; + }else{ + $this->success = false; + } + } else if ($ratio == 0) { $this->success = true; } else { $imageInfo = getimagesize($value['tmp_name']); diff --git a/src/Rule/Upload/ImageWidth.php b/src/Rule/Upload/ImageWidth.php index 1aa4180..b0a0afe 100644 --- a/src/Rule/Upload/ImageWidth.php +++ b/src/Rule/Upload/ImageWidth.php @@ -20,8 +20,14 @@ class ImageWidth extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (!is_array($value) || !isset($value['tmp_name']) || !file_exists($value['tmp_name'])) { + if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; + } else if(! file_exists($value['tmp_name'])) { + if($value['error'] === UPLOAD_ERR_NO_FILE ){ + $this->success = true; + }else{ + $this->success = false; + } } else { $imageInfo = getimagesize($value['tmp_name']); $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; diff --git a/src/Rule/Upload/Required.php b/src/Rule/Upload/Required.php new file mode 100644 index 0000000..574f47d --- /dev/null +++ b/src/Rule/Upload/Required.php @@ -0,0 +1,31 @@ +value = $value; + if (! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name']) || $value['error'] !== UPLOAD_ERR_OK) { + $this->success = false; + } else { + $this->success = true; + } + + return $this->success; + } +} \ No newline at end of file diff --git a/src/Rule/Upload/Size.php b/src/Rule/Upload/Size.php index d746a22..7115c94 100644 --- a/src/Rule/Upload/Size.php +++ b/src/Rule/Upload/Size.php @@ -32,8 +32,14 @@ protected function normalizeSize($size) public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name'])) { + if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; + } else if(! file_exists($value['tmp_name'])) { + if($value['error'] === UPLOAD_ERR_NO_FILE ){ + $this->success = true; + }else{ + $this->success = false; + } } else { $fileSize = @filesize($value['tmp_name']); $limit = $this->normalizeSize($this->options[self::OPTION_SIZE]); diff --git a/tests/src/Rule/Upload/ExtensionTest.php b/tests/src/Rule/Upload/ExtensionTest.php index abff3ab..3608b20 100644 --- a/tests/src/Rule/Upload/ExtensionTest.php +++ b/tests/src/Rule/Upload/ExtensionTest.php @@ -24,6 +24,18 @@ function testExistingFiles() $this->assertTrue($this->validator->validate($file)); } + function testNoUpload() + { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + $this->assertTrue($this->validator->validate($file)); + } + function testMissingFiles() { $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); diff --git a/tests/src/Rule/Upload/ImageHeightTest.php b/tests/src/Rule/Upload/ImageHeightTest.php index 139c75f..253edc5 100644 --- a/tests/src/Rule/Upload/ImageHeightTest.php +++ b/tests/src/Rule/Upload/ImageHeightTest.php @@ -23,6 +23,18 @@ function testMissingFiles() $this->assertFalse($this->validator->validate($file)); } + function testNoUpload() + { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + $this->assertTrue($this->validator->validate($file)); + } + function testFile() { $fileName = 'real_jpeg_file.jpg'; diff --git a/tests/src/Rule/Upload/ImageRatioTest.php b/tests/src/Rule/Upload/ImageRatioTest.php index 9c10f43..751ac6a 100644 --- a/tests/src/Rule/Upload/ImageRatioTest.php +++ b/tests/src/Rule/Upload/ImageRatioTest.php @@ -23,6 +23,18 @@ function testMissingFiles() $this->assertFalse($this->validator->validate($file)); } + function testNoUpload() + { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + $this->assertTrue($this->validator->validate($file)); + } + function testSquare() { $fileName = 'square_image.gif'; diff --git a/tests/src/Rule/Upload/ImageTest.php b/tests/src/Rule/Upload/ImageTest.php index dbf01ee..d1d29bb 100644 --- a/tests/src/Rule/Upload/ImageTest.php +++ b/tests/src/Rule/Upload/ImageTest.php @@ -23,6 +23,18 @@ function testMissingFiles() $this->assertFalse($this->validator->validate($file)); } + function testNoUpload() + { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + $this->assertTrue($this->validator->validate($file)); + } + function testRealImage() { $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); diff --git a/tests/src/Rule/Upload/ImageWidthTest.php b/tests/src/Rule/Upload/ImageWidthTest.php index 3f444be..7d547fe 100644 --- a/tests/src/Rule/Upload/ImageWidthTest.php +++ b/tests/src/Rule/Upload/ImageWidthTest.php @@ -23,6 +23,18 @@ function testMissingFiles() $this->assertFalse($this->validator->validate($file)); } + function testNoUpload() + { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + $this->assertTrue($this->validator->validate($file)); + } + function testFile() { $fileName = 'real_jpeg_file.jpg'; diff --git a/tests/src/Rule/Upload/RequiredTest.php b/tests/src/Rule/Upload/RequiredTest.php new file mode 100644 index 0000000..ae82ca4 --- /dev/null +++ b/tests/src/Rule/Upload/RequiredTest.php @@ -0,0 +1,83 @@ +validator = new Required(); + } + + function testMissingFiles() + { + $fileName = 'file_that_does_not_exist.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + $this->assertFalse($this->validator->validate($file)); + } + + function testUploadOk() + { + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + $this->assertTrue($this->validator->validate($file)); + } + + function testUploadNotOk() + { + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_PARTIAL + ); + $this->assertFalse($this->validator->validate($file)); + } + + function testNoUpload() + { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + $this->assertFalse($this->validator->validate($file)); + } + + function testFile() + { + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + $this->assertTrue($this->validator->validate($file)); + } +} diff --git a/tests/src/Rule/Upload/SizeTest.php b/tests/src/Rule/Upload/SizeTest.php index 20ed7a8..4423717 100644 --- a/tests/src/Rule/Upload/SizeTest.php +++ b/tests/src/Rule/Upload/SizeTest.php @@ -23,6 +23,18 @@ function testMissingFiles() $this->assertFalse($this->validator->validate($file)); } + function testNoUpload() + { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + $this->assertTrue($this->validator->validate($file)); + } + function testFile() { $fileName = 'real_jpeg_file.jpg'; From 7941ef027e1e6b19226f81eaeca552e51120a842 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Tue, 7 Mar 2017 18:03:27 +0200 Subject: [PATCH 030/112] Added .editorconfig file --- .editorconfig | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..cd8eb86 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false From 26eba30d8512822b12919241d117ff0f06a74de8 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Tue, 7 Mar 2017 18:12:51 +0200 Subject: [PATCH 031/112] Fixed some coding style issues introduced by the previous pull-request --- src/Rule/Upload/Extension.php | 8 ++------ src/Rule/Upload/Image.php | 8 ++------ src/Rule/Upload/ImageHeight.php | 8 ++------ src/Rule/Upload/ImageRatio.php | 10 +++------- src/Rule/Upload/ImageWidth.php | 8 ++------ src/Rule/Upload/Required.php | 6 +++--- src/Rule/Upload/Size.php | 8 ++------ src/RuleFactory.php | 1 + src/Validator.php | 1 + 9 files changed, 18 insertions(+), 40 deletions(-) diff --git a/src/Rule/Upload/Extension.php b/src/Rule/Upload/Extension.php index bdf580b..c0efb94 100644 --- a/src/Rule/Upload/Extension.php +++ b/src/Rule/Upload/Extension.php @@ -34,12 +34,8 @@ public function validate($value, $valueIdentifier = null) $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; - } else if(! file_exists($value['tmp_name'])) { - if($value['error'] === UPLOAD_ERR_NO_FILE ){ - $this->success = true; - }else{ - $this->success = false; - } + } elseif (! file_exists($value['tmp_name'])) { + $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { $extension = strtolower(substr($value['name'], strrpos($value['name'], '.') + 1, 10)); $this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array( diff --git a/src/Rule/Upload/Image.php b/src/Rule/Upload/Image.php index f5934f6..d2f92e9 100644 --- a/src/Rule/Upload/Image.php +++ b/src/Rule/Upload/Image.php @@ -44,12 +44,8 @@ public function validate($value, $valueIdentifier = null) $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; - } else if(! file_exists($value['tmp_name'])) { - if($value['error'] === UPLOAD_ERR_NO_FILE ){ - $this->success = true; - }else{ - $this->success = false; - } + } elseif (! file_exists($value['tmp_name'])) { + $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { $imageInfo = getimagesize($value['tmp_name']); $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; diff --git a/src/Rule/Upload/ImageHeight.php b/src/Rule/Upload/ImageHeight.php index 1b63e23..b6e0f15 100644 --- a/src/Rule/Upload/ImageHeight.php +++ b/src/Rule/Upload/ImageHeight.php @@ -22,12 +22,8 @@ public function validate($value, $valueIdentifier = null) $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; - } else if(! file_exists($value['tmp_name'])) { - if($value['error'] === UPLOAD_ERR_NO_FILE ){ - $this->success = true; - }else{ - $this->success = false; - } + } elseif (! file_exists($value['tmp_name'])) { + $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { $imageInfo = getimagesize($value['tmp_name']); $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; diff --git a/src/Rule/Upload/ImageRatio.php b/src/Rule/Upload/ImageRatio.php index b08b073..0dc119a 100644 --- a/src/Rule/Upload/ImageRatio.php +++ b/src/Rule/Upload/ImageRatio.php @@ -40,13 +40,9 @@ public function validate($value, $valueIdentifier = null) $ratio = $this->normalizeRatio($this->options[self::OPTION_RATIO]); if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; - } else if(! file_exists($value['tmp_name'])) { - if($value['error'] === UPLOAD_ERR_NO_FILE ){ - $this->success = true; - }else{ - $this->success = false; - } - } else if ($ratio == 0) { + } elseif (! file_exists($value['tmp_name'])) { + $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; + } elseif ($ratio == 0) { $this->success = true; } else { $imageInfo = getimagesize($value['tmp_name']); diff --git a/src/Rule/Upload/ImageWidth.php b/src/Rule/Upload/ImageWidth.php index b0a0afe..190797a 100644 --- a/src/Rule/Upload/ImageWidth.php +++ b/src/Rule/Upload/ImageWidth.php @@ -22,12 +22,8 @@ public function validate($value, $valueIdentifier = null) $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; - } else if(! file_exists($value['tmp_name'])) { - if($value['error'] === UPLOAD_ERR_NO_FILE ){ - $this->success = true; - }else{ - $this->success = false; - } + } elseif (! file_exists($value['tmp_name'])) { + $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { $imageInfo = getimagesize($value['tmp_name']); $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; diff --git a/src/Rule/Upload/Required.php b/src/Rule/Upload/Required.php index 574f47d..e109469 100644 --- a/src/Rule/Upload/Required.php +++ b/src/Rule/Upload/Required.php @@ -8,7 +8,6 @@ namespace Sirius\Validation\Rule\Upload; - use Sirius\Validation\Rule\AbstractRule; class Required extends AbstractRule @@ -20,7 +19,8 @@ class Required extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - if (! is_array($value) || ! isset($value['tmp_name']) || ! file_exists($value['tmp_name']) || $value['error'] !== UPLOAD_ERR_OK) { + if (! is_array($value) || ! isset($value['tmp_name']) || + ! file_exists($value['tmp_name']) || $value['error'] !== UPLOAD_ERR_OK) { $this->success = false; } else { $this->success = true; @@ -28,4 +28,4 @@ public function validate($value, $valueIdentifier = null) return $this->success; } -} \ No newline at end of file +} diff --git a/src/Rule/Upload/Size.php b/src/Rule/Upload/Size.php index 7115c94..83c602d 100644 --- a/src/Rule/Upload/Size.php +++ b/src/Rule/Upload/Size.php @@ -34,12 +34,8 @@ public function validate($value, $valueIdentifier = null) $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; - } else if(! file_exists($value['tmp_name'])) { - if($value['error'] === UPLOAD_ERR_NO_FILE ){ - $this->success = true; - }else{ - $this->success = false; - } + } elseif (! file_exists($value['tmp_name'])) { + $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { $fileSize = @filesize($value['tmp_name']); $limit = $this->normalizeSize($this->options[self::OPTION_SIZE]); diff --git a/src/RuleFactory.php b/src/RuleFactory.php index 8d2adec..771e5d7 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -79,6 +79,7 @@ protected function registerDefaultRules() 'File\ImageRatio', 'File\ImageWidth', 'File\Size', + 'Upload\Required', 'Upload\Extension', 'Upload\Image', 'Upload\ImageHeight', diff --git a/src/Validator.php b/src/Validator.php index 1cbddeb..14e1176 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -85,6 +85,7 @@ class Validator implements ValidatorInterface const RULE_IMAGE_WIDTH = 'imagewidth'; const RULE_IMAGE_RATIO = 'imageratio'; // upload rules + const RULE_UPLOAD_REQUIRED = 'uploadrequired'; const RULE_UPLOAD_EXTENSION = 'uploadextension'; const RULE_UPLOAD_SIZE = 'uploadsize'; const RULE_UPLOAD_IMAGE = 'uploadimage'; From d2140d71aeeaf54797907a03e11cc20418ac86c4 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Tue, 7 Mar 2017 18:35:59 +0200 Subject: [PATCH 032/112] Updated docs and changelog --- CHANGELOG.md | 5 +++++ docs/validation_rules.md | 13 +++++++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 749fbfc..06aa4b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +#### 2.2.0 + +- added `Upload\Required` rule +- fixed upload validators when the upload was not successful + #### 2.0.0 - added the `data_selector:label` feature diff --git a/docs/validation_rules.md b/docs/validation_rules.md index 609b0ca..67d0bcf 100644 --- a/docs/validation_rules.md +++ b/docs/validation_rules.md @@ -64,11 +64,12 @@ File validators work only with local files and they fail if the file does not ex ### Upload validators Upload validators work only uploaded files (each file is an upload-like array) and they fail if the temporary file does not exist. -1. `Upload\Extension`. Checks if the uploaded file has a certain extension. Rule options: `allowed` which can be an array or a comma separated string. -2. `Upload\Image`. Checks if the uploaded file is an image of a certain type. Rule options: `allowed` which can be an array or a comma separated string (default: `jpg,png,gif`) -3. `Upload\ImageRatio`. Checks if the uploaded image has a certain ratio. Rule options: `ratio` which can be a number or a string like `4:3`, `error_margin` - how much the file's ratio can deviate from the target (default: 0) -4. `Upload\ImageWidth`. Checks if the uploaded image's width is between certain limits. Rule options: `min` (default: 0) and `max` (default: 1 million) -5. `Upload\ImageHeight`. Checks if the uploaded image's height is between certain limits. Rule options: `min` (default: 0) and `max` (default: 1 million) -6. `Upload\Size`. Checks if the uploaded file' size is bellow a certain limit. Rule options: `size` which can be a number or a string like '10K', '0.5M' or '1.3G` (default: 2M) +1. `Upload\Required`. Checks if the uploaded file was uploaded and there are no errors. +2. `Upload\Extension`. Checks if the uploaded file has a certain extension. Rule options: `allowed` which can be an array or a comma separated string. +3. `Upload\Image`. Checks if the uploaded file is an image of a certain type. Rule options: `allowed` which can be an array or a comma separated string (default: `jpg,png,gif`) +4. `Upload\ImageRatio`. Checks if the uploaded image has a certain ratio. Rule options: `ratio` which can be a number or a string like `4:3`, `error_margin` - how much the file's ratio can deviate from the target (default: 0) +5. `Upload\ImageWidth`. Checks if the uploaded image's width is between certain limits. Rule options: `min` (default: 0) and `max` (default: 1 million) +6. `Upload\ImageHeight`. Checks if the uploaded image's height is between certain limits. Rule options: `min` (default: 0) and `max` (default: 1 million) +7. `Upload\Size`. Checks if the uploaded file' size is bellow a certain limit. Rule options: `size` which can be a number or a string like '10K', '0.5M' or '1.3G` (default: 2M) *Note!* The upload validators use only the `tmp_name` and `name` values to perform the validation From da6dc2c8fd67dc0290917a6015b661ef294eda56 Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Wed, 17 May 2017 15:05:58 -0500 Subject: [PATCH 033/112] Create test to probe the failure --- tests/src/ValidatorTest.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/src/ValidatorTest.php b/tests/src/ValidatorTest.php index 80c498a..d85cce9 100755 --- a/tests/src/ValidatorTest.php +++ b/tests/src/ValidatorTest.php @@ -281,4 +281,12 @@ function testEmptyArrayValidation() $this->assertEquals(2, count($this->validator->getMessages())); } + function testValidationRequireConditional() + { + $this->validator->add(array( + 'a' => array( 'number', 'requiredWith(b)' ), + 'b' => array( 'number', 'requiredWith(a)' ) + )); + $this->assertTrue($this->validator->validate(array())); + } } From 945526d4a8fc0423d0752d2a02d6b2325adcad31 Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Wed, 17 May 2017 15:12:48 -0500 Subject: [PATCH 034/112] Evaluate Rules\Required rules first on validate method --- src/ValueValidator.php | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/src/ValueValidator.php b/src/ValueValidator.php index 91ba3fe..6f30700 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -241,27 +241,38 @@ public function validate($value, $valueIdentifier = null, DataWrapper\WrapperInt { $this->messages = array(); $isRequired = false; + + /* @var $rule \Sirius\Validation\Rule\AbstractValidator */ + // evaluate the required rules foreach ($this->rules as $rule) { if ($rule instanceof Rule\Required) { $isRequired = true; - break; + + $rule->setContext($context); + if (!$rule->validate($value, $valueIdentifier)) { + $this->addMessage($rule->getMessage()); + return false; + } } } - if (!$isRequired && $value === null) { + // avoid future rule evaluations if value is null + if ($value === null) { return true; } - /* @var $rule \Sirius\Validation\Rule\AbstractValidator */ + // evaluate the non-required rules foreach ($this->rules as $rule) { - $rule->setContext($context); - if (!$rule->validate($value, $valueIdentifier)) { - $this->addMessage($rule->getMessage()); - } - // if field is required and we have an error, - // do not continue with the rest of rules - if ($isRequired && count($this->messages)) { - break; + if (!($rule instanceof Rule\Required)) { + $rule->setContext($context); + if (!$rule->validate($value, $valueIdentifier)) { + $this->addMessage($rule->getMessage()); + } + // if field is required and we have an error, + // do not continue with the rest of rules + if ($isRequired && count($this->messages)) { + break; + } } } From b11a1181a472ae91264659e6f7c728e850c01319 Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Wed, 17 May 2017 15:19:09 -0500 Subject: [PATCH 035/112] Refactor to avoid code duplication --- src/ValueValidator.php | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/ValueValidator.php b/src/ValueValidator.php index 6f30700..e96fc11 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -242,15 +242,13 @@ public function validate($value, $valueIdentifier = null, DataWrapper\WrapperInt $this->messages = array(); $isRequired = false; - /* @var $rule \Sirius\Validation\Rule\AbstractValidator */ // evaluate the required rules + /* @var $rule \Sirius\Validation\Rule\AbstractValidator */ foreach ($this->rules as $rule) { if ($rule instanceof Rule\Required) { $isRequired = true; - $rule->setContext($context); - if (!$rule->validate($value, $valueIdentifier)) { - $this->addMessage($rule->getMessage()); + if (!$this->validateRule($rule, $value, $valueIdentifier, $context)) { return false; } } @@ -264,10 +262,8 @@ public function validate($value, $valueIdentifier = null, DataWrapper\WrapperInt // evaluate the non-required rules foreach ($this->rules as $rule) { if (!($rule instanceof Rule\Required)) { - $rule->setContext($context); - if (!$rule->validate($value, $valueIdentifier)) { - $this->addMessage($rule->getMessage()); - } + $this->validateRule($rule, $value, $valueIdentifier, $context); + // if field is required and we have an error, // do not continue with the rest of rules if ($isRequired && count($this->messages)) { @@ -279,6 +275,16 @@ public function validate($value, $valueIdentifier = null, DataWrapper\WrapperInt return count($this->messages) === 0; } + private function validateRule($rule, $value, $valueIdentifier, $context) + { + $rule->setContext($context); + if (!$rule->validate($value, $valueIdentifier)) { + $this->addMessage($rule->getMessage()); + return false; + } + return true; + } + public function getMessages() { return $this->messages; From b81bf20ead1d4df908fb84406d383851996598ce Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Wed, 17 May 2017 15:52:35 -0500 Subject: [PATCH 036/112] Run phpunit from the right location --- .travis.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0c1a459..ad6624e 100755 --- a/.travis.yml +++ b/.travis.yml @@ -5,8 +5,8 @@ php: - 5.4 - 5.5 - 5.6 + - 7.0 - hhvm - - '7' matrix: allow_failures: @@ -22,8 +22,7 @@ before_script: script: - mkdir -p build/logs - composer run-script phpcs - - cd tests - - phpunit + - cd tests && ../vendor/bin/phpunit && cd .. after_script: - wget https://scrutinizer-ci.com/ocular.phar From a44ca71c4ca5d72e22cdb4fe8828bf89a15344aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20M=C3=BCller?= Date: Sun, 12 Nov 2017 10:03:12 +0100 Subject: [PATCH 037/112] Fixed Division-by-zero bug in Ratio validation if File is a corrupt image. --- src/Rule/File/ImageRatio.php | 10 ++++++++-- src/Rule/Upload/ImageRatio.php | 10 ++++++++-- tests/fixitures/corrupt_image.jpg | 1 + tests/src/Rule/File/ImageRatioTest.php | 7 +++++++ tests/src/Rule/Upload/ImageRatioTest.php | 14 ++++++++++++++ 5 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 tests/fixitures/corrupt_image.jpg diff --git a/src/Rule/File/ImageRatio.php b/src/Rule/File/ImageRatio.php index e058721..3a6e8c0 100644 --- a/src/Rule/File/ImageRatio.php +++ b/src/Rule/File/ImageRatio.php @@ -44,8 +44,14 @@ public function validate($value, $valueIdentifier = null) $this->success = true; } else { $imageInfo = getimagesize($value); - $actualRatio = $imageInfo[0] / $imageInfo[1]; - $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; + + if($imageInfo) { + $actualRatio = $imageInfo[0] / $imageInfo[1]; + $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; + } else { + // no image size computed => no valid image + return $this->success = false; + } } return $this->success; diff --git a/src/Rule/Upload/ImageRatio.php b/src/Rule/Upload/ImageRatio.php index 0dc119a..fa17a05 100644 --- a/src/Rule/Upload/ImageRatio.php +++ b/src/Rule/Upload/ImageRatio.php @@ -46,8 +46,14 @@ public function validate($value, $valueIdentifier = null) $this->success = true; } else { $imageInfo = getimagesize($value['tmp_name']); - $actualRatio = $imageInfo[0] / $imageInfo[1]; - $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; + + if($imageInfo) { + $actualRatio = $imageInfo[0] / $imageInfo[1]; + $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; + } else { + // no image size computed => no valid image + return $this->success = false; + } } return $this->success; diff --git a/tests/fixitures/corrupt_image.jpg b/tests/fixitures/corrupt_image.jpg new file mode 100644 index 0000000..4b0d1b5 --- /dev/null +++ b/tests/fixitures/corrupt_image.jpg @@ -0,0 +1 @@ +IM_A_CORRUPT_IMAGE diff --git a/tests/src/Rule/File/ImageRatioTest.php b/tests/src/Rule/File/ImageRatioTest.php index d183a92..dac7363 100644 --- a/tests/src/Rule/File/ImageRatioTest.php +++ b/tests/src/Rule/File/ImageRatioTest.php @@ -53,4 +53,11 @@ function testRatioAsString() $this->assertTrue($this->validator->validate($file)); } + function testFileNotAnImage() + { + $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'corrupt_image.jpg'; + $this->assertFalse($this->validator->validate($file)); + } + } diff --git a/tests/src/Rule/Upload/ImageRatioTest.php b/tests/src/Rule/Upload/ImageRatioTest.php index 751ac6a..adcc525 100644 --- a/tests/src/Rule/Upload/ImageRatioTest.php +++ b/tests/src/Rule/Upload/ImageRatioTest.php @@ -107,4 +107,18 @@ function testRatioAsString() $this->assertTrue($this->validator->validate($file)); } + function testFileNotAnImage() + { + $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); + $fileName = 'corrupt_image.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + $this->assertFalse($this->validator->validate($file)); + } + } From e112518a1a9e7c97d3aeb687036f3330e5f6073d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20M=C3=BCller?= Date: Sun, 12 Nov 2017 10:14:43 +0100 Subject: [PATCH 038/112] Fixed Travis error --- src/Rule/File/ImageRatio.php | 2 +- src/Rule/Upload/ImageRatio.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Rule/File/ImageRatio.php b/src/Rule/File/ImageRatio.php index 3a6e8c0..0b9f7bd 100644 --- a/src/Rule/File/ImageRatio.php +++ b/src/Rule/File/ImageRatio.php @@ -45,7 +45,7 @@ public function validate($value, $valueIdentifier = null) } else { $imageInfo = getimagesize($value); - if($imageInfo) { + if ($imageInfo) { $actualRatio = $imageInfo[0] / $imageInfo[1]; $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; } else { diff --git a/src/Rule/Upload/ImageRatio.php b/src/Rule/Upload/ImageRatio.php index fa17a05..c736037 100644 --- a/src/Rule/Upload/ImageRatio.php +++ b/src/Rule/Upload/ImageRatio.php @@ -47,7 +47,7 @@ public function validate($value, $valueIdentifier = null) } else { $imageInfo = getimagesize($value['tmp_name']); - if($imageInfo) { + if ($imageInfo) { $actualRatio = $imageInfo[0] / $imageInfo[1]; $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; } else { From c9583f628041e1ff3f2af9dd6122e6687e4e91d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20M=C3=BCller?= Date: Sun, 12 Nov 2017 10:22:44 +0100 Subject: [PATCH 039/112] Corrected implicit array to boolean conversion --- src/Rule/File/ImageRatio.php | 2 +- src/Rule/Upload/ImageRatio.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Rule/File/ImageRatio.php b/src/Rule/File/ImageRatio.php index 0b9f7bd..622be13 100644 --- a/src/Rule/File/ImageRatio.php +++ b/src/Rule/File/ImageRatio.php @@ -45,7 +45,7 @@ public function validate($value, $valueIdentifier = null) } else { $imageInfo = getimagesize($value); - if ($imageInfo) { + if (is_array($imageInfo)) { $actualRatio = $imageInfo[0] / $imageInfo[1]; $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; } else { diff --git a/src/Rule/Upload/ImageRatio.php b/src/Rule/Upload/ImageRatio.php index c736037..647d794 100644 --- a/src/Rule/Upload/ImageRatio.php +++ b/src/Rule/Upload/ImageRatio.php @@ -47,7 +47,7 @@ public function validate($value, $valueIdentifier = null) } else { $imageInfo = getimagesize($value['tmp_name']); - if ($imageInfo) { + if (is_array($imageInfo)) { $actualRatio = $imageInfo[0] / $imageInfo[1]; $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; } else { From bded0b4eea7214a320d9d7bbf282b75fed52b7dc Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Fri, 26 Jan 2018 01:53:06 -0600 Subject: [PATCH 040/112] Add test to review the default values with no options --- tests/src/Rule/GreaterThanTest.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/src/Rule/GreaterThanTest.php b/tests/src/Rule/GreaterThanTest.php index 9849f8f..5476837 100755 --- a/tests/src/Rule/GreaterThanTest.php +++ b/tests/src/Rule/GreaterThanTest.php @@ -12,6 +12,12 @@ function setUp() $this->rule = new Rule(); } + function testDefaultOptions() + { + $this->assertNull($this->rule->getOption('min')); + $this->assertTrue($this->rule->getOption('inclusive')); + } + function testExclusiveValidation() { $this->rule->setOption('inclusive', false); From 71410379ab7aabc3204c0793acf2af5b2ee9c4f4 Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Fri, 26 Jan 2018 01:54:19 -0600 Subject: [PATCH 041/112] Add test to check cvs format with two options --- tests/src/Rule/GreaterThanTest.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/src/Rule/GreaterThanTest.php b/tests/src/Rule/GreaterThanTest.php index 5476837..91d09fe 100755 --- a/tests/src/Rule/GreaterThanTest.php +++ b/tests/src/Rule/GreaterThanTest.php @@ -29,4 +29,11 @@ function testValidationWithoutALimit() { $this->assertTrue($this->rule->validate(0)); } + + function testConstructCvsFormatMinZeroAndInclusiveFalse() + { + $this->rule = new Rule('0,false'); + $this->assertSame('0', $this->rule->getOption('min')); + $this->assertSame(false, $this->rule->getOption('inclusive')); + } } From 57cdb76af95fdf048477c1dc593e8297e0878f6c Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Fri, 26 Jan 2018 01:55:52 -0600 Subject: [PATCH 042/112] Add test to check query string format with one option --- tests/src/Rule/GreaterThanTest.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/src/Rule/GreaterThanTest.php b/tests/src/Rule/GreaterThanTest.php index 91d09fe..b0938f8 100755 --- a/tests/src/Rule/GreaterThanTest.php +++ b/tests/src/Rule/GreaterThanTest.php @@ -36,4 +36,10 @@ function testConstructCvsFormatMinZeroAndInclusiveFalse() $this->assertSame('0', $this->rule->getOption('min')); $this->assertSame(false, $this->rule->getOption('inclusive')); } + + function testConstructWithMinValueZeroQueryStringFormat() + { + $this->rule = new Rule('min=0'); + $this->assertSame('0', $this->rule->getOption('min')); + } } From c9d3a3d1255eee46c4cea121f1d769c82c2c256a Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Fri, 26 Jan 2018 01:56:15 -0600 Subject: [PATCH 043/112] Add test to check issue #46 --- tests/src/Rule/GreaterThanTest.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/src/Rule/GreaterThanTest.php b/tests/src/Rule/GreaterThanTest.php index b0938f8..d4db449 100755 --- a/tests/src/Rule/GreaterThanTest.php +++ b/tests/src/Rule/GreaterThanTest.php @@ -42,4 +42,10 @@ function testConstructWithMinValueZeroQueryStringFormat() $this->rule = new Rule('min=0'); $this->assertSame('0', $this->rule->getOption('min')); } + + function testConstructWithMinValueZeroCvsFormat() + { + $this->rule = new Rule('0'); + $this->assertSame('0', $this->rule->getOption('min')); + } } From f0391761ef2c99593ddafcd8b15cdca9f38c47e9 Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Fri, 26 Jan 2018 01:58:15 -0600 Subject: [PATCH 044/112] Fix issue #46 --- src/Rule/AbstractRule.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index d79e002..0363b5e 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -90,7 +90,7 @@ public function __construct($options = array()) */ protected function normalizeOptions($options) { - if (! $options) { + if ('0' !== $options && ! $options) { return array(); } @@ -99,7 +99,7 @@ protected function normalizeOptions($options) } $result = $options; - if ($options && is_string($options)) { + if (is_string($options) && '' !== $options) { $startChar = substr($options, 0, 1); if ($startChar == '{') { $result = json_decode($options, true); @@ -264,7 +264,7 @@ public function setContext($context = null) } if (! is_object($context) || ! $context instanceof WrapperInterface) { throw new \InvalidArgumentException( - 'Validator context must be either an array or an instance + 'Validator context must be either an array or an instance of Sirius\Validator\DataWrapper\WrapperInterface' ); } From 13ab88fc439255ba0296865b2388c25e28c309f2 Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Fri, 26 Jan 2018 01:58:15 -0600 Subject: [PATCH 045/112] Revert "Fix issue #46" This reverts commit f0391761ef2c99593ddafcd8b15cdca9f38c47e9. --- src/Rule/AbstractRule.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index 0363b5e..d79e002 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -90,7 +90,7 @@ public function __construct($options = array()) */ protected function normalizeOptions($options) { - if ('0' !== $options && ! $options) { + if (! $options) { return array(); } @@ -99,7 +99,7 @@ protected function normalizeOptions($options) } $result = $options; - if (is_string($options) && '' !== $options) { + if ($options && is_string($options)) { $startChar = substr($options, 0, 1); if ($startChar == '{') { $result = json_decode($options, true); @@ -264,7 +264,7 @@ public function setContext($context = null) } if (! is_object($context) || ! $context instanceof WrapperInterface) { throw new \InvalidArgumentException( - 'Validator context must be either an array or an instance + 'Validator context must be either an array or an instance of Sirius\Validator\DataWrapper\WrapperInterface' ); } From 598b583f3bd3d4dcc227dbc205a9b383fd2ce59a Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Fri, 26 Jan 2018 02:06:59 -0600 Subject: [PATCH 046/112] Fix issue #46 with a more elegant solution --- src/Rule/AbstractRule.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index d79e002..c3c0649 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -90,6 +90,9 @@ public function __construct($options = array()) */ protected function normalizeOptions($options) { + if ('0' === $options && count($this->optionsIndexMap) > 0) { + $options = [$this->optionsIndexMap[0] => '0']; + } if (! $options) { return array(); } @@ -264,7 +267,7 @@ public function setContext($context = null) } if (! is_object($context) || ! $context instanceof WrapperInterface) { throw new \InvalidArgumentException( - 'Validator context must be either an array or an instance + 'Validator context must be either an array or an instance of Sirius\Validator\DataWrapper\WrapperInterface' ); } From 3c9a9fdbfeac7b37eebdace86e693ed33f84b655 Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Fri, 26 Jan 2018 02:09:51 -0600 Subject: [PATCH 047/112] Use array long notation --- src/Rule/AbstractRule.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index c3c0649..dc5b704 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -91,7 +91,7 @@ public function __construct($options = array()) protected function normalizeOptions($options) { if ('0' === $options && count($this->optionsIndexMap) > 0) { - $options = [$this->optionsIndexMap[0] => '0']; + $options = array($this->optionsIndexMap[0] => '0'); } if (! $options) { return array(); From 5d869bf5bdf9a60319ca3df83da10afc03776c76 Mon Sep 17 00:00:00 2001 From: Carlos C Soto Date: Fri, 26 Jan 2018 02:17:54 -0600 Subject: [PATCH 048/112] Fix code style by phpcbf, make travis green again! --- src/Rule/Website.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Rule/Website.php b/src/Rule/Website.php index 8bfc32f..6c11395 100755 --- a/src/Rule/Website.php +++ b/src/Rule/Website.php @@ -12,11 +12,11 @@ public function validate($value, $valueIdentifier = null) { $this->value = $value; $this->success = (substr($value, 0, 2) == '//') - || (preg_match(static::WEBSITE_REGEX, $value) && filter_var( - $value, - FILTER_VALIDATE_URL, - FILTER_FLAG_HOST_REQUIRED - )); + || (preg_match(static::WEBSITE_REGEX, $value) && filter_var( + $value, + FILTER_VALIDATE_URL, + FILTER_FLAG_HOST_REQUIRED + )); return $this->success; } From 9f3058ddf65ca933b1dbe251f03e37189ddab47e Mon Sep 17 00:00:00 2001 From: Sergei Belyakov Date: Mon, 29 Jan 2018 20:20:16 +0200 Subject: [PATCH 049/112] Add test to review parse rule 'GreaterThan(0)' --- tests/src/ValueValidatorTest.php | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/src/ValueValidatorTest.php b/tests/src/ValueValidatorTest.php index 33007d3..36a7260 100644 --- a/tests/src/ValueValidatorTest.php +++ b/tests/src/ValueValidatorTest.php @@ -1,8 +1,14 @@ validator->getMessages()); } + + function testParseRuleWithZeroValueInCsvFormat() + { + $this->validator->add('GreaterThan(0)'); + /** @var GreaterThan $rule */ + foreach ($this->validator->getRules() as $rule) { + break; + } + + $this->assertSame('0', $rule->getOption('min')); + + $this->validator->validate(1); + $this->assertEmpty($this->validator->getMessages()); + + $this->validator->validate(0); + $this->assertEmpty($this->validator->getMessages()); + + $this->validator->validate(-1); + $this->assertNotEmpty($this->validator->getMessages()); + } } From 0b7f21c955fbaf984e4fb509452be4af95e1f8cc Mon Sep 17 00:00:00 2001 From: Sergei Belyakov Date: Mon, 29 Jan 2018 20:23:46 +0200 Subject: [PATCH 050/112] Fixes method names of tests for issue 46 (GreaterThan(0)) after PR #48 --- tests/src/Rule/GreaterThanTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/src/Rule/GreaterThanTest.php b/tests/src/Rule/GreaterThanTest.php index d4db449..9a5d688 100755 --- a/tests/src/Rule/GreaterThanTest.php +++ b/tests/src/Rule/GreaterThanTest.php @@ -30,7 +30,7 @@ function testValidationWithoutALimit() $this->assertTrue($this->rule->validate(0)); } - function testConstructCvsFormatMinZeroAndInclusiveFalse() + function testConstructCsvFormatMinZeroAndInclusiveFalse() { $this->rule = new Rule('0,false'); $this->assertSame('0', $this->rule->getOption('min')); @@ -43,7 +43,7 @@ function testConstructWithMinValueZeroQueryStringFormat() $this->assertSame('0', $this->rule->getOption('min')); } - function testConstructWithMinValueZeroCvsFormat() + function testConstructWithMinValueZeroCsvFormat() { $this->rule = new Rule('0'); $this->assertSame('0', $this->rule->getOption('min')); From 0c57da6fca6286966d42999960a6ff34d78df7e4 Mon Sep 17 00:00:00 2001 From: Sergei Belyakov Date: Mon, 29 Jan 2018 20:37:28 +0200 Subject: [PATCH 051/112] Fixes reason 2 for issue 46: parseRule with zero value in csv format, for example 'GreaterThan(0)' --- src/ValueValidator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ValueValidator.php b/src/ValueValidator.php index e96fc11..c10894f 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -217,7 +217,7 @@ protected function parseRule($ruleAsString) preg_match_all('/\(([^\)]*)\)/', $ruleAsString, $matches); if (isset($matches[1])) { - if (isset($matches[1][0]) && $matches[1][0]) { + if (isset($matches[1][0]) && $matches[1][0] !== '') { $options = $matches[1][0]; } if (isset($matches[1][1]) && $matches[1][1]) { From c49a58816ccd1854eaab3d6f79c95c53b693ad91 Mon Sep 17 00:00:00 2001 From: Siavash Habil Date: Wed, 31 Jan 2018 16:30:44 +0300 Subject: [PATCH 052/112] Change Validator::add() first param to accept array in phpdocs --- src/Validator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Validator.php b/src/Validator.php index 14e1176..4c80f06 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -194,7 +194,7 @@ public function getErroMessagePrototype() * // add validator with string and parameters as query string * $validator->add('field:label', 'minlength(min=2)({label} should have at least {min} characters)'); * - * @param string $selector + * @param string|array $selector * @param string|callback $name * @param string|array $options * @param string $messageTemplate From 5506b659795d4408d1a64723e3a9c4e76dc86eb7 Mon Sep 17 00:00:00 2001 From: Sergei Belyakov Date: Thu, 1 Mar 2018 14:18:39 +0200 Subject: [PATCH 053/112] Avoids future rule evaluations if value is empty string --- src/ValueValidator.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/ValueValidator.php b/src/ValueValidator.php index e96fc11..4449ceb 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -254,8 +254,8 @@ public function validate($value, $valueIdentifier = null, DataWrapper\WrapperInt } } - // avoid future rule evaluations if value is null - if ($value === null) { + // avoid future rule evaluations if value is null or empty string + if ($this->isEmpty($value)) { return true; } @@ -301,4 +301,9 @@ public function getRules() { return $this->rules; } + + protected function isEmpty($value) + { + return in_array($value, [null, '']); + } } From 2aa83b28368a6c9e609326676e492647cff951ce Mon Sep 17 00:00:00 2001 From: Sergei Belyakov Date: Wed, 4 Apr 2018 16:49:31 +0300 Subject: [PATCH 054/112] Add test to review issue 52 (empty string, that is not required, is not valid) --- tests/src/ValueValidatorTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/src/ValueValidatorTest.php b/tests/src/ValueValidatorTest.php index 36a7260..f192dd5 100644 --- a/tests/src/ValueValidatorTest.php +++ b/tests/src/ValueValidatorTest.php @@ -58,6 +58,7 @@ function testNonRequiredRules() { $this->validator->add('email'); $this->assertTrue($this->validator->validate(null)); + $this->assertTrue($this->validator->validate('')); } function testDefaultLabel() From cb2925df0213edee12996454e67d66047976daba Mon Sep 17 00:00:00 2001 From: Sergei Belyakov Date: Mon, 14 May 2018 21:02:45 +0300 Subject: [PATCH 055/112] Issue 52: Fixes for php-5.3 after PR #53 --- src/ValueValidator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ValueValidator.php b/src/ValueValidator.php index fcf5a2f..f00ba55 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -304,6 +304,6 @@ public function getRules() protected function isEmpty($value) { - return in_array($value, [null, '']); + return in_array($value, array(null, '')); } } From 349ca4dac41ca61148a251f62c11fb6db30de814 Mon Sep 17 00:00:00 2001 From: Mitchell Macpherson Date: Thu, 27 Sep 2018 13:26:55 +1000 Subject: [PATCH 056/112] Corrected link to validation helper doc on index doc --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index a796e83..a90510c 100755 --- a/docs/index.md +++ b/docs/index.md @@ -12,7 +12,7 @@ Sirius Validation is a library for data validation. It offers: 1. [validator object](validator.md) 2. [45 build-in validation rules](validation_rules.md). There are validators for strings, array, numbers, emails, URLs, files and uploads -3. [validation helper](helper.md) to simplify the validation of single values +3. [validation helper](validation_helper.md) to simplify the validation of single values Out-of-the-box, the library can handle `array`s, `ArrayObject`s and objects that have implemented the `toArray` method. In order to validate other data containers you must create a [`DataWrapper`](https://github.com/siriusphp/validation/blob/master/src/Validation/DataWrapper/WrapperInterface.php) so that the validator be able to extract data from your object. From 7df3014ba0568885ba714537a66f9f4539b51390 Mon Sep 17 00:00:00 2001 From: kulavvy <47749939+kulavvy@users.noreply.github.com> Date: Mon, 18 Feb 2019 16:06:11 +0100 Subject: [PATCH 057/112] fix checking empty value as strict --- src/ValueValidator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ValueValidator.php b/src/ValueValidator.php index f00ba55..e85a969 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -304,6 +304,6 @@ public function getRules() protected function isEmpty($value) { - return in_array($value, array(null, '')); + return in_array($value, array(null, ''), true); } } From 38cdc13ef949fa80334bdba26e325038d91d4716 Mon Sep 17 00:00:00 2001 From: Rhilip Date: Sat, 27 Jul 2019 12:02:53 +0800 Subject: [PATCH 058/112] Fix issue #58 for PHP-7.3 --- src/Rule/Url.php | 2 +- tests/src/Rule/UrlTest.php | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 tests/src/Rule/UrlTest.php diff --git a/src/Rule/Url.php b/src/Rule/Url.php index ed460e6..97bb352 100755 --- a/src/Rule/Url.php +++ b/src/Rule/Url.php @@ -9,7 +9,7 @@ class Url extends AbstractRule public function validate($value, $valueIdentifier = null) { $this->value = $value; - $this->success = (bool) filter_var($value, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED); + $this->success = (bool) filter_var($value, FILTER_VALIDATE_URL); return $this->success; } diff --git a/tests/src/Rule/UrlTest.php b/tests/src/Rule/UrlTest.php new file mode 100644 index 0000000..5c1957f --- /dev/null +++ b/tests/src/Rule/UrlTest.php @@ -0,0 +1,25 @@ +rule = new Rule(); + } + + function testValidation() + { + $this->assertFalse($this->rule->validate('')); + $this->assertTrue($this->rule->validate('http://www.google.com')); + } +} From 3a72511af912a92509d0ea59b92137b02c7b61be Mon Sep 17 00:00:00 2001 From: Rhilip Date: Sat, 27 Jul 2019 17:40:00 +0800 Subject: [PATCH 059/112] Fix issue #59 with new build-in validator `NotMatch` , `NotEqual` --- docs/validation_rules.md | 4 ++- src/Helper.php | 9 +++++++ src/Rule/NotEqual.php | 16 ++++++++++++ src/Rule/NotMatch.php | 17 +++++++++++++ src/RuleFactory.php | 2 ++ src/Validator.php | 4 +++ tests/src/ComplexTest.php | 10 ++++---- tests/src/HelperTest.php | 43 +++++++++++++++++++++++++++++++++ tests/src/Rule/NotEqualTest.php | 28 +++++++++++++++++++++ tests/src/Rule/NotMatchTest.php | 36 +++++++++++++++++++++++++++ 10 files changed, 163 insertions(+), 6 deletions(-) create mode 100644 src/Rule/NotEqual.php create mode 100644 src/Rule/NotMatch.php create mode 100644 tests/src/Rule/NotEqualTest.php create mode 100644 tests/src/Rule/NotMatchTest.php diff --git a/docs/validation_rules.md b/docs/validation_rules.md index 67d0bcf..e4e270d 100644 --- a/docs/validation_rules.md +++ b/docs/validation_rules.md @@ -49,7 +49,9 @@ title: Built-in validation rules 2. `NotRegex`: value must NOT match a regular expression pattern. Rule options: `pattern` 3. `Callback`: checks if a value is valid using a custom callback (a function, an object's method, a class' static method). Rule options: `callback` and `arguments` (additional paramters for the callback) 4. `Match`: the value must match the value of another item in the context. Rule options: `item` (eg: if `auth[password_confirm]` must match `auth[password]` the `item` is `auth[password]` -5. `Equal`: the value must be the same as predefined value. Rule options: `value` +5. `NotMatch': the value must not match the value of another item in the context. Rule options: `item` (eg: if `auth[password]` must not match `auth[username]` the `item` is `auth[username]` +6. `Equal`: the value must be the same as predefined value. Rule options: `value` +7. `NotEqual`: the value must not be the same as predefined value. Rule options: `value` ### File validators File validators work only with local files and they fail if the file does not exist diff --git a/src/Helper.php b/src/Helper.php index 413d4bf..e119da8 100755 --- a/src/Helper.php +++ b/src/Helper.php @@ -251,6 +251,15 @@ public static function equalTo($value, $otherElementOrValue, $context = null) return $value == Arr::getByPath($context, $otherElementOrValue); } + public static function notEqualTo($value, $otherElementOrValue, $context = null) + { + if (func_num_args() == 2) { + return $value != $otherElementOrValue; + } + + return $value != Arr::getByPath($context, $otherElementOrValue); + } + public static function date($value, $format = 'Y-m-d') { $validator = new Rule\Date( diff --git a/src/Rule/NotEqual.php b/src/Rule/NotEqual.php new file mode 100644 index 0000000..340cfae --- /dev/null +++ b/src/Rule/NotEqual.php @@ -0,0 +1,16 @@ +success = ! $this->success; + + return $this->success; + } +} diff --git a/src/Rule/NotMatch.php b/src/Rule/NotMatch.php new file mode 100644 index 0000000..dba9235 --- /dev/null +++ b/src/Rule/NotMatch.php @@ -0,0 +1,17 @@ +success = ! $this->success; + + return $this->success; + } +} diff --git a/src/RuleFactory.php b/src/RuleFactory.php index 771e5d7..05519db 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -62,7 +62,9 @@ protected function registerDefaultRules() 'Match', 'MaxLength', 'MinLength', + 'NotEqual', 'NotInList', + 'NotMatch', 'NotRegex', 'Number', 'Regex', diff --git a/src/Validator.php b/src/Validator.php index 4c80f06..7f2b43b 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -73,8 +73,12 @@ class Validator implements ValidatorInterface const RULE_MATCH = 'match'; + const RULE_NOT_MATCH = 'notmatch'; + const RULE_EQUAL = 'equal'; + const RULE_NOT_EQUAL = 'notequal'; + const RULE_CALLBACK = 'callback'; // files rules diff --git a/tests/src/ComplexTest.php b/tests/src/ComplexTest.php index 9b09146..fba184b 100644 --- a/tests/src/ComplexTest.php +++ b/tests/src/ComplexTest.php @@ -12,7 +12,7 @@ function setUp() $this->validator ->add('email', 'email | required')// does the order matter? ->add('email_confirm', 'required | email | match(item=email)') - ->add('password', 'required') + ->add('password', 'required | notmatch(item=email)') ->add('password_confirm', 'required | match(item=password)') ->add('feedback', 'requiredwith(item=agree_to_provide_feedback)') ->add('birthday', 'requiredwhen', array( 'item' => 'email_confirm', 'rule' => 'Email' )) @@ -41,8 +41,8 @@ function notestWithCorrectData() function testWithInvalidData() { $data = array( - 'email_confirm' => 'me@domain.com', - 'password' => '1234', + 'email' => 'me@domain.com', + 'password' => 'me@domain.com', 'password_confirm' => '123456', 'agree_to_provide_feedback' => true, 'lines' => array( @@ -52,10 +52,10 @@ function testWithInvalidData() $this->validator->validate($data); $messages = $this->validator->getMessages(); - $this->assertEquals('This field is required', (string) $messages['email'][0]); + $this->assertEquals('This field is required', (string) $messages['email_confirm'][0]); + $this->assertEquals('This input does match email', (string) $messages['password'][0]); $this->assertEquals('This input does not match password', (string) $messages['password_confirm'][0]); $this->assertEquals('This field is required', (string) $messages['feedback'][0]); $this->assertEquals('This field is required', (string) $messages['lines[0][price]'][0]); } - } diff --git a/tests/src/HelperTest.php b/tests/src/HelperTest.php index c689097..467bd27 100755 --- a/tests/src/HelperTest.php +++ b/tests/src/HelperTest.php @@ -488,12 +488,55 @@ function testOfEqualToWithContext() } } + function testOfNotEqualToWithContext() + { + $pool = array( + array( + 'value', + 'element_1', + false + ), + array( + 'value', + 'element_2', + true + ), + array( + 'new value', + 'element_3[sub_element_1][sub_element_2]', + false + ) + ); + $context = array( + 'element_1' => 'value', + 'element_2' => 'another_value', + 'element_3' => array( + 'sub_element_1' => array( + 'sub_element_2' => 'new value' + ) + ) + ); + foreach ($pool as $sample) { + $this->assertSame( + Helper::notEqualTo($sample[0], $sample[1], $context), + $sample[2], + sprintf("%s %s", $sample[0], $sample[1]) + ); + } + } + function testOfEqualToWithoutContext() { $this->assertTrue(Helper::equalTo(5, '5')); $this->assertFalse(Helper::equalTo(5, 'a')); } + function testOfNotEqualToWithoutContext() + { + $this->assertTrue(Helper::NotEqualTo(5, 'a')); + $this->assertFalse(Helper::NotEqualTo(5, '5')); + } + function testOfWebsite() { $pool = array( diff --git a/tests/src/Rule/NotEqualTest.php b/tests/src/Rule/NotEqualTest.php new file mode 100644 index 0000000..d04b4d0 --- /dev/null +++ b/tests/src/Rule/NotEqualTest.php @@ -0,0 +1,28 @@ +rule = new Rule(); + } + + function testValidationWithOptionSet() + { + $this->rule->setOption(Rule::OPTION_VALUE, '123'); + $this->assertFalse($this->rule->validate('123')); + $this->assertTrue($this->rule->validate('abc')); + } + + function testValidationWithoutOptionSet() + { + $this->assertFalse($this->rule->validate('abc')); + $this->assertFalse($this->rule->validate(null)); + } + +} diff --git a/tests/src/Rule/NotMatchTest.php b/tests/src/Rule/NotMatchTest.php new file mode 100644 index 0000000..b0a0893 --- /dev/null +++ b/tests/src/Rule/NotMatchTest.php @@ -0,0 +1,36 @@ +rule = new Rule(); + $this->rule->setContext( + new ArrayWrapper( + array( + 'password' => 'secret' + ) + ) + ); + } + + function testValidationWithItemPresent() + { + $this->rule->setOption(Rule::OPTION_ITEM, 'password'); + $this->assertFalse($this->rule->validate('secret')); + $this->assertTrue($this->rule->validate('abc')); + } + + function testValidationWithoutItemPresent() + { + $this->assertTrue($this->rule->validate('abc')); + $this->assertTrue($this->rule->validate(null)); + } + +} From 14e536184e3494c64b7d2b0739b7c1ec02459a69 Mon Sep 17 00:00:00 2001 From: Rhilip Date: Sat, 27 Jul 2019 17:50:41 +0800 Subject: [PATCH 060/112] fix test error $ composer run-script phpcs > php phpcs.phar --standard=PSR2 ./src FILE: /home/travis/build/Rhilip/validation/src/Rule/NotMatch.php ---------------------------------------------------------------------- FOUND 1 ERROR AFFECTING 1 LINE ---------------------------------------------------------------------- 2 | ERROR | [x] There must be one blank line after the namespace | | declaration ---------------------------------------------------------------------- PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- Time: 1.47 secs; Memory: 10MB Script php phpcs.phar --standard=PSR2 ./src handling the phpcs event returned with error code 2 The command "composer run-script phpcs" exited with 2. $ cd tests && ../vendor/bin/phpunit && cd .. PHPUnit 3.7.38 by Sebastian Bergmann. Configuration read from /home/travis/build/Rhilip/validation/tests/phpunit.xml ............................................................... 63 / 192 ( 32%) .......................................F....................... 126 / 192 ( 65%) ............................................................... 189 / 192 ( 98%) ... Time: 1.46 seconds, Memory: 10.00MB There was 1 failure: 1) Sirius\Validation\Rule\NotMatchTest::testValidationWithoutItemPresent Failed asserting that false is true. /home/travis/build/Rhilip/validation/tests/src/Rule/NotMatchTest.php:32 FAILURES! Tests: 192, Assertions: 359, Failures: 1. Generating code coverage report in Clover XML format ... done Generating code coverage report in HTML format ... done The command "cd tests && ../vendor/bin/phpunit && cd .." exited with 1. --- readme.md | 8 ++++---- src/Rule/NotMatch.php | 1 - tests/src/Rule/NotMatchTest.php | 4 ++-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/readme.md b/readme.md index bd77943..c57fa7c 100755 --- a/readme.md +++ b/readme.md @@ -1,4 +1,4 @@ -#Sirius Validation +# Sirius Validation [![Source Code](http://img.shields.io/badge/source-siriusphp/validation-blue.svg?style=flat-square)](https://github.com/siriusphp/validation) [![Latest Version](https://img.shields.io/packagist/v/siriusphp/validation.svg?style=flat-square)](https://github.com/siriusphp/validation/releases) @@ -18,7 +18,7 @@ Sirius Validation is a library for data validation. It offers: Out-of-the-box, the library can handle `array`s, `ArrayObject`s and objects that have implemented the `toArray` method. In order to validate other data containers you must create a [`DataWrapper`](https://github.com/siriusphp/validation/blob/master/src/Validation/DataWrapper/WrapperInterface.php) so that the validator be able to extract data from your object. -##Elevator pitch +## Elevator pitch ```php $validator = new \Sirius\Validation\Validator; @@ -60,12 +60,12 @@ $validator->add('shipping_address[city]:City', 'MyApp\Validator\City'); // uses ``` -##Links +## Links - [documentation](http://sirius.ro/php/sirius/validation/) - [changelog](CHANGELOG.md) -##Known issues +## Known issues In PHP 5.3 there is some problem with the SplObject storage that prevents the library to remove validation rules. This means that in PHP 5.3, you cannot remove a validation rule from a `Validator` or `ValueValidator` object diff --git a/src/Rule/NotMatch.php b/src/Rule/NotMatch.php index dba9235..61db020 100644 --- a/src/Rule/NotMatch.php +++ b/src/Rule/NotMatch.php @@ -1,7 +1,6 @@ assertTrue($this->rule->validate('abc')); - $this->assertTrue($this->rule->validate(null)); + $this->assertFalse($this->rule->validate('abc')); + $this->assertFalse($this->rule->validate(null)); } } From 33f9a72d3e81cef0d9172ed33c6d0162beeeabda Mon Sep 17 00:00:00 2001 From: Rhilip Date: Sat, 27 Jul 2019 18:17:20 +0800 Subject: [PATCH 061/112] test: Add php-7.1 7.2 7.3 --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.travis.yml b/.travis.yml index ad6624e..789a972 100755 --- a/.travis.yml +++ b/.travis.yml @@ -6,6 +6,9 @@ php: - 5.5 - 5.6 - 7.0 + - 7.1 + - 7.2 + - 7.3 - hhvm matrix: From 1cdc82fcae3e9d7f0c33b049d985cc504dbf7e70 Mon Sep 17 00:00:00 2001 From: Rhilip Date: Sat, 27 Jul 2019 19:58:09 +0800 Subject: [PATCH 062/112] test: Update phpunit to last version wich compatible with PHP-5.3 Fix last commit on phpunit fail check in PHP-7.2 and PHP-7.3 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 98d68f2..5366530 100755 --- a/composer.json +++ b/composer.json @@ -20,7 +20,7 @@ "php": ">=5.3" }, "require-dev": { - "phpunit/phpunit": "^3.7" + "phpunit/phpunit": "^4.8" }, "autoload": { "psr-4": { From c6f129579378cf6a055e665d7f33d9cb22f96a68 Mon Sep 17 00:00:00 2001 From: Rhilip Date: Sat, 27 Jul 2019 20:09:25 +0800 Subject: [PATCH 063/112] fix: Another Field which cause travis-ci fail --- src/Rule/Website.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Rule/Website.php b/src/Rule/Website.php index 6c11395..ffd3b7f 100755 --- a/src/Rule/Website.php +++ b/src/Rule/Website.php @@ -14,8 +14,7 @@ public function validate($value, $valueIdentifier = null) $this->success = (substr($value, 0, 2) == '//') || (preg_match(static::WEBSITE_REGEX, $value) && filter_var( $value, - FILTER_VALIDATE_URL, - FILTER_FLAG_HOST_REQUIRED + FILTER_VALIDATE_URL )); return $this->success; From bc73f7c4d011067882253d2f71db5ec7e83d8522 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 6 Dec 2019 18:10:44 +0200 Subject: [PATCH 064/112] Fixed CS issues, remove PHP 5.* from Travis --- .travis.yml | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index 789a972..6390f72 100755 --- a/.travis.yml +++ b/.travis.yml @@ -1,21 +1,14 @@ language: php php: - - 5.3 - - 5.4 - - 5.5 - - 5.6 - 7.0 - 7.1 - 7.2 - 7.3 - - hhvm + - 7.4 matrix: allow_failures: - - php: 5.3 - - php: 5.4 - - php: hhvm before_script: - wget -c https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar From 45823465ac6ab6c765c06656d8c71dda461df5a1 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Sun, 8 Dec 2019 09:31:03 +0200 Subject: [PATCH 065/112] Allow php 7.4 to fail --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 6390f72..e2fbc94 100755 --- a/.travis.yml +++ b/.travis.yml @@ -9,6 +9,7 @@ php: matrix: allow_failures: + - php: 7.4 before_script: - wget -c https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar From a0327ea26a97176597e47ed4093027c497f1100f Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 26 Feb 2020 18:29:39 +0200 Subject: [PATCH 066/112] Upgrade code to PHP 7.1+ --- .travis.yml | 1 - CHANGELOG.md | 9 ++ composer.json | 12 +- docs/couscous.yml | 2 +- readme.md | 20 +-- src/DataWrapper/ArrayWrapper.php | 9 +- src/DataWrapper/WrapperInterface.php | 9 +- src/ErrorMessage.php | 7 +- src/Helper.php | 115 ++++----------- src/Rule/AbstractRule.php | 170 +++------------------- src/Rule/AbstractStringRule.php | 1 + src/Rule/Alpha.php | 3 +- src/Rule/AlphaNumHyphen.php | 7 +- src/Rule/AlphaNumeric.php | 3 +- src/Rule/ArrayLength.php | 9 +- src/Rule/ArrayMaxLength.php | 9 +- src/Rule/ArrayMinLength.php | 9 +- src/Rule/Between.php | 9 +- src/Rule/Callback.php | 9 +- src/Rule/Date.php | 11 +- src/Rule/DateTime.php | 5 +- src/Rule/Email.php | 3 +- src/Rule/EmailDomain.php | 3 +- src/Rule/Equal.php | 7 +- src/Rule/File/Extension.php | 17 +-- src/Rule/File/Image.php | 21 ++- src/Rule/File/ImageHeight.php | 7 +- src/Rule/File/ImageRatio.php | 10 +- src/Rule/File/ImageWidth.php | 7 +- src/Rule/File/Size.php | 24 +-- src/Rule/FullName.php | 3 +- src/Rule/GreaterThan.php | 11 +- src/Rule/InList.php | 7 +- src/Rule/Integer.php | 3 +- src/Rule/IpAddress.php | 3 +- src/Rule/Length.php | 9 +- src/Rule/LessThan.php | 11 +- src/Rule/Match.php | 7 +- src/Rule/MaxLength.php | 9 +- src/Rule/MinLength.php | 9 +- src/Rule/NotEqual.php | 3 +- src/Rule/NotInList.php | 7 +- src/Rule/NotMatch.php | 3 +- src/Rule/NotRegex.php | 3 +- src/Rule/Number.php | 3 +- src/Rule/Regex.php | 7 +- src/Rule/Required.php | 3 +- src/Rule/RequiredWhen.php | 7 +- src/Rule/RequiredWith.php | 9 +- src/Rule/RequiredWithout.php | 7 +- src/Rule/Time.php | 5 +- src/Rule/Upload/Extension.php | 17 +-- src/Rule/Upload/Image.php | 21 ++- src/Rule/Upload/ImageHeight.php | 7 +- src/Rule/Upload/ImageRatio.php | 24 +-- src/Rule/Upload/ImageWidth.php | 7 +- src/Rule/Upload/Required.php | 3 +- src/Rule/Upload/Size.php | 24 +-- src/Rule/Url.php | 3 +- src/Rule/Website.php | 3 +- src/RuleCollection.php | 3 +- src/RuleFactory.php | 21 ++- src/Util/Arr.php | 17 +-- src/Util/RuleHelper.php | 164 +++++++++++++++++++++ src/Validator.php | 32 ++-- src/ValidatorInterface.php | 3 +- src/ValueValidator.php | 45 +++--- tests/phpunit.xml | 18 ++- tests/src/ComplexTest.php | 4 +- tests/src/ErrorMessageTest.php | 4 +- tests/src/HelperTest.php | 4 +- tests/src/Rule/AbstractValidatorTest.php | 6 +- tests/src/Rule/ArrayMaxLengthTest.php | 4 +- tests/src/Rule/ArrayMinLengthTest.php | 4 +- tests/src/Rule/BetweenTest.php | 4 +- tests/src/Rule/CallbackTest.php | 4 +- tests/src/Rule/EmailTest.php | 4 +- tests/src/Rule/EqualTest.php | 4 +- tests/src/Rule/File/ExtensionTest.php | 4 +- tests/src/Rule/File/ImageHeightTest.php | 4 +- tests/src/Rule/File/ImageRatioTest.php | 4 +- tests/src/Rule/File/ImageTest.php | 4 +- tests/src/Rule/File/ImageWidthTest.php | 4 +- tests/src/Rule/File/SizeTest.php | 4 +- tests/src/Rule/GreaterThanTest.php | 4 +- tests/src/Rule/InListTest.php | 4 +- tests/src/Rule/IntegerTest.php | 4 +- tests/src/Rule/LessThanTest.php | 4 +- tests/src/Rule/MatchTest.php | 4 +- tests/src/Rule/NotEqualTest.php | 4 +- tests/src/Rule/NotInListTest.php | 4 +- tests/src/Rule/NotMatchTest.php | 4 +- tests/src/Rule/NumberTest.php | 4 +- tests/src/Rule/RegexTest.php | 4 +- tests/src/Rule/RequiredTest.php | 4 +- tests/src/Rule/RequiredWhenTest.php | 6 +- tests/src/Rule/RequiredWithTest.php | 4 +- tests/src/Rule/RequiredWithoutTest.php | 4 +- tests/src/Rule/Upload/ExtensionTest.php | 4 +- tests/src/Rule/Upload/ImageHeightTest.php | 4 +- tests/src/Rule/Upload/ImageRatioTest.php | 4 +- tests/src/Rule/Upload/ImageTest.php | 4 +- tests/src/Rule/Upload/ImageWidthTest.php | 4 +- tests/src/Rule/Upload/RequiredTest.php | 4 +- tests/src/Rule/Upload/SizeTest.php | 4 +- tests/src/Rule/UrlTest.php | 4 +- tests/src/Rule/WebsiteTest.php | 4 +- tests/src/RuleCollectionTest.php | 4 +- tests/src/RuleFactoryTest.php | 4 +- tests/src/Util/ArrTest.php | 4 +- tests/src/ValidatorTest.php | 12 +- tests/src/ValueValidatorTest.php | 4 +- 112 files changed, 623 insertions(+), 634 deletions(-) create mode 100644 src/Util/RuleHelper.php diff --git a/.travis.yml b/.travis.yml index e2fbc94..61c5d9d 100755 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 7.0 - 7.1 - 7.2 - 7.3 diff --git a/CHANGELOG.md b/CHANGELOG.md index 06aa4b1..c1cc350 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +#### 3.0.0 + +- Simplified the API (ie: less options to create rules) +- Expanded the ability to set custom error messages per selector (eg: "address.city.required") + +#### 2.3.0 + +- Removed 5.* support + #### 2.2.0 - added `Upload\Required` rule diff --git a/composer.json b/composer.json index 5366530..ea9ac8b 100755 --- a/composer.json +++ b/composer.json @@ -17,10 +17,10 @@ } ], "require": { - "php": ">=5.3" + "php": ">=7.1" }, "require-dev": { - "phpunit/phpunit": "^4.8" + "phpunit/phpunit": "^8.5" }, "autoload": { "psr-4": { @@ -28,16 +28,16 @@ } }, "scripts": { - "phpcs": [ + "cs": [ "php phpcs.phar --standard=PSR2 ./src" ], - "phpmd": [ + "md": [ "php phpmd.phar ./src xml phpmd.xml" ], - "phpcbf": [ + "cbf": [ "php phpcbf.phar ./src --standard=PSR2 -w" ], - "phpcsfix": [ + "csfix": [ "php php-cs-fixer.phar fix ./src --rules=@PSR2" ] } diff --git a/docs/couscous.yml b/docs/couscous.yml index fad4112..88eb964 100644 --- a/docs/couscous.yml +++ b/docs/couscous.yml @@ -85,4 +85,4 @@ menu: relativeUrl: custom_rule.html translate_messages: text: Translating the error messages - relativeUrl: translate_messages.html \ No newline at end of file + relativeUrl: translate_messages.html diff --git a/readme.md b/readme.md index c57fa7c..a03b039 100755 --- a/readme.md +++ b/readme.md @@ -41,18 +41,17 @@ $validator->add('title', 'maxlength', 'max=100', 'Article title must have less t // add a rule with a custom message and a label (very handy with forms) $validator->add('title:Title', 'maxlength', 'max=100', '{label} must have less than {max} characters'); -// add all of rule's configuration in a string (you'll see later why it's handy') -$validator->add('title:Title', 'maxlength(max=255)({label} must have less than {max} characters)'); - // add multiple rules at once (separate using [space][pipe][space]) $validator->add('title:Title', 'required | maxlength(255) | minlength(min=10)'); // add all your rules at once -$validator->add(array( - 'title:Title' => 'required | maxlength(100)({label} must have less than {max} characters)', - 'content:Content' => 'required', - 'source:Source' => 'website' -)); +$validator->add([ + 'title:Title' => 'required | maxlength(100)', + 'content:Content' => 'required', + 'source:Source' => 'website' + ], [ + 'content.required' => 'The content field should have a velue' + ]); // add nested rules $validator->add('recipients[*]:Recipients', 'email'); //all recipients must be valid email addresses @@ -65,8 +64,3 @@ $validator->add('shipping_address[city]:City', 'MyApp\Validator\City'); // uses - [documentation](http://sirius.ro/php/sirius/validation/) - [changelog](CHANGELOG.md) -## Known issues - -In PHP 5.3 there is some problem with the SplObject storage that prevents the library to remove validation rules. -This means that in PHP 5.3, you cannot remove a validation rule from a `Validator` or `ValueValidator` object - diff --git a/src/DataWrapper/ArrayWrapper.php b/src/DataWrapper/ArrayWrapper.php index f64ad94..0992620 100644 --- a/src/DataWrapper/ArrayWrapper.php +++ b/src/DataWrapper/ArrayWrapper.php @@ -1,4 +1,5 @@ data = $data; } - public function getItemValue($item) + public function getItemValue(string $item) { return Arr::getByPath($this->data, $item); } - public function getItemsBySelector($selector) + public function getItemsBySelector(string $selector): array { return Arr::getBySelector($this->data, $selector); } diff --git a/src/DataWrapper/WrapperInterface.php b/src/DataWrapper/WrapperInterface.php index 5c0b24c..1ea636c 100644 --- a/src/DataWrapper/WrapperInterface.php +++ b/src/DataWrapper/WrapperInterface.php @@ -1,4 +1,5 @@ setTemplate($template) ->setVariables($variables); @@ -28,7 +29,7 @@ public function getTemplate() return $this->template; } - public function setVariables($variables = array()) + public function setVariables($variables = []) { foreach ($variables as $k => $v) { $this->variables[$k] = $v; diff --git a/src/Helper.php b/src/Helper.php index e119da8..c27137e 100755 --- a/src/Helper.php +++ b/src/Helper.php @@ -1,11 +1,12 @@ setOption('callback', $callback); @@ -42,7 +43,7 @@ public static function callback($value, $callback, $context = array()) public static function required($value) { - return $value !== null && trim($value) !== ''; + return $value !== null && (!is_string($value) || trim($value) !== ''); } public static function truthy($value) @@ -67,34 +68,24 @@ public static function integer($value) public static function lessThan($value, $max) { - $validator = new Rule\LessThan( - array( - 'max' => $max - ) - ); + $validator = new Rule\LessThan(['max' => $max]); return $validator->validate($value); } public static function greaterThan($value, $min) { - $validator = new Rule\GreaterThan( - array( - 'min' => $min - ) - ); + $validator = new Rule\GreaterThan(['min' => $min]); return $validator->validate($value); } public static function between($value, $min, $max) { - $validator = new Rule\Between( - array( - 'min' => $min, - 'max' => $max - ) - ); + $validator = new Rule\Between([ + 'min' => $min, + 'max' => $max + ]); return $validator->validate($value); } @@ -132,112 +123,76 @@ public static function alphanumhyphen($value) public static function minLength($value, $min) { - $validator = new Rule\MinLength( - array( - 'min' => $min - ) - ); + $validator = new Rule\MinLength(['min' => $min]); return $validator->validate($value); } public static function maxLength($value, $max) { - $validator = new Rule\MaxLength( - array( - 'max' => $max - ) - ); + $validator = new Rule\MaxLength(['max' => $max]); return $validator->validate($value); } public static function length($value, $min, $max) { - $validator = new Rule\Length( - array( - 'min' => $min, - 'max' => $max - ) - ); + $validator = new Rule\Length([ + 'min' => $min, + 'max' => $max + ]); return $validator->validate($value); } public static function setMinSize($value, $min) { - $validator = new Rule\ArrayMinLength( - array( - 'min' => $min - ) - ); + $validator = new Rule\ArrayMinLength(['min' => $min]); return $validator->validate($value); } public static function setMaxSize($value, $max) { - $validator = new Rule\ArrayMaxLength( - array( - 'max' => $max - ) - ); + $validator = new Rule\ArrayMaxLength(['max' => $max]); return $validator->validate($value); } public static function setSize($value, $min, $max) { - $validator = new Rule\ArrayLength( - array( - 'min' => $min, - 'max' => $max - ) - ); + $validator = new Rule\ArrayLength([ + 'min' => $min, + 'max' => $max + ]); return $validator->validate($value); } public static function inList($value, $values) { - $validator = new Rule\InList( - array( - 'list' => $values - ) - ); + $validator = new Rule\InList(['list' => $values]); return $validator->validate($value); } public static function notInList($value, $values) { - $validator = new Rule\NotInList( - array( - 'list' => $values - ) - ); + $validator = new Rule\NotInList(['list' => $values]); return $validator->validate($value); } public static function regex($value, $pattern) { - $validator = new Rule\Regex( - array( - 'pattern' => $pattern - ) - ); + $validator = new Rule\Regex(['pattern' => $pattern]); return $validator->validate($value); } public static function notRegex($value, $pattern) { - $validator = new Rule\NotRegex( - array( - 'pattern' => $pattern - ) - ); + $validator = new Rule\NotRegex(['pattern' => $pattern]); return $validator->validate($value); } @@ -262,33 +217,21 @@ public static function notEqualTo($value, $otherElementOrValue, $context = null) public static function date($value, $format = 'Y-m-d') { - $validator = new Rule\Date( - array( - 'format' => $format - ) - ); + $validator = new Rule\Date(['format' => $format]); return $validator->validate($value); } public static function dateTime($value, $format = 'Y-m-d H:i:s') { - $validator = new Rule\DateTime( - array( - 'format' => $format - ) - ); + $validator = new Rule\DateTime(['format' => $format]); return $validator->validate($value); } public static function time($value, $format = 'H:i:s') { - $validator = new Rule\Time( - array( - 'format' => $format - ) - ); + $validator = new Rule\Time(['format' => $format]); return $validator->validate($value); } diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index dc5b704..1ef9aa3 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -1,9 +1,11 @@ normalizeOptions($options); + $options = RuleHelper::normalizeOptions($options, $this->optionsIndexMap); if (is_array($options) && ! empty($options)) { foreach ($options as $k => $v) { $this->setOption($k, $v); @@ -76,139 +78,13 @@ public function __construct($options = array()) } } - /** - * Method that parses the option variable and converts it into an array - * You can pass anything to a validator like: - * - a query string: 'min=3&max=5' - * - a JSON string: '{"min":3,"max":5}' - * - a CSV string: '5,true' (for this scenario the 'optionsIndexMap' property is required) - * - * @param mixed $options - * - * @return array - * @throws \InvalidArgumentException - */ - protected function normalizeOptions($options) - { - if ('0' === $options && count($this->optionsIndexMap) > 0) { - $options = array($this->optionsIndexMap[0] => '0'); - } - if (! $options) { - return array(); - } - - if (is_array($options) && $this->arrayIsAssoc($options)) { - return $options; - } - - $result = $options; - if ($options && is_string($options)) { - $startChar = substr($options, 0, 1); - if ($startChar == '{') { - $result = json_decode($options, true); - } elseif (strpos($options, '=') !== false) { - $result = $this->parseHttpQueryString($options); - } else { - $result = $this->parseCsvString($options); - } - } - - if (! is_array($result)) { - throw new \InvalidArgumentException('Validator options should be an array, JSON string or query string'); - } - - return $result; - } - - /** - * Converts a HTTP query string to an array - * - * @param $str - * - * @return array - */ - protected function parseHttpQueryString($str) - { - parse_str($str, $arr); - - return $this->convertBooleanStrings($arr); - } - - /** - * Converts 'true' and 'false' strings to TRUE and FALSE - * - * @param $v - * - * @return bool|array - */ - protected function convertBooleanStrings($v) - { - if (is_array($v)) { - return array_map(array( $this, 'convertBooleanStrings' ), $v); - } - if ($v === 'true') { - return true; - } - if ($v === 'false') { - return false; - } - - return $v; - } - - /** - * Parses a CSV string and converts the result into an "options" array - * (an associative array that contains the options for the validation rule) - * - * @param $str - * - * @return array - */ - protected function parseCsvString($str) - { - if (! isset($this->optionsIndexMap) || ! is_array($this->optionsIndexMap) || empty($this->optionsIndexMap)) { - throw new \InvalidArgumentException(sprintf( - 'Class %s is missing the `optionsIndexMap` property', - get_class($this) - )); - } - - $options = explode(',', $str); - $result = array(); - foreach ($options as $k => $v) { - if (! isset($this->optionsIndexMap[$k])) { - throw new \InvalidArgumentException(sprintf( - 'Class %s does not have the index %d configured in the `optionsIndexMap` property', - get_class($this), - $k - )); - } - $result[$this->optionsIndexMap[$k]] = $v; - } - - return $this->convertBooleanStrings($result); - } - - /** - * Checks if an array is associative (ie: the keys are not numbers in sequence) - * - * @param array $arr - * - * @return bool - */ - protected function arrayIsAssoc($arr) - { - return array_keys($arr) !== range(0, count($arr)); - } - - /** * Generates a unique string to identify the validator. * It is used to compare 2 validators so you don't add the same rule twice in a validator object * * @return string */ - public function getUniqueId() + public function getUniqueId(): string { return get_called_class() . '|' . json_encode(ksort($this->options)); } @@ -221,7 +97,7 @@ public function getUniqueId() * @param string $name * @param mixed $value * - * @return \Sirius\Validation\Rule\AbstractRule + * @return AbstractRule */ public function setOption($name, $value) { @@ -254,8 +130,8 @@ public function getOption($name) * * @param array|object $context * - * @throws \InvalidArgumentException - * @return \Sirius\Validation\Rule\AbstractRule + * @return AbstractRule + *@throws \InvalidArgumentException */ public function setContext($context = null) { @@ -268,7 +144,7 @@ public function setContext($context = null) if (! is_object($context) || ! $context instanceof WrapperInterface) { throw new \InvalidArgumentException( 'Validator context must be either an array or an instance - of Sirius\Validator\DataWrapper\WrapperInterface' + of ' . WrapperInterface::class ); } $this->context = $context; @@ -281,7 +157,7 @@ public function setContext($context = null) * * @param string $messageTemplate * - * @return \Sirius\Validation\Rule\AbstractRule + * @return AbstractRule */ public function setMessageTemplate($messageTemplate) { @@ -295,7 +171,7 @@ public function setMessageTemplate($messageTemplate) * * @return string */ - public function getMessageTemplate() + public function getMessageTemplate(): string { if ($this->messageTemplate) { return $this->messageTemplate; @@ -315,7 +191,7 @@ public function getMessageTemplate() * * @return mixed */ - abstract public function validate($value, $valueIdentifier = null); + abstract public function validate($value, string $valueIdentifier = null); /** * Sets the error message prototype that will be used when returning the error message @@ -324,8 +200,8 @@ abstract public function validate($value, $valueIdentifier = null); * * @param ErrorMessage $errorMessagePrototype * + * @return AbstractRule * @throws \InvalidArgumentException - * @return \Sirius\Validation\Rule\AbstractRule */ public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype) { @@ -352,7 +228,7 @@ public function getErrorMessagePrototype() /** * Retrieve the error message if validation failed * - * @return NULL|\Sirius\Validation\ErrorMessage + * @return NULL|ErrorMessage */ public function getMessage() { @@ -360,11 +236,9 @@ public function getMessage() return null; } $message = $this->getPotentialMessage(); - $message->setVariables( - array( - 'value' => $this->value - ) - ); + $message->setVariables([ + 'value' => $this->value + ]); return $message; } @@ -377,7 +251,7 @@ public function getMessage() */ public function getPotentialMessage() { - $message = clone ($this->getErrorMessagePrototype()); + $message = clone $this->getErrorMessagePrototype(); $message->setTemplate($this->getMessageTemplate()); $message->setVariables($this->options); @@ -411,7 +285,7 @@ protected function getRelatedValueIdentifier($valueIdentifier, $relatedItem) } // the result should be ['lines', '5', 'quantity'] - $relatedValueIdentifierParts = array(); + $relatedValueIdentifierParts = []; foreach ($relatedItemParts as $index => $part) { if ($part === '*' && isset($valueIdentifierParts[$index])) { $relatedValueIdentifierParts[] = $valueIdentifierParts[$index]; diff --git a/src/Rule/AbstractStringRule.php b/src/Rule/AbstractStringRule.php index ba9ff4c..4f04419 100644 --- a/src/Rule/AbstractStringRule.php +++ b/src/Rule/AbstractStringRule.php @@ -1,4 +1,5 @@ value = $value; $this->success = (bool) ctype_alpha((string) str_replace(' ', '', $value)); diff --git a/src/Rule/AlphaNumHyphen.php b/src/Rule/AlphaNumHyphen.php index b6cd55b..81307a9 100755 --- a/src/Rule/AlphaNumHyphen.php +++ b/src/Rule/AlphaNumHyphen.php @@ -1,4 +1,5 @@ value = $value; $this->success = (bool) ctype_alnum( (string) str_replace( - array( + [ ' ', '_', '-' - ), + ], '', $value ) diff --git a/src/Rule/AlphaNumeric.php b/src/Rule/AlphaNumeric.php index e663bf6..7450723 100755 --- a/src/Rule/AlphaNumeric.php +++ b/src/Rule/AlphaNumeric.php @@ -1,4 +1,5 @@ value = $value; $this->success = (bool) ctype_alnum((string) str_replace(' ', '', $value)); diff --git a/src/Rule/ArrayLength.php b/src/Rule/ArrayLength.php index a3c8816..94a7346 100755 --- a/src/Rule/ArrayLength.php +++ b/src/Rule/ArrayLength.php @@ -1,4 +1,5 @@ self::OPTION_MIN, 1 => self::OPTION_MAX - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; $maxValidator = new ArrayMaxLength(); diff --git a/src/Rule/ArrayMaxLength.php b/src/Rule/ArrayMaxLength.php index 8875c19..8fa9abf 100755 --- a/src/Rule/ArrayMaxLength.php +++ b/src/Rule/ArrayMaxLength.php @@ -1,4 +1,5 @@ value = $value; if (! isset($this->options['max'])) { diff --git a/src/Rule/ArrayMinLength.php b/src/Rule/ArrayMinLength.php index 77bf840..bd1e161 100755 --- a/src/Rule/ArrayMinLength.php +++ b/src/Rule/ArrayMinLength.php @@ -1,4 +1,5 @@ self::OPTION_MIN - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! isset($this->options['min'])) { diff --git a/src/Rule/Between.php b/src/Rule/Between.php index f029c55..6ae7b8b 100755 --- a/src/Rule/Between.php +++ b/src/Rule/Between.php @@ -1,4 +1,5 @@ self::OPTION_MIN, 1 => self::OPTION_MAX - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; $minValidator = new LessThan(); diff --git a/src/Rule/Callback.php b/src/Rule/Callback.php index d6df15f..914df9c 100755 --- a/src/Rule/Callback.php +++ b/src/Rule/Callback.php @@ -1,4 +1,5 @@ options['callback'])) { $uniqueId .= '|' . $this->options['callback']; } elseif (is_array($this->options['callback'])) { - // the callback is an array that points to a static class method (eg: array('MyClass', 'method')) + // the callback is an array that points to a static class method (eg: ['MyClass', 'method']) if (is_string($this->options['callback'][0])) { $uniqueId .= '|' . implode('::', $this->options['callback']); } elseif (is_object($this->options['callback'][0])) { @@ -38,13 +39,13 @@ public function getUniqueId() return $uniqueId; } - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! isset($this->options['callback']) || ! is_callable($this->options['callback'])) { $this->success = true; } else { - $args = (isset($this->options['arguments'])) ? (array) $this->options['arguments'] : array(); + $args = (isset($this->options['arguments'])) ? (array) $this->options['arguments'] : []; array_unshift($args, $value); array_push($args, $valueIdentifier, $this->context); $this->success = (bool) call_user_func_array($this->options['callback'], $args); diff --git a/src/Rule/Date.php b/src/Rule/Date.php index 4eba3e4..2330ddf 100644 --- a/src/Rule/Date.php +++ b/src/Rule/Date.php @@ -1,4 +1,5 @@ 'Y-m-d' - ); + ]; - protected $optionsIndexMap = array( + protected $optionsIndexMap = [ 0 => self::OPTION_FORMAT - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; $this->success = $value == date( diff --git a/src/Rule/DateTime.php b/src/Rule/DateTime.php index d8b6391..48c44c4 100644 --- a/src/Rule/DateTime.php +++ b/src/Rule/DateTime.php @@ -1,4 +1,5 @@ 'Y-m-d H:i:s' - ); + ]; } diff --git a/src/Rule/Email.php b/src/Rule/Email.php index 8d7d324..6a55e85 100755 --- a/src/Rule/Email.php +++ b/src/Rule/Email.php @@ -1,4 +1,5 @@ value = $value; $this->success = (filter_var((string) $value, FILTER_VALIDATE_EMAIL) !== false); diff --git a/src/Rule/EmailDomain.php b/src/Rule/EmailDomain.php index b851eaa..d75de47 100755 --- a/src/Rule/EmailDomain.php +++ b/src/Rule/EmailDomain.php @@ -1,4 +1,5 @@ value = $value; diff --git a/src/Rule/Equal.php b/src/Rule/Equal.php index 87684e5..4ad2d3b 100644 --- a/src/Rule/Equal.php +++ b/src/Rule/Equal.php @@ -1,4 +1,5 @@ self::OPTION_VALUE - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (isset($this->options[self::OPTION_VALUE])) { diff --git a/src/Rule/File/Extension.php b/src/Rule/File/Extension.php index df31238..1b9d433 100644 --- a/src/Rule/File/Extension.php +++ b/src/Rule/File/Extension.php @@ -1,4 +1,5 @@ array() - ); + protected $options = [ + self::OPTION_ALLOWED_EXTENSIONS => [] + ]; public function setOption($name, $value) { @@ -29,7 +30,7 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! file_exists($value)) { @@ -49,11 +50,9 @@ public function getPotentialMessage() { $message = parent::getPotentialMessage(); $fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]); - $message->setVariables( - array( - 'file_extensions' => implode(', ', $fileExtensions) - ) - ); + $message->setVariables([ + 'file_extensions' => implode(', ', $fileExtensions) + ]); return $message; } diff --git a/src/Rule/File/Image.php b/src/Rule/File/Image.php index aa57e9a..753aa04 100644 --- a/src/Rule/File/Image.php +++ b/src/Rule/File/Image.php @@ -1,4 +1,5 @@ array( 'jpg', 'png', 'gif' ) - ); + protected $options = [ + self::OPTION_ALLOWED_IMAGES => ['jpg', 'png', 'gif'] + ]; - protected $imageTypesMap = array( + protected $imageTypesMap = [ IMAGETYPE_GIF => 'gif', IMAGETYPE_JPEG => 'jpg', IMAGETYPE_JPEG2000 => 'jpg', @@ -24,7 +25,7 @@ class Image extends AbstractRule IMAGETYPE_PSD => 'psd', IMAGETYPE_BMP => 'bmp', IMAGETYPE_ICO => 'ico', - ); + ]; public function setOption($name, $value) { @@ -39,7 +40,7 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! file_exists($value)) { @@ -57,11 +58,9 @@ public function getPotentialMessage() { $message = parent::getPotentialMessage(); $imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]); - $message->setVariables( - array( - 'image_types' => implode(', ', $imageTypes) - ) - ); + $message->setVariables([ + 'image_types' => implode(', ', $imageTypes) + ]); return $message; } diff --git a/src/Rule/File/ImageHeight.php b/src/Rule/File/ImageHeight.php index 7e4a6e7..769efc5 100644 --- a/src/Rule/File/ImageHeight.php +++ b/src/Rule/File/ImageHeight.php @@ -1,4 +1,5 @@ 1000000, self::OPTION_MIN => 0, - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (!file_exists($value)) { diff --git a/src/Rule/File/ImageRatio.php b/src/Rule/File/ImageRatio.php index 622be13..f86a07e 100644 --- a/src/Rule/File/ImageRatio.php +++ b/src/Rule/File/ImageRatio.php @@ -1,7 +1,9 @@ 0, self::OPTION_ERROR_MARGIN => 0, - ); + ]; protected function normalizeRatio($ratio) { @@ -34,10 +36,10 @@ protected function normalizeRatio($ratio) return 0; } - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; - $ratio = $this->normalizeRatio($this->options[self::OPTION_RATIO]); + $ratio = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]); if (! file_exists($value)) { $this->success = false; } elseif ($ratio == 0) { diff --git a/src/Rule/File/ImageWidth.php b/src/Rule/File/ImageWidth.php index 8d3cfed..04586be 100644 --- a/src/Rule/File/ImageWidth.php +++ b/src/Rule/File/ImageWidth.php @@ -1,4 +1,5 @@ 1000000, self::OPTION_MIN => 0, - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! file_exists($value)) { diff --git a/src/Rule/File/Size.php b/src/Rule/File/Size.php index 0312ccc..aafd22f 100644 --- a/src/Rule/File/Size.php +++ b/src/Rule/File/Size.php @@ -1,7 +1,9 @@ '2M' - ); + ]; - protected function normalizeSize($size) - { - $units = array( 'B' => 0, 'K' => 1, 'M' => 2, 'G' => 3 ); - $unit = strtoupper(substr($size, strlen($size) - 1, 1)); - if (! isset($units[$unit])) { - $normalizedSize = filter_var($size, FILTER_SANITIZE_NUMBER_INT); - } else { - $size = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); - $normalizedSize = $size * pow(1024, $units[$unit]); - } - - return $normalizedSize; - } - - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! file_exists($value)) { $this->success = false; } else { $fileSize = @filesize($value); - $limit = $this->normalizeSize($this->options[self::OPTION_SIZE]); + $limit = RuleHelper::normalizeFileSize($this->options[self::OPTION_SIZE]); $this->success = $fileSize && $fileSize <= $limit; } diff --git a/src/Rule/FullName.php b/src/Rule/FullName.php index 2b96145..750bcda 100755 --- a/src/Rule/FullName.php +++ b/src/Rule/FullName.php @@ -1,4 +1,5 @@ value = $value; diff --git a/src/Rule/GreaterThan.php b/src/Rule/GreaterThan.php index 182e2b4..4d43cac 100755 --- a/src/Rule/GreaterThan.php +++ b/src/Rule/GreaterThan.php @@ -1,4 +1,5 @@ true - ); + ]; - protected $optionsIndexMap = array( + protected $optionsIndexMap = [ 0 => self::OPTION_MIN, 1 => self::OPTION_INCLUSIVE - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! isset($this->options['min'])) { diff --git a/src/Rule/InList.php b/src/Rule/InList.php index 5975a51..ec6688a 100755 --- a/src/Rule/InList.php +++ b/src/Rule/InList.php @@ -1,4 +1,5 @@ self::OPTION_LIST - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! isset($this->options['list'])) { diff --git a/src/Rule/Integer.php b/src/Rule/Integer.php index 158cb3d..cb6a1db 100644 --- a/src/Rule/Integer.php +++ b/src/Rule/Integer.php @@ -1,4 +1,5 @@ value = $value; $this->success = (bool) filter_var($value, FILTER_VALIDATE_INT) || (string) $value === '0'; diff --git a/src/Rule/IpAddress.php b/src/Rule/IpAddress.php index 855b384..64ea922 100755 --- a/src/Rule/IpAddress.php +++ b/src/Rule/IpAddress.php @@ -1,4 +1,5 @@ value = $value; // Do not allow private and reserved range IPs diff --git a/src/Rule/Length.php b/src/Rule/Length.php index 87bcc55..68cef6f 100755 --- a/src/Rule/Length.php +++ b/src/Rule/Length.php @@ -1,4 +1,5 @@ self::OPTION_MIN, 1 => self::OPTION_MAX, 2 => self::OPTION_ENCODING - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; $maxValidator = new MinLength(); diff --git a/src/Rule/LessThan.php b/src/Rule/LessThan.php index 4fcd406..e67fc91 100755 --- a/src/Rule/LessThan.php +++ b/src/Rule/LessThan.php @@ -1,4 +1,5 @@ true - ); + ]; - protected $optionsIndexMap = array( + protected $optionsIndexMap = [ 0 => self::OPTION_MAX, 1 => self::OPTION_INCLUSIVE - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! isset($this->options['max'])) { diff --git a/src/Rule/Match.php b/src/Rule/Match.php index 61c8c2f..4c4f36a 100644 --- a/src/Rule/Match.php +++ b/src/Rule/Match.php @@ -1,4 +1,5 @@ self::OPTION_ITEM - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (isset($this->options[self::OPTION_ITEM])) { diff --git a/src/Rule/MaxLength.php b/src/Rule/MaxLength.php index ef796b2..2b44278 100755 --- a/src/Rule/MaxLength.php +++ b/src/Rule/MaxLength.php @@ -1,4 +1,5 @@ self::OPTION_MAX, 1 => self::OPTION_ENCODING - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! isset($this->options['max'])) { diff --git a/src/Rule/MinLength.php b/src/Rule/MinLength.php index e470a39..e98433c 100755 --- a/src/Rule/MinLength.php +++ b/src/Rule/MinLength.php @@ -1,4 +1,5 @@ self::OPTION_MIN, 1 => self::OPTION_ENCODING - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! isset($this->options['min'])) { diff --git a/src/Rule/NotEqual.php b/src/Rule/NotEqual.php index 340cfae..720b90c 100644 --- a/src/Rule/NotEqual.php +++ b/src/Rule/NotEqual.php @@ -1,4 +1,5 @@ success = ! $this->success; diff --git a/src/Rule/NotInList.php b/src/Rule/NotInList.php index 00c5167..ac10d5c 100755 --- a/src/Rule/NotInList.php +++ b/src/Rule/NotInList.php @@ -1,4 +1,5 @@ self::OPTION_LIST - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! isset($this->options['list'])) { diff --git a/src/Rule/NotMatch.php b/src/Rule/NotMatch.php index 61db020..7e2c65a 100644 --- a/src/Rule/NotMatch.php +++ b/src/Rule/NotMatch.php @@ -1,4 +1,5 @@ success = ! $this->success; diff --git a/src/Rule/NotRegex.php b/src/Rule/NotRegex.php index abdfb9d..2e76192 100755 --- a/src/Rule/NotRegex.php +++ b/src/Rule/NotRegex.php @@ -1,4 +1,5 @@ success = ! $this->success; diff --git a/src/Rule/Number.php b/src/Rule/Number.php index e7d8d94..c25ac1e 100644 --- a/src/Rule/Number.php +++ b/src/Rule/Number.php @@ -1,4 +1,5 @@ value = $value; $this->success = (bool) filter_var($value, FILTER_VALIDATE_FLOAT) || (string) $value === '0'; diff --git a/src/Rule/Regex.php b/src/Rule/Regex.php index 1867b4e..ec8e6ad 100755 --- a/src/Rule/Regex.php +++ b/src/Rule/Regex.php @@ -1,4 +1,5 @@ self::OPTION_PATTERN - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (isset($this->options['pattern'])) { diff --git a/src/Rule/Required.php b/src/Rule/Required.php index 7f9012b..80da45d 100755 --- a/src/Rule/Required.php +++ b/src/Rule/Required.php @@ -1,4 +1,5 @@ value = $value; $this->success = ($value !== null && $value !== ''); diff --git a/src/Rule/RequiredWhen.php b/src/Rule/RequiredWhen.php index 2cf9b2c..9cc6919 100644 --- a/src/Rule/RequiredWhen.php +++ b/src/Rule/RequiredWhen.php @@ -1,4 +1,5 @@ options[self::OPTION_RULE_OPTIONS])) ? (array) $this->options[self::OPTION_RULE_OPTIONS] : - array(); + []; if (is_string($this->options[self::OPTION_RULE])) { $ruleClass = $this->options[self::OPTION_RULE]; @@ -36,13 +37,13 @@ public function getItemRule() 'Validator for the other item is not valid or cannot be constructed based on the data provided' ); } - $context = $this->context ? $this->context : array(); + $context = $this->context ? $this->context : []; $rule->setContext($context); return $rule; } - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; diff --git a/src/Rule/RequiredWith.php b/src/Rule/RequiredWith.php index 9e01b5a..54ca5ef 100644 --- a/src/Rule/RequiredWith.php +++ b/src/Rule/RequiredWith.php @@ -1,4 +1,5 @@ self::OPTION_ITEM - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; @@ -20,7 +21,7 @@ public function validate($value, $valueIdentifier = null) $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; if (isset($this->options[self::OPTION_ITEM]) && $relatedItemValue !== null) { - $this->success = ($value !== null && trim($value) !== ''); + $this->success = ($value !== null && trim((string)$value) !== ''); } else { $this->success = true; } diff --git a/src/Rule/RequiredWithout.php b/src/Rule/RequiredWithout.php index e76c53d..1b35ff0 100644 --- a/src/Rule/RequiredWithout.php +++ b/src/Rule/RequiredWithout.php @@ -1,4 +1,5 @@ self::OPTION_ITEM - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; diff --git a/src/Rule/Time.php b/src/Rule/Time.php index b2d9c7d..2bf1285 100644 --- a/src/Rule/Time.php +++ b/src/Rule/Time.php @@ -1,4 +1,5 @@ 'H:i:s' - ); + ]; } diff --git a/src/Rule/Upload/Extension.php b/src/Rule/Upload/Extension.php index c0efb94..428e0fc 100644 --- a/src/Rule/Upload/Extension.php +++ b/src/Rule/Upload/Extension.php @@ -1,4 +1,5 @@ array() - ); + protected $options = [ + self::OPTION_ALLOWED_EXTENSIONS => [] + ]; public function setOption($name, $value) { @@ -29,7 +30,7 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { @@ -51,11 +52,9 @@ public function getPotentialMessage() { $message = parent::getPotentialMessage(); $fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]); - $message->setVariables( - array( - 'file_extensions' => implode(', ', $fileExtensions) - ) - ); + $message->setVariables([ + 'file_extensions' => implode(', ', $fileExtensions) + ]); return $message; } diff --git a/src/Rule/Upload/Image.php b/src/Rule/Upload/Image.php index d2f92e9..fa32f12 100644 --- a/src/Rule/Upload/Image.php +++ b/src/Rule/Upload/Image.php @@ -1,4 +1,5 @@ array( 'jpg', 'png', 'gif' ) - ); + protected $options = [ + self::OPTION_ALLOWED_IMAGES => ['jpg', 'png', 'gif'] + ]; - protected $imageTypesMap = array( + protected $imageTypesMap = [ IMAGETYPE_GIF => 'gif', IMAGETYPE_JPEG => 'jpg', IMAGETYPE_JPEG2000 => 'jpg', @@ -24,7 +25,7 @@ class Image extends AbstractRule IMAGETYPE_PSD => 'psd', IMAGETYPE_BMP => 'bmp', IMAGETYPE_ICO => 'ico', - ); + ]; public function setOption($name, $value) { @@ -39,7 +40,7 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { @@ -59,11 +60,9 @@ public function getPotentialMessage() { $message = parent::getPotentialMessage(); $imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]); - $message->setVariables( - array( - 'image_types' => implode(', ', $imageTypes) - ) - ); + $message->setVariables([ + 'image_types' => implode(', ', $imageTypes) + ]); return $message; } diff --git a/src/Rule/Upload/ImageHeight.php b/src/Rule/Upload/ImageHeight.php index b6e0f15..1a26d94 100644 --- a/src/Rule/Upload/ImageHeight.php +++ b/src/Rule/Upload/ImageHeight.php @@ -1,4 +1,5 @@ 1000000, self::OPTION_MIN => 0, - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { diff --git a/src/Rule/Upload/ImageRatio.php b/src/Rule/Upload/ImageRatio.php index 647d794..630c016 100644 --- a/src/Rule/Upload/ImageRatio.php +++ b/src/Rule/Upload/ImageRatio.php @@ -1,7 +1,9 @@ 0, self::OPTION_ERROR_MARGIN => 0, - ); + ]; - protected function normalizeRatio($ratio) - { - if (is_numeric($ratio) || $ratio == filter_var($ratio, FILTER_SANITIZE_NUMBER_FLOAT)) { - return floatval($ratio); - } - if (strpos($ratio, ':') !== false) { - list($width, $height) = explode(':', $ratio); - - return $width / $height; - } - - return 0; - } - - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; - $ratio = $this->normalizeRatio($this->options[self::OPTION_RATIO]); + $ratio = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]); if (! is_array($value) || ! isset($value['tmp_name'])) { $this->success = false; } elseif (! file_exists($value['tmp_name'])) { diff --git a/src/Rule/Upload/ImageWidth.php b/src/Rule/Upload/ImageWidth.php index 190797a..aedef62 100644 --- a/src/Rule/Upload/ImageWidth.php +++ b/src/Rule/Upload/ImageWidth.php @@ -1,4 +1,5 @@ 1000000, self::OPTION_MIN => 0, - ); + ]; - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { diff --git a/src/Rule/Upload/Required.php b/src/Rule/Upload/Required.php index e109469..bc59b53 100644 --- a/src/Rule/Upload/Required.php +++ b/src/Rule/Upload/Required.php @@ -1,4 +1,5 @@ value = $value; if (! is_array($value) || ! isset($value['tmp_name']) || diff --git a/src/Rule/Upload/Size.php b/src/Rule/Upload/Size.php index 83c602d..8e081b5 100644 --- a/src/Rule/Upload/Size.php +++ b/src/Rule/Upload/Size.php @@ -1,7 +1,9 @@ '2M' - ); + ]; - protected function normalizeSize($size) - { - $units = array( 'B' => 0, 'K' => 1, 'M' => 2, 'G' => 3 ); - $unit = strtoupper(substr($size, strlen($size) - 1, 1)); - if (! isset($units[$unit])) { - $normalizedSize = filter_var($size, FILTER_SANITIZE_NUMBER_INT); - } else { - $size = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); - $normalizedSize = $size * pow(1024, $units[$unit]); - } - - return $normalizedSize; - } - - public function validate($value, $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null) { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { @@ -38,7 +26,7 @@ public function validate($value, $valueIdentifier = null) $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { $fileSize = @filesize($value['tmp_name']); - $limit = $this->normalizeSize($this->options[self::OPTION_SIZE]); + $limit = RuleHelper::normalizeFileSize($this->options[self::OPTION_SIZE]); $this->success = $fileSize && $fileSize <= $limit; } diff --git a/src/Rule/Url.php b/src/Rule/Url.php index 97bb352..e416bbd 100755 --- a/src/Rule/Url.php +++ b/src/Rule/Url.php @@ -1,4 +1,5 @@ value = $value; $this->success = (bool) filter_var($value, FILTER_VALIDATE_URL); diff --git a/src/Rule/Website.php b/src/Rule/Website.php index ffd3b7f..0a42468 100755 --- a/src/Rule/Website.php +++ b/src/Rule/Website.php @@ -1,4 +1,5 @@ value = $value; $this->success = (substr($value, 0, 2) == '//') diff --git a/src/RuleCollection.php b/src/RuleCollection.php index d26d35d..93fc75e 100644 --- a/src/RuleCollection.php +++ b/src/RuleCollection.php @@ -1,4 +1,5 @@ detach($r); diff --git a/src/RuleFactory.php b/src/RuleFactory.php index 05519db..daedc0d 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -1,4 +1,5 @@ $name, - 'arguments' => $options - ) - ); + $validator = new CallbackRule([ + 'callback' => $name, + 'arguments' => $options + ]); } elseif (is_string($name)) { $name = trim($name); // use the validator map diff --git a/src/Util/Arr.php b/src/Util/Arr.php index ac555e5..ef7e2b6 100644 --- a/src/Util/Arr.php +++ b/src/Util/Arr.php @@ -1,4 +1,5 @@ self::getByPath($array, $selector) - ); + return [$selector => self::getByPath($array, $selector)]; } - $result = array(); + $result = []; list($preffix, $suffix) = explode('[*]', $selector, 2); $base = self::getByPath($array, $preffix); if (! is_array($base)) { - $base = array(); + $base = []; } // we don't have a suffix, the selector was something like path[subpath][*] if (! $suffix) { diff --git a/src/Util/RuleHelper.php b/src/Util/RuleHelper.php new file mode 100644 index 0000000..fbbd332 --- /dev/null +++ b/src/Util/RuleHelper.php @@ -0,0 +1,164 @@ + 0) { + $options = [$optionsIndexMap[0] => '0']; + } + if (! $options) { + return []; + } + + if (is_array($options) && static::arrayIsAssoc($options)) { + return $options; + } + + $result = $options; + if ($options && is_string($options)) { + $startChar = substr($options, 0, 1); + if ($startChar == '{') { + $result = json_decode($options, true); + } elseif (strpos($options, '=') !== false) { + $result = static::parseHttpQueryString($options); + } else { + $result = static::parseCsvString($options, $optionsIndexMap); + } + } + + if (! is_array($result)) { + throw new \InvalidArgumentException('Validator options should be an array, JSON string or query string'); + } + + return $result; + } + + /** + * Converts a HTTP query string to an array + * + * @param $str + * + * @return array + */ + public static function parseHttpQueryString(string $str) + { + parse_str($str, $arr); + + return static::convertBooleanStrings($arr); + } + + /** + * Converts 'true' and 'false' strings to TRUE and FALSE + * + * @param $arr + * + * @return bool|array + */ + public static function convertBooleanStrings($arr) + { + if (is_array($arr)) { + return array_map([ __CLASS__, 'convertBooleanStrings'], $arr); + } + if ($arr === 'true') { + return true; + } + if ($arr === 'false') { + return false; + } + + return $arr; + } + + + /** + * Parses a CSV string and converts the result into an "options" array + * (an associative array that contains the options for the validation rule) + * + * @param $str + * + * @param array $optionsIndexMap + * + * @return array + */ + public static function parseCsvString($str, array $optionsIndexMap = []) + { + if (! isset($optionsIndexMap) || ! is_array($optionsIndexMap) || empty($optionsIndexMap)) { + throw new \InvalidArgumentException( + '`$optionsIndexMap` argument must be provided for CSV-type parameters' + ); + } + + $options = explode(',', $str); + $result = []; + foreach ($options as $k => $v) { + if (! isset($optionsIndexMap[$k])) { + throw new \InvalidArgumentException(sprintf( + '`$optionsIndexMap` for the validator is missing the %s index', + $k + )); + } + $result[$optionsIndexMap[$k]] = $v; + } + + return static::convertBooleanStrings($result); + } + + /** + * Checks if an array is associative (ie: the keys are not numbers in sequence) + * + * @param array $arr + * + * @return bool + */ + public static function arrayIsAssoc($arr) + { + return array_keys($arr) !== range(0, count($arr)); + } + + public static function normalizeFileSize($size) + { + $size = (string) $size; + $units = ['B' => 0, 'K' => 1, 'M' => 2, 'G' => 3 ]; + $unit = strtoupper(substr($size, strlen($size) - 1, 1)); + if (! isset($units[$unit])) { + $normalizedSize = filter_var($size, FILTER_SANITIZE_NUMBER_INT); + } else { + $size = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); + $normalizedSize = $size * pow(1024, $units[$unit]); + } + + return $normalizedSize; + } + + + + public static function normalizeImageRatio($ratio) + { + if (is_numeric($ratio) || $ratio == filter_var($ratio, FILTER_SANITIZE_NUMBER_FLOAT)) { + return floatval($ratio); + } + if (strpos($ratio, ':') !== false) { + list($width, $height) = explode(':', $ratio); + + return $width / $height; + } + + return 0; + } +} diff --git a/src/Validator.php b/src/Validator.php index 7f2b43b..d9523f2 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -1,4 +1,5 @@ add(array( * 'field_a' => 'required', - * 'field_b' => array('required', array('email', null, '{label} must be an email', 'Field B')), + * 'field_b' => ['required', ['email', null, '{label} must be an email', 'Field B']], * )); * * // add multiple rules using arrays - * $validator->add('field', array('required', 'email')); + * $validator->add('field', ['required', 'email']); * * // add multiple rules using a string * $validator->add('field', 'required | email'); * * // add validator with options - * $validator->add('field:Label', 'minlength', array('min' => 2), '{label} should have at least {min} characters'); - * - * // add validator with string and parameters as JSON string - * $validator->add('field:Label', 'minlength({"min": 2})({label} should have at least {min} characters)'); + * $validator->add('field:Label', 'minlength', ['min' => 2], '{label} should have at least {min} characters'); * * // add validator with string and parameters as query string * $validator->add('field:label', 'minlength(min=2)({label} should have at least {min} characters)'); @@ -249,14 +247,8 @@ public function addMultiple($selectorRulesCollection) // the rule is an array, this means it contains $name, $options, $messageTemplate, $label if (is_array($rule)) { array_unshift($rule, $selector); - call_user_func_array( - array( - $this, - 'add' - ), - $rule - ); - // the rule is only the name of the validator + call_user_func_array([$this, 'add'], $rule); + // the rule is only the name of the validator } else { $this->add($selector, $rule); } @@ -311,7 +303,7 @@ public function setData($data) $this->getDataWrapper($data); $this->wasValidated = false; // reset messages - $this->messages = array(); + $this->messages = []; return $this; } @@ -361,7 +353,7 @@ public function addMessage($item, $message = null) return $this; } if (!array_key_exists($item, $this->messages)) { - $this->messages[$item] = array(); + $this->messages[$item] = []; } $this->messages[$item][] = $message; @@ -382,7 +374,7 @@ public function clearMessages($item = null) unset($this->messages[$item]); } } elseif ($item === null) { - $this->messages = array(); + $this->messages = []; } return $this; @@ -397,7 +389,7 @@ public function clearMessages($item = null) public function getMessages($item = null) { if (is_string($item)) { - return array_key_exists($item, $this->messages) ? $this->messages[$item] : array(); + return array_key_exists($item, $this->messages) ? $this->messages[$item] : []; } return $this->messages; diff --git a/src/ValidatorInterface.php b/src/ValidatorInterface.php index 591cd1f..872393d 100644 --- a/src/ValidatorInterface.php +++ b/src/ValidatorInterface.php @@ -1,4 +1,5 @@ add(array( * 'required', - * array('required', array('email', null, '{label} must be an email', 'Field B')), + * ['required', ['email', null, '{label} must be an email', 'Field B']], * )); * * // add multiple rules using a string * $validator->add('required | email'); * * // add validator with options - * $validator->add('minlength', array('min' => 2), '{label} should have at least {min} characters', 'Field label'); + * $validator->add('minlength', ['min' => 2], '{label} should have at least {min} characters', 'Field label'); * * // add validator with string and parameters as JSON string * $validator->add('minlength({"min": 2})({label} should have at least {min} characters)(Field label)'); @@ -133,16 +134,8 @@ public function addMultiple($rules) { foreach ($rules as $singleRule) { // make sure the rule is an array (the parameters of subsequent calls); - $singleRule = is_array($singleRule) ? $singleRule : array( - $singleRule - ); - call_user_func_array( - array( - $this, - 'add' - ), - $singleRule - ); + $singleRule = is_array($singleRule) ? $singleRule : [$singleRule]; + call_user_func_array([$this, 'add'], $singleRule); } return $this; @@ -193,12 +186,12 @@ public function remove($name = true, $options = null) * * will be converted into * - * array( - * 'minLength', // validator name - * array('min' => 2'), // validator options - * '{label} must have at least {min} characters', - * 'Street' // label - * ) + * [ + * 'minLength', // validator name + * ['min' => 2'], // validator options + * '{label} must have at least {min} characters', + * 'Street' // label + * ] * * @param string $ruleAsString * @@ -207,13 +200,13 @@ public function remove($name = true, $options = null) protected function parseRule($ruleAsString) { $ruleAsString = trim($ruleAsString); - $options = array(); + $options = []; $messageTemplate = null; $label = null; $name = substr($ruleAsString, 0, strpos($ruleAsString, '(')); $ruleAsString = substr($ruleAsString, strpos($ruleAsString, '(')); - $matches = array(); + $matches = []; preg_match_all('/\(([^\)]*)\)/', $ruleAsString, $matches); if (isset($matches[1])) { @@ -228,18 +221,18 @@ protected function parseRule($ruleAsString) } } - return array( + return [ $name, $options, $messageTemplate, $label - ); + ]; } - public function validate($value, $valueIdentifier = null, DataWrapper\WrapperInterface $context = null) + public function validate($value, string $valueIdentifier = null, DataWrapper\WrapperInterface $context = null) { - $this->messages = array(); + $this->messages = []; $isRequired = false; // evaluate the required rules @@ -304,6 +297,6 @@ public function getRules() protected function isEmpty($value) { - return in_array($value, array(null, ''), true); + return in_array($value, [null, ''], true); } } diff --git a/tests/phpunit.xml b/tests/phpunit.xml index cbabf13..e8ed11d 100644 --- a/tests/phpunit.xml +++ b/tests/phpunit.xml @@ -1,5 +1,14 @@ - - + @@ -9,4 +18,9 @@ ./src/ + + + ./../src + + diff --git a/tests/src/ComplexTest.php b/tests/src/ComplexTest.php index fba184b..447491c 100644 --- a/tests/src/ComplexTest.php +++ b/tests/src/ComplexTest.php @@ -3,10 +3,10 @@ namespace Sirius\Validation; -class ComplexTest extends \PHPUnit_Framework_TestCase +class ComplexTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new Validator(); $this->validator diff --git a/tests/src/ErrorMessageTest.php b/tests/src/ErrorMessageTest.php index f1a61bf..ad51a16 100644 --- a/tests/src/ErrorMessageTest.php +++ b/tests/src/ErrorMessageTest.php @@ -12,10 +12,10 @@ function __toString() } -class ErrorMessageTest extends \PHPUnit_Framework_TestCase +class ErrorMessageTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new Validator(); $this->validator->setErrorMessagePrototype(new CustomErrorMessage()); diff --git a/tests/src/HelperTest.php b/tests/src/HelperTest.php index 467bd27..8bd039d 100755 --- a/tests/src/HelperTest.php +++ b/tests/src/HelperTest.php @@ -1,7 +1,7 @@ setExpectedException('InvalidArgumentException'); + $this->expectException('InvalidArgumentException'); Helper::addMethod('mySecondValidation', 'nonexistantcallback'); $this->assertTrue(Helper::mySecondValidation(5)); } diff --git a/tests/src/Rule/AbstractValidatorTest.php b/tests/src/Rule/AbstractValidatorTest.php index d4e356c..e24f934 100755 --- a/tests/src/Rule/AbstractValidatorTest.php +++ b/tests/src/Rule/AbstractValidatorTest.php @@ -15,10 +15,10 @@ function validate($value, $valueIdentifier = null) } -class AbstractRuleTest extends \PHPUnit_Framework_TestCase +class AbstractRuleTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new FakeRule(); } @@ -62,7 +62,7 @@ function testErrorMessageTemplateIsUsed() function testErrorThrownOnInvalidContext() { - $this->setExpectedException('\InvalidArgumentException'); + $this->expectException('\InvalidArgumentException'); $this->rule->setContext(new \stdClass()); } diff --git a/tests/src/Rule/ArrayMaxLengthTest.php b/tests/src/Rule/ArrayMaxLengthTest.php index c11a310..bf7e967 100755 --- a/tests/src/Rule/ArrayMaxLengthTest.php +++ b/tests/src/Rule/ArrayMaxLengthTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\ArrayMaxLength as Rule; -class ArrayMaxLengthTest extends \PHPUnit_Framework_TestCase +class ArrayMaxLengthTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/ArrayMinLengthTest.php b/tests/src/Rule/ArrayMinLengthTest.php index 46f2b3c..9b3048e 100755 --- a/tests/src/Rule/ArrayMinLengthTest.php +++ b/tests/src/Rule/ArrayMinLengthTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\ArrayMinLength as Rule; -class ArrayMinLengthTest extends \PHPUnit_Framework_TestCase +class ArrayMinLengthTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/BetweenTest.php b/tests/src/Rule/BetweenTest.php index 22d9ebf..47e38b4 100644 --- a/tests/src/Rule/BetweenTest.php +++ b/tests/src/Rule/BetweenTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\Between as Rule; -class BetweenTest extends \PHPUnit_Framework_TestCase +class BetweenTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/CallbackTest.php b/tests/src/Rule/CallbackTest.php index 998c2fd..58af382 100644 --- a/tests/src/Rule/CallbackTest.php +++ b/tests/src/Rule/CallbackTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\Callback as Rule; -class CallbackTest extends \PHPUnit_Framework_TestCase +class CallbackTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/EmailTest.php b/tests/src/Rule/EmailTest.php index 84adabd..db3b686 100644 --- a/tests/src/Rule/EmailTest.php +++ b/tests/src/Rule/EmailTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\Email as Rule; -class EmailTest extends \PHPUnit_Framework_TestCase +class EmailTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/EqualTest.php b/tests/src/Rule/EqualTest.php index a3c09a3..82fd389 100644 --- a/tests/src/Rule/EqualTest.php +++ b/tests/src/Rule/EqualTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\Equal as Rule; -class EqualTest extends \PHPUnit_Framework_TestCase +class EqualTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/File/ExtensionTest.php b/tests/src/Rule/File/ExtensionTest.php index 60ac725..0b3eec7 100644 --- a/tests/src/Rule/File/ExtensionTest.php +++ b/tests/src/Rule/File/ExtensionTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\File; -class ExtensionTest extends \PHPUnit_Framework_TestCase +class ExtensionTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new Extension(); } diff --git a/tests/src/Rule/File/ImageHeightTest.php b/tests/src/Rule/File/ImageHeightTest.php index 3c326b7..31ea2c6 100644 --- a/tests/src/Rule/File/ImageHeightTest.php +++ b/tests/src/Rule/File/ImageHeightTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\File; -class ImageHeightTest extends \PHPUnit_Framework_TestCase +class ImageHeightTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new ImageHeight(array( 'min' => 400 )); } diff --git a/tests/src/Rule/File/ImageRatioTest.php b/tests/src/Rule/File/ImageRatioTest.php index dac7363..db08e17 100644 --- a/tests/src/Rule/File/ImageRatioTest.php +++ b/tests/src/Rule/File/ImageRatioTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\File; -class ImageRatioTest extends \PHPUnit_Framework_TestCase +class ImageRatioTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new ImageRatio(array( 'ratio' => 1 )); } diff --git a/tests/src/Rule/File/ImageTest.php b/tests/src/Rule/File/ImageTest.php index 31012b6..02d1817 100644 --- a/tests/src/Rule/File/ImageTest.php +++ b/tests/src/Rule/File/ImageTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\File; -class ImageTest extends \PHPUnit_Framework_TestCase +class ImageTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new Image(); } diff --git a/tests/src/Rule/File/ImageWidthTest.php b/tests/src/Rule/File/ImageWidthTest.php index e49720f..800af11 100644 --- a/tests/src/Rule/File/ImageWidthTest.php +++ b/tests/src/Rule/File/ImageWidthTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\File; -class ImageWidthTest extends \PHPUnit_Framework_TestCase +class ImageWidthTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new ImageWidth(array( 'min' => 500 )); } diff --git a/tests/src/Rule/File/SizeTest.php b/tests/src/Rule/File/SizeTest.php index 5511ae2..455efd1 100644 --- a/tests/src/Rule/File/SizeTest.php +++ b/tests/src/Rule/File/SizeTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\File; -class SizeTest extends \PHPUnit_Framework_TestCase +class SizeTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new Size(array( 'size' => '1M' )); } diff --git a/tests/src/Rule/GreaterThanTest.php b/tests/src/Rule/GreaterThanTest.php index 9a5d688..ab8ed52 100755 --- a/tests/src/Rule/GreaterThanTest.php +++ b/tests/src/Rule/GreaterThanTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\GreaterThan as Rule; -class GreaterThanTest extends \PHPUnit_Framework_TestCase +class GreaterThanTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/InListTest.php b/tests/src/Rule/InListTest.php index e8cf996..3202e47 100755 --- a/tests/src/Rule/InListTest.php +++ b/tests/src/Rule/InListTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\InList as Rule; -class InListTest extends \PHPUnit_Framework_TestCase +class InListTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/IntegerTest.php b/tests/src/Rule/IntegerTest.php index c3cda25..78b5404 100644 --- a/tests/src/Rule/IntegerTest.php +++ b/tests/src/Rule/IntegerTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\Integer as Rule; -class IntegerTest extends \PHPUnit_Framework_TestCase +class IntegerTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/LessThanTest.php b/tests/src/Rule/LessThanTest.php index 090f506..c61c8bc 100755 --- a/tests/src/Rule/LessThanTest.php +++ b/tests/src/Rule/LessThanTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\LessThan as Rule; -class LessThanTest extends \PHPUnit_Framework_TestCase +class LessThanTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/MatchTest.php b/tests/src/Rule/MatchTest.php index 7355318..25f0c59 100644 --- a/tests/src/Rule/MatchTest.php +++ b/tests/src/Rule/MatchTest.php @@ -5,10 +5,10 @@ use Sirius\Validation\DataWrapper\ArrayWrapper; use Sirius\Validation\Rule\Match as Rule; -class MatchTest extends \PHPUnit_Framework_TestCase +class MatchTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); $this->rule->setContext( diff --git a/tests/src/Rule/NotEqualTest.php b/tests/src/Rule/NotEqualTest.php index d04b4d0..1a19a44 100644 --- a/tests/src/Rule/NotEqualTest.php +++ b/tests/src/Rule/NotEqualTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\NotEqual as Rule; -class NotEqualTest extends \PHPUnit_Framework_TestCase +class NotEqualTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/NotInListTest.php b/tests/src/Rule/NotInListTest.php index 8c5384f..8bd91b1 100755 --- a/tests/src/Rule/NotInListTest.php +++ b/tests/src/Rule/NotInListTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\NotInList as Rule; -class NotInListTest extends \PHPUnit_Framework_TestCase +class NotInListTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/NotMatchTest.php b/tests/src/Rule/NotMatchTest.php index 254ea0d..6395152 100644 --- a/tests/src/Rule/NotMatchTest.php +++ b/tests/src/Rule/NotMatchTest.php @@ -5,10 +5,10 @@ use Sirius\Validation\DataWrapper\ArrayWrapper; use Sirius\Validation\Rule\NotMatch as Rule; -class NotMatchTest extends \PHPUnit_Framework_TestCase +class NotMatchTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); $this->rule->setContext( diff --git a/tests/src/Rule/NumberTest.php b/tests/src/Rule/NumberTest.php index ddf53fe..019a998 100644 --- a/tests/src/Rule/NumberTest.php +++ b/tests/src/Rule/NumberTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\Number as Rule; -class NumberTest extends \PHPUnit_Framework_TestCase +class NumberTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/RegexTest.php b/tests/src/Rule/RegexTest.php index e4b581e..2ef6ba7 100755 --- a/tests/src/Rule/RegexTest.php +++ b/tests/src/Rule/RegexTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\Regex as Rule; -class RegexTest extends \PHPUnit_Framework_TestCase +class RegexTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/RequiredTest.php b/tests/src/Rule/RequiredTest.php index 67f0e47..2252f47 100644 --- a/tests/src/Rule/RequiredTest.php +++ b/tests/src/Rule/RequiredTest.php @@ -5,7 +5,7 @@ use Sirius\Validation\DataWrapper\ArrayWrapper; use Sirius\Validation\Rule\Required as Rule; -class RequiredTest extends \PHPUnit_Framework_TestCase +class RequiredTest extends \PHPUnit\Framework\TestCase { /** @@ -13,7 +13,7 @@ class RequiredTest extends \PHPUnit_Framework_TestCase */ protected $rule; - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/RequiredWhenTest.php b/tests/src/Rule/RequiredWhenTest.php index bb1bf71..3530af3 100644 --- a/tests/src/Rule/RequiredWhenTest.php +++ b/tests/src/Rule/RequiredWhenTest.php @@ -5,10 +5,10 @@ use Sirius\Validation\DataWrapper\ArrayWrapper; use Sirius\Validation\Rule\RequiredWhen as Rule; -class RequiredWhenTest extends \PHPUnit_Framework_TestCase +class RequiredWhenTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } @@ -78,7 +78,7 @@ function testItemRuleSetAsRuleObject() function testExceptionThrownOnInvalidItemRule() { - $this->setExpectedException('\InvalidArgumentException'); + $this->expectException('\InvalidArgumentException'); $this->rule->setOption(Rule::OPTION_ITEM, 'email'); $this->rule->setOption(Rule::OPTION_RULE, new \stdClass()); $this->rule->setContext( diff --git a/tests/src/Rule/RequiredWithTest.php b/tests/src/Rule/RequiredWithTest.php index 8e0fd00..f2f5877 100644 --- a/tests/src/Rule/RequiredWithTest.php +++ b/tests/src/Rule/RequiredWithTest.php @@ -5,7 +5,7 @@ use Sirius\Validation\DataWrapper\ArrayWrapper; use Sirius\Validation\Rule\RequiredWith as Rule; -class RequiredWithTest extends \PHPUnit_Framework_TestCase +class RequiredWithTest extends \PHPUnit\Framework\TestCase { /** @@ -13,7 +13,7 @@ class RequiredWithTest extends \PHPUnit_Framework_TestCase */ protected $rule; - function setUp() + protected function setUp(): void { $this->rule = new Rule(); $this->rule->setContext( diff --git a/tests/src/Rule/RequiredWithoutTest.php b/tests/src/Rule/RequiredWithoutTest.php index 788e9c0..c8fdade 100644 --- a/tests/src/Rule/RequiredWithoutTest.php +++ b/tests/src/Rule/RequiredWithoutTest.php @@ -5,7 +5,7 @@ use Sirius\Validation\DataWrapper\ArrayWrapper; use Sirius\Validation\Rule\RequiredWithout as Rule; -class RequiredWithoutTest extends \PHPUnit_Framework_TestCase +class RequiredWithoutTest extends \PHPUnit\Framework\TestCase { /** @@ -13,7 +13,7 @@ class RequiredWithoutTest extends \PHPUnit_Framework_TestCase */ protected $rule; - function setUp() + protected function setUp(): void { $this->rule = new Rule(); $this->rule->setContext( diff --git a/tests/src/Rule/Upload/ExtensionTest.php b/tests/src/Rule/Upload/ExtensionTest.php index 3608b20..762d728 100644 --- a/tests/src/Rule/Upload/ExtensionTest.php +++ b/tests/src/Rule/Upload/ExtensionTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\Upload; -class ExtensionTest extends \PHPUnit_Framework_TestCase +class ExtensionTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new Extension(); } diff --git a/tests/src/Rule/Upload/ImageHeightTest.php b/tests/src/Rule/Upload/ImageHeightTest.php index 253edc5..54af80a 100644 --- a/tests/src/Rule/Upload/ImageHeightTest.php +++ b/tests/src/Rule/Upload/ImageHeightTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\Upload; -class ImageHeightTest extends \PHPUnit_Framework_TestCase +class ImageHeightTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new ImageHeight(array( 'min' => 400 )); } diff --git a/tests/src/Rule/Upload/ImageRatioTest.php b/tests/src/Rule/Upload/ImageRatioTest.php index adcc525..bf7d273 100644 --- a/tests/src/Rule/Upload/ImageRatioTest.php +++ b/tests/src/Rule/Upload/ImageRatioTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\Upload; -class ImageRatioTest extends \PHPUnit_Framework_TestCase +class ImageRatioTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new ImageRatio(array( 'ratio' => 1 )); } diff --git a/tests/src/Rule/Upload/ImageTest.php b/tests/src/Rule/Upload/ImageTest.php index d1d29bb..6758139 100644 --- a/tests/src/Rule/Upload/ImageTest.php +++ b/tests/src/Rule/Upload/ImageTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\Upload; -class ImageTest extends \PHPUnit_Framework_TestCase +class ImageTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new Image(); } diff --git a/tests/src/Rule/Upload/ImageWidthTest.php b/tests/src/Rule/Upload/ImageWidthTest.php index 7d547fe..919575f 100644 --- a/tests/src/Rule/Upload/ImageWidthTest.php +++ b/tests/src/Rule/Upload/ImageWidthTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\Upload; -class ImageWidthTest extends \PHPUnit_Framework_TestCase +class ImageWidthTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new ImageWidth(array( 'min' => 500 )); } diff --git a/tests/src/Rule/Upload/RequiredTest.php b/tests/src/Rule/Upload/RequiredTest.php index ae82ca4..6f947b4 100644 --- a/tests/src/Rule/Upload/RequiredTest.php +++ b/tests/src/Rule/Upload/RequiredTest.php @@ -9,10 +9,10 @@ namespace Sirius\Validation\Rule\Upload; -class RequiredTest extends \PHPUnit_Framework_TestCase +class RequiredTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new Required(); } diff --git a/tests/src/Rule/Upload/SizeTest.php b/tests/src/Rule/Upload/SizeTest.php index 4423717..98662fa 100644 --- a/tests/src/Rule/Upload/SizeTest.php +++ b/tests/src/Rule/Upload/SizeTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Rule\Upload; -class SizeTest extends \PHPUnit_Framework_TestCase +class SizeTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new Size(array( 'size' => '1M' )); } diff --git a/tests/src/Rule/UrlTest.php b/tests/src/Rule/UrlTest.php index 5c1957f..8b4065c 100644 --- a/tests/src/Rule/UrlTest.php +++ b/tests/src/Rule/UrlTest.php @@ -10,9 +10,9 @@ use Sirius\Validation\Rule\Url as Rule; -class UrlTest extends \PHPUnit_Framework_TestCase +class UrlTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/Rule/WebsiteTest.php b/tests/src/Rule/WebsiteTest.php index 62f7448..0d1bec2 100644 --- a/tests/src/Rule/WebsiteTest.php +++ b/tests/src/Rule/WebsiteTest.php @@ -4,10 +4,10 @@ use Sirius\Validation\Rule\Website as Rule; -class WebsiteTest extends \PHPUnit_Framework_TestCase +class WebsiteTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->rule = new Rule(); } diff --git a/tests/src/RuleCollectionTest.php b/tests/src/RuleCollectionTest.php index 7868554..46c1aef 100644 --- a/tests/src/RuleCollectionTest.php +++ b/tests/src/RuleCollectionTest.php @@ -1,10 +1,10 @@ collection = new RuleCollection(); } diff --git a/tests/src/RuleFactoryTest.php b/tests/src/RuleFactoryTest.php index ec43fe8..845948f 100644 --- a/tests/src/RuleFactoryTest.php +++ b/tests/src/RuleFactoryTest.php @@ -13,10 +13,10 @@ function validate($value, $valueIdentifier = null) } } -class RuleFactoryTest extends \PHPUnit_Framework_TestCase +class RuleFactoryTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->ruleFactory = new RuleFactory(); } diff --git a/tests/src/Util/ArrTest.php b/tests/src/Util/ArrTest.php index da5f75b..472b608 100644 --- a/tests/src/Util/ArrTest.php +++ b/tests/src/Util/ArrTest.php @@ -2,10 +2,10 @@ namespace Sirius\Validation\Util; -class ArrTest extends \PHPUnit_Framework_TestCase +class ArrTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->data = array( 'name' => 'John Doe', diff --git a/tests/src/ValidatorTest.php b/tests/src/ValidatorTest.php index d85cce9..818c344 100755 --- a/tests/src/ValidatorTest.php +++ b/tests/src/ValidatorTest.php @@ -15,10 +15,10 @@ function toArray() } } -class ValidatorTest extends \PHPUnit_Framework_TestCase +class ValidatorTest extends \PHPUnit\Framework\TestCase { - function setUp() + protected function setUp(): void { $this->validator = new Validator(new RuleFactory, new ErrorMessage); } @@ -43,7 +43,7 @@ function testIfMessagesCanBeSetAndCleared() function testExceptionThrownWhenTheDataIsNotAnArray() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException('InvalidArgumentException'); $this->validator->validate('string'); $this->validator->validate(false); } @@ -106,7 +106,7 @@ function testDifferentDataFormats() function testIfExceptionIsThrownOnInvalidRules() { - $this->setExpectedException('\InvalidArgumentException'); + $this->expectException('\InvalidArgumentException'); $this->validator->add('random_string'); } @@ -177,7 +177,7 @@ function testAddingValidationRulesViaStrings() function testExceptionOnInvalidValidatorOptions() { - $this->setExpectedException('\InvalidArgumentException'); + $this->expectException('\InvalidArgumentException'); $this->validator->add('item', 'required', new \stdClass()); } @@ -266,7 +266,7 @@ function testIfParametersAreSentToValidationMethods() function testIfExceptionIsThrownForInvalidValidationMethods() { - $this->setExpectedException('\InvalidArgumentException'); + $this->expectException('\InvalidArgumentException'); $this->validator->add('item', 'faker'); $this->validator->validate(array( 'item' => true )); } diff --git a/tests/src/ValueValidatorTest.php b/tests/src/ValueValidatorTest.php index f192dd5..caa119a 100644 --- a/tests/src/ValueValidatorTest.php +++ b/tests/src/ValueValidatorTest.php @@ -3,14 +3,14 @@ use Sirius\Validation\Rule\GreaterThan; -class ValueValidatorTest extends \PHPUnit_Framework_TestCase +class ValueValidatorTest extends \PHPUnit\Framework\TestCase { /** * @var ValueValidator */ private $validator; - function setUp() + protected function setUp(): void { $this->validator = new ValueValidator(); } From 58d0fbf26960f8fb43d94f217173576df4a8ec62 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 26 Feb 2020 18:58:35 +0200 Subject: [PATCH 067/112] Updated docs to use array short notation --- docs/complex_validators.md | 10 +++++----- docs/custom_rule.md | 14 +++++++------- docs/index.md | 10 +++++----- docs/simple_example.md | 4 ++-- docs/syntactic_sugar.md | 8 ++++---- docs/validator.md | 2 +- 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/docs/complex_validators.md b/docs/complex_validators.md index 838f2fb..716f7b6 100644 --- a/docs/complex_validators.md +++ b/docs/complex_validators.md @@ -50,7 +50,7 @@ $UniqueUsername = $dependencyInjectionContainer->get('UniqueUsername'); $validator = new Validator($ruleFactory); // the second parameter for the add() can be the name of a rule or a callback -$validator->add('username', array($UniqueUsername, 'validate')); +$validator->add('username', [$UniqueUsername, 'validate'];); ``` ###2. Pass the dependencies as options @@ -76,9 +76,9 @@ and in your validator you do something like ``` $dbConn = $serviceLocator->get('dbconnection'); -$validator->add('username', 'MyApp\Validation\Rule\UniqueUsername', array( +$validator->add('username', 'MyApp\Validation\Rule\UniqueUsername', [ 'db_connection' => $dbConn -)); +];); ``` ###3. Extend the `RuleFactory` class @@ -100,7 +100,7 @@ class RuleFactory extends \Sirius\Validation\RuleFactory { protected function constructValidatorByNameAndOptions($name, $options) { $validatorClass = $this->validatorsMap[$name]; - $validator = $this->dic->createInstanceWithParams($validatorClass, array($options)); + $validator = $this->dic->createInstanceWithParams($validatorClass, [$options];); return $validator; } } @@ -136,4 +136,4 @@ use Sirius\Validation\Validator; $validator = new Validator($container->get('RuleFactory')); $validator->add('username', 'MyApp\Validation\Rule\UniqueUsername'); -``` \ No newline at end of file +``` diff --git a/docs/custom_rule.md b/docs/custom_rule.md index f10ef51..968aab6 100644 --- a/docs/custom_rule.md +++ b/docs/custom_rule.md @@ -21,18 +21,18 @@ class ThisOrThat extends AbstractRule { const OPTION_THAT = 'that'; // specify default options if you want - protected $options = array( + protected $options = [ 'this' => 'a', 'that' => 'b' - ); + ];; // if you want to let the user pass the options as a CSV (eg: 'this,that') // you need to provide a `optionsIndexMap` property which will convert the options list // into an associative array of options - protected $optionsIndexMap = array( + protected $optionsIndexMap = [ 0 => self::OPTION_THIS, 1 => self::OPTION_THAT - ); + ];; function validate($value, $valueIdentifier = null) { return $value == $this->options[self::OPTION_THIS] || $value == $this->options[self::OPTION_THAT]; @@ -50,11 +50,11 @@ use Sirius\Validation\Validator; use MyApp\Validation\Rule\ThisOrThat; $validator = new Validator(); -$validator->add('key', 'MyApp\Validation\Rule\ThisOrThat', array( +$validator->add('key', 'MyApp\Validation\Rule\ThisOrThat', [ ThisOrThat::OPTION_THIS => 'c', ThisOrThat::OPTION_THAT => 'd' -)); +];); // or less verbose $validator->add('key', 'MyApp\Validation\Rule\ThisOrThat(c,d)'); -``` \ No newline at end of file +``` diff --git a/docs/index.md b/docs/index.md index a90510c..292b1ba 100755 --- a/docs/index.md +++ b/docs/index.md @@ -31,13 +31,13 @@ $validator->add(array( 'shipping_address[city]:City' => 'required' 'shipping_address[state]:State' => 'required' 'shipping_address[country]:Country' => 'required', - 'lines[*]price:Price' => array( + 'lines[*]price:Price' => [ 'requiredWith(item=lines[*]product_id', // the price is required only if a product was selected 'MyApp\Validator\Rule\InvoiceItemPrice' // another app-specific rule, specified as a class - ), - 'lines[*]quantity:Quantity' => array( + ];, + 'lines[*]quantity:Quantity' => [ 'requiredWith(item=lines[*]product_id', - ('invoice_item_quantity', 'The quantity is not valid') // here we have a custom error message + ('invoice_item_quantity', 'The quantity is not valid']; // here we have a custom error message ) )); ``` @@ -82,4 +82,4 @@ $clientSideRules = $helperThatCompilesTheClientSideValidation->getValidationRule ?> $('#myForm').validate(); -``` \ No newline at end of file +``` diff --git a/docs/simple_example.md b/docs/simple_example.md index 4f5f276..2464d6d 100644 --- a/docs/simple_example.md +++ b/docs/simple_example.md @@ -13,7 +13,7 @@ use Sirius\Validation\Validator; $validator = new Validator(); $validator->add( - array( + [ // the key is in the form [field]:[label] 'name:Name' => 'required', @@ -22,7 +22,7 @@ $validator->add( 'email:Your email' => 'required | email', // validators can have options - 'message:Your message' => 'required | minlength(10)', + 'message:Your message' => 'required | minlength(10];', // and you can overwrite the default error message 'phone:Phone' => 'regex(/your_regex_here/)(This field must be a valid US phone number)' diff --git a/docs/syntactic_sugar.md b/docs/syntactic_sugar.md index 55b36db..d487766 100644 --- a/docs/syntactic_sugar.md +++ b/docs/syntactic_sugar.md @@ -18,7 +18,7 @@ $validator->add('name', 'minlength({"min":2})({label} must have at least {min} c $validator->add('name', 'minlength(min=2)({label} must have at least {min} characters)(Name)'); // the above examples are similar to -$validator->add('name', 'minlength', array('min' => 2), '{label} must have at least {min} characters', 'Name'); +$validator->add('name', 'minlength', ['min' => 2];, '{label} must have at least {min} characters', 'Name'); ``` ##### 3. Mix and match 1 and 2 @@ -33,11 +33,11 @@ Of course this means the error message cannot contain the ` | ` sequence $validator->add( // add the label after the selector so you don't have to pass the label to every rule 'email:Email', - array( + [ // only using the name of the validation rule 'email', - // or with all parameters (here passed as CSV) - array('length', '2,100', '{label} must have between {min} and {max} characters'), + // or with all parameters (here passed as CSV]; + ['length', '2,100', '{label} must have between {min} and {max} characters'];, ) ); ``` diff --git a/docs/validator.md b/docs/validator.md index ab03f46..3ec881f 100755 --- a/docs/validator.md +++ b/docs/validator.md @@ -29,7 +29,7 @@ $validator->add($selector, $name = null, $options = null, $messageTemplate = nul // examples $validator->add('username', 'required'); -$validator->add('password', 'minLength', array('min' => 6), '{label} must have at least {min} characters', 'Password'); +$validator->add('password', 'minLength', ['min' => 6];, '{label} must have at least {min} characters', 'Password'); $validator->add('additional_emails[*]', 'email', array(), 'Email address is not valid'); ``` From 1422172d9ef26f7308ed2140b7816004057779a1 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 26 Feb 2020 18:58:49 +0200 Subject: [PATCH 068/112] Fix Travis script --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 61c5d9d..ebdf471 100755 --- a/.travis.yml +++ b/.travis.yml @@ -8,7 +8,7 @@ php: matrix: allow_failures: - - php: 7.4 + - php: 7.1 before_script: - wget -c https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar @@ -17,7 +17,7 @@ before_script: script: - mkdir -p build/logs - - composer run-script phpcs + - composer run-script cs - cd tests && ../vendor/bin/phpunit && cd .. after_script: From d45ca180764326dd066e7f90cd0741a8d48e0525 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 26 Feb 2020 19:38:38 +0200 Subject: [PATCH 069/112] Fix Travis code --- .travis.yml | 4 ++-- tests/phpunit.xml | 2 +- tests/phpunit_bootstrap.php | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index ebdf471..e757899 100755 --- a/.travis.yml +++ b/.travis.yml @@ -18,8 +18,8 @@ before_script: script: - mkdir -p build/logs - composer run-script cs - - cd tests && ../vendor/bin/phpunit && cd .. + - vendor\bin\phpunit -c tests\phpunit.xml after_script: - wget https://scrutinizer-ci.com/ocular.phar - - php ocular.phar code-coverage:upload --format=php-clover ../build/logs/clover.xml + - php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml diff --git a/tests/phpunit.xml b/tests/phpunit.xml index e8ed11d..c4db208 100644 --- a/tests/phpunit.xml +++ b/tests/phpunit.xml @@ -1,4 +1,4 @@ - Date: Wed, 26 Feb 2020 19:41:00 +0200 Subject: [PATCH 070/112] Fix Travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index e757899..9753d3a 100755 --- a/.travis.yml +++ b/.travis.yml @@ -18,7 +18,7 @@ before_script: script: - mkdir -p build/logs - composer run-script cs - - vendor\bin\phpunit -c tests\phpunit.xml + - vendor/bin/phpunit -c tests/phpunit.xml after_script: - wget https://scrutinizer-ci.com/ocular.phar From b3b5bc63495d48da060c1a1c90b55cab81a58469 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 26 Feb 2020 19:55:25 +0200 Subject: [PATCH 071/112] Fix PHP 7.4 issues --- src/Rule/File/Image.php | 8 ++++++-- src/Rule/Upload/Image.php | 8 ++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/Rule/File/Image.php b/src/Rule/File/Image.php index 753aa04..b17d630 100644 --- a/src/Rule/File/Image.php +++ b/src/Rule/File/Image.php @@ -47,8 +47,12 @@ public function validate($value, string $valueIdentifier = null) $this->success = false; } else { $imageInfo = getimagesize($value); - $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; - $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); + if (!is_array($imageInfo)) { + $this->success = false; + } else { + $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; + $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); + } } return $this->success; diff --git a/src/Rule/Upload/Image.php b/src/Rule/Upload/Image.php index fa32f12..fa1af90 100644 --- a/src/Rule/Upload/Image.php +++ b/src/Rule/Upload/Image.php @@ -49,8 +49,12 @@ public function validate($value, string $valueIdentifier = null) $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { $imageInfo = getimagesize($value['tmp_name']); - $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; - $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); + if (!is_array($imageInfo)) { + $this->success = false; + } else { + $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; + $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); + } } return $this->success; From 9cb290fd644969ffae44dac78c1c801d5fc48e14 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 26 Feb 2020 22:50:24 +0200 Subject: [PATCH 072/112] Fixed code style issues --- src/Rule/File/Image.php | 2 +- src/Rule/Upload/Image.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Rule/File/Image.php b/src/Rule/File/Image.php index b17d630..7fcf9cd 100644 --- a/src/Rule/File/Image.php +++ b/src/Rule/File/Image.php @@ -50,7 +50,7 @@ public function validate($value, string $valueIdentifier = null) if (!is_array($imageInfo)) { $this->success = false; } else { - $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; + $extension = $this->imageTypesMap[$imageInfo[2]] ?? false; $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); } } diff --git a/src/Rule/Upload/Image.php b/src/Rule/Upload/Image.php index fa1af90..a2efe1d 100644 --- a/src/Rule/Upload/Image.php +++ b/src/Rule/Upload/Image.php @@ -52,7 +52,7 @@ public function validate($value, string $valueIdentifier = null) if (!is_array($imageInfo)) { $this->success = false; } else { - $extension = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false; + $extension = $this->imageTypesMap[$imageInfo[2]] ?? false; $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); } } From 8f11752397075ecbda8c14db2f7d492a5d4e094d Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 26 Feb 2020 22:54:40 +0200 Subject: [PATCH 073/112] Updated readme --- readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/readme.md b/readme.md index a03b039..4b90a18 100755 --- a/readme.md +++ b/readme.md @@ -4,7 +4,6 @@ [![Latest Version](https://img.shields.io/packagist/v/siriusphp/validation.svg?style=flat-square)](https://github.com/siriusphp/validation/releases) [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/siriusphp/validation/blob/master/LICENSE) [![Build Status](https://img.shields.io/travis/siriusphp/validation/master.svg?style=flat-square)](https://travis-ci.org/siriusphp/validation) -[![PHP 7 ready](http://php7ready.timesplinter.ch/siriusphp/validation/master/badge.svg)](https://travis-ci.org/siriusphp/validation) [![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/siriusphp/validation.svg?style=flat-square)](https://scrutinizer-ci.com/g/siriusphp/validation/code-structure) [![Quality Score](https://img.shields.io/scrutinizer/g/siriusphp/validation.svg?style=flat-square)](https://scrutinizer-ci.com/g/siriusphp/validation) [![Total Downloads](https://img.shields.io/packagist/dt/siriusphp/validation.svg?style=flat-square)](https://packagist.org/packages/siriusphp/validation) From f5c89e53f34dd19c656d870adbb179bd93ba1681 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Thu, 27 Feb 2020 09:03:56 +0200 Subject: [PATCH 074/112] Added PHP 7 type hinting --- src/Helper.php | 76 ++++++++++++------------ src/Rule/AbstractRule.php | 6 +- src/Rule/Alpha.php | 2 +- src/Rule/AlphaNumHyphen.php | 2 +- src/Rule/AlphaNumeric.php | 2 +- src/Rule/ArrayLength.php | 2 +- src/Rule/ArrayMaxLength.php | 2 +- src/Rule/ArrayMinLength.php | 2 +- src/Rule/Between.php | 2 +- src/Rule/Callback.php | 2 +- src/Rule/Date.php | 2 +- src/Rule/Email.php | 2 +- src/Rule/EmailDomain.php | 2 +- src/Rule/Equal.php | 2 +- src/Rule/File/Extension.php | 5 +- src/Rule/File/Image.php | 5 +- src/Rule/File/ImageHeight.php | 2 +- src/Rule/File/ImageRatio.php | 2 +- src/Rule/File/ImageWidth.php | 2 +- src/Rule/File/Size.php | 2 +- src/Rule/FullName.php | 2 +- src/Rule/GreaterThan.php | 2 +- src/Rule/InList.php | 2 +- src/Rule/Integer.php | 2 +- src/Rule/IpAddress.php | 2 +- src/Rule/Length.php | 2 +- src/Rule/LessThan.php | 2 +- src/Rule/Match.php | 2 +- src/Rule/MaxLength.php | 2 +- src/Rule/MinLength.php | 2 +- src/Rule/NotEqual.php | 2 +- src/Rule/NotInList.php | 2 +- src/Rule/NotMatch.php | 2 +- src/Rule/NotRegex.php | 2 +- src/Rule/Number.php | 2 +- src/Rule/Regex.php | 2 +- src/Rule/Required.php | 2 +- src/Rule/RequiredWhen.php | 2 +- src/Rule/RequiredWith.php | 2 +- src/Rule/RequiredWithout.php | 2 +- src/Rule/Upload/Extension.php | 5 +- src/Rule/Upload/Image.php | 5 +- src/Rule/Upload/ImageHeight.php | 2 +- src/Rule/Upload/ImageRatio.php | 2 +- src/Rule/Upload/ImageWidth.php | 2 +- src/Rule/Upload/Required.php | 2 +- src/Rule/Upload/Size.php | 2 +- src/Rule/Url.php | 2 +- src/Rule/Website.php | 2 +- src/RuleCollection.php | 2 +- src/RuleFactory.php | 7 ++- src/Validator.php | 41 ++++++------- src/ValueValidator.php | 24 ++++---- tests/src/Rule/AbstractValidatorTest.php | 2 +- tests/src/RuleFactoryTest.php | 2 +- 55 files changed, 136 insertions(+), 130 deletions(-) diff --git a/src/Helper.php b/src/Helper.php index c27137e..af5ddcb 100755 --- a/src/Helper.php +++ b/src/Helper.php @@ -8,7 +8,7 @@ class Helper { protected static $methods = []; - public static function addMethod($ruleName, $callback) + public static function addMethod($ruleName, $callback):bool { if (is_callable($callback)) { self::$methods[$ruleName] = $callback; @@ -19,12 +19,12 @@ public static function addMethod($ruleName, $callback) return false; } - public static function methodExists($name) + public static function methodExists($name):bool { return method_exists(__CLASS__, $name) || array_key_exists($name, self::$methods); } - public static function __callStatic($name, $arguments) + public static function __callStatic($name, $arguments):bool { if (array_key_exists($name, self::$methods)) { return call_user_func_array(self::$methods[$name], $arguments); @@ -32,7 +32,7 @@ public static function __callStatic($name, $arguments) throw new \InvalidArgumentException(sprintf('Validation method "%s" does not exist', $name)); } - public static function callback($value, $callback, $context = []) + public static function callback($value, $callback, $context = []):bool { $validator = new Rule\Callback(); $validator->setOption('callback', $callback); @@ -41,46 +41,46 @@ public static function callback($value, $callback, $context = []) return $validator->validate($value); } - public static function required($value) + public static function required($value):bool { return $value !== null && (!is_string($value) || trim($value) !== ''); } - public static function truthy($value) + public static function truthy($value):bool { return (bool) $value; } - public static function falsy($value) + public static function falsy($value):bool { return ! static::truthy($value); } - public static function number($value) + public static function number($value):bool { return $value == '0' || is_numeric($value); } - public static function integer($value) + public static function integer($value):bool { return $value == '0' || (int) $value == $value; } - public static function lessThan($value, $max) + public static function lessThan($value, $max):bool { $validator = new Rule\LessThan(['max' => $max]); return $validator->validate($value); } - public static function greaterThan($value, $min) + public static function greaterThan($value, $min):bool { $validator = new Rule\GreaterThan(['min' => $min]); return $validator->validate($value); } - public static function between($value, $min, $max) + public static function between($value, $min, $max):bool { $validator = new Rule\Between([ 'min' => $min, @@ -90,52 +90,52 @@ public static function between($value, $min, $max) return $validator->validate($value); } - public static function exactly($value, $otherValue) + public static function exactly($value, $otherValue):bool { return $value == $otherValue; } - public static function not($value, $otherValue) + public static function not($value, $otherValue):bool { return ! self::exactly($value, $otherValue); } - public static function alpha($value) + public static function alpha($value):bool { $validator = new Rule\Alpha(); return $validator->validate($value); } - public static function alphanumeric($value) + public static function alphanumeric($value):bool { $validator = new Rule\AlphaNumeric(); return $validator->validate($value); } - public static function alphanumhyphen($value) + public static function alphanumhyphen($value):bool { $validator = new Rule\AlphaNumHyphen(); return $validator->validate($value); } - public static function minLength($value, $min) + public static function minLength($value, $min):bool { $validator = new Rule\MinLength(['min' => $min]); return $validator->validate($value); } - public static function maxLength($value, $max) + public static function maxLength($value, $max):bool { $validator = new Rule\MaxLength(['max' => $max]); return $validator->validate($value); } - public static function length($value, $min, $max) + public static function length($value, $min, $max):bool { $validator = new Rule\Length([ 'min' => $min, @@ -145,21 +145,21 @@ public static function length($value, $min, $max) return $validator->validate($value); } - public static function setMinSize($value, $min) + public static function setMinSize($value, $min):bool { $validator = new Rule\ArrayMinLength(['min' => $min]); return $validator->validate($value); } - public static function setMaxSize($value, $max) + public static function setMaxSize($value, $max):bool { $validator = new Rule\ArrayMaxLength(['max' => $max]); return $validator->validate($value); } - public static function setSize($value, $min, $max) + public static function setSize($value, $min, $max):bool { $validator = new Rule\ArrayLength([ 'min' => $min, @@ -169,35 +169,35 @@ public static function setSize($value, $min, $max) return $validator->validate($value); } - public static function inList($value, $values) + public static function inList($value, $values):bool { $validator = new Rule\InList(['list' => $values]); return $validator->validate($value); } - public static function notInList($value, $values) + public static function notInList($value, $values):bool { $validator = new Rule\NotInList(['list' => $values]); return $validator->validate($value); } - public static function regex($value, $pattern) + public static function regex($value, $pattern):bool { $validator = new Rule\Regex(['pattern' => $pattern]); return $validator->validate($value); } - public static function notRegex($value, $pattern) + public static function notRegex($value, $pattern):bool { $validator = new Rule\NotRegex(['pattern' => $pattern]); return $validator->validate($value); } - public static function equalTo($value, $otherElementOrValue, $context = null) + public static function equalTo($value, $otherElementOrValue, $context = null):bool { if (func_num_args() == 2) { return $value == $otherElementOrValue; @@ -206,7 +206,7 @@ public static function equalTo($value, $otherElementOrValue, $context = null) return $value == Arr::getByPath($context, $otherElementOrValue); } - public static function notEqualTo($value, $otherElementOrValue, $context = null) + public static function notEqualTo($value, $otherElementOrValue, $context = null):bool { if (func_num_args() == 2) { return $value != $otherElementOrValue; @@ -215,35 +215,35 @@ public static function notEqualTo($value, $otherElementOrValue, $context = null) return $value != Arr::getByPath($context, $otherElementOrValue); } - public static function date($value, $format = 'Y-m-d') + public static function date($value, $format = 'Y-m-d'):bool { $validator = new Rule\Date(['format' => $format]); return $validator->validate($value); } - public static function dateTime($value, $format = 'Y-m-d H:i:s') + public static function dateTime($value, $format = 'Y-m-d H:i:s'):bool { $validator = new Rule\DateTime(['format' => $format]); return $validator->validate($value); } - public static function time($value, $format = 'H:i:s') + public static function time($value, $format = 'H:i:s'):bool { $validator = new Rule\Time(['format' => $format]); return $validator->validate($value); } - public static function website($value) + public static function website($value):bool { $validator = new Rule\Website(); return $validator->validate($value); } - public static function url($value) + public static function url($value):bool { $validator = new Rule\Url(); @@ -257,14 +257,14 @@ public static function url($value) * * @return bool */ - public static function ipAddress($value) + public static function ipAddress($value):bool { $validator = new Rule\IpAddress(); return $validator->validate($value); } - public static function email($value) + public static function email($value):bool { $validator = new Rule\Email(); @@ -279,7 +279,7 @@ public static function email($value) * * @return bool */ - public static function fullName($value) + public static function fullName($value):bool { $validator = new Rule\FullName(); @@ -293,7 +293,7 @@ public static function fullName($value) * * @return bool */ - public static function emailDomain($value) + public static function emailDomain($value):bool { $validator = new Rule\EmailDomain(); diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index 1ef9aa3..5480192 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -191,7 +191,7 @@ public function getMessageTemplate(): string * * @return mixed */ - abstract public function validate($value, string $valueIdentifier = null); + abstract public function validate($value, string $valueIdentifier = null):bool; /** * Sets the error message prototype that will be used when returning the error message @@ -216,7 +216,7 @@ public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype) * * @return ErrorMessage */ - public function getErrorMessagePrototype() + public function getErrorMessagePrototype():ErrorMessage { if (! $this->errorMessagePrototype) { $this->errorMessagePrototype = new ErrorMessage(); @@ -249,7 +249,7 @@ public function getMessage() * * @return ErrorMessage */ - public function getPotentialMessage() + public function getPotentialMessage(): ErrorMessage { $message = clone $this->getErrorMessagePrototype(); $message->setTemplate($this->getMessageTemplate()); diff --git a/src/Rule/Alpha.php b/src/Rule/Alpha.php index 4c3652a..2115b82 100755 --- a/src/Rule/Alpha.php +++ b/src/Rule/Alpha.php @@ -7,7 +7,7 @@ class Alpha extends AbstractRule const MESSAGE = 'This input can contain only letters'; const LABELED_MESSAGE = '{label} can contain only letters'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = (bool) ctype_alpha((string) str_replace(' ', '', $value)); diff --git a/src/Rule/AlphaNumHyphen.php b/src/Rule/AlphaNumHyphen.php index 81307a9..d07b908 100755 --- a/src/Rule/AlphaNumHyphen.php +++ b/src/Rule/AlphaNumHyphen.php @@ -7,7 +7,7 @@ class AlphaNumHyphen extends AbstractRule const MESSAGE = 'This input must contain only letters, digits, spaces, hyphens and underscores'; const LABELED_MESSAGE = '{label} must contain only letters, digits, spaces, hyphens and underscores'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = (bool) ctype_alnum( diff --git a/src/Rule/AlphaNumeric.php b/src/Rule/AlphaNumeric.php index 7450723..004e9f2 100755 --- a/src/Rule/AlphaNumeric.php +++ b/src/Rule/AlphaNumeric.php @@ -8,7 +8,7 @@ class AlphaNumeric extends AbstractRule const LABELED_MESSAGE = '{label} must contain only letters and digits'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = (bool) ctype_alnum((string) str_replace(' ', '', $value)); diff --git a/src/Rule/ArrayLength.php b/src/Rule/ArrayLength.php index 94a7346..36ae64c 100755 --- a/src/Rule/ArrayLength.php +++ b/src/Rule/ArrayLength.php @@ -17,7 +17,7 @@ class ArrayLength extends AbstractRule 1 => self::OPTION_MAX ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $maxValidator = new ArrayMaxLength(); diff --git a/src/Rule/ArrayMaxLength.php b/src/Rule/ArrayMaxLength.php index 8fa9abf..53cbf50 100755 --- a/src/Rule/ArrayMaxLength.php +++ b/src/Rule/ArrayMaxLength.php @@ -16,7 +16,7 @@ class ArrayMaxLength extends AbstractRule self::OPTION_MAX ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! isset($this->options['max'])) { diff --git a/src/Rule/ArrayMinLength.php b/src/Rule/ArrayMinLength.php index bd1e161..12ac939 100755 --- a/src/Rule/ArrayMinLength.php +++ b/src/Rule/ArrayMinLength.php @@ -15,7 +15,7 @@ class ArrayMinLength extends AbstractRule 0 => self::OPTION_MIN ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! isset($this->options['min'])) { diff --git a/src/Rule/Between.php b/src/Rule/Between.php index 6ae7b8b..d1d2cc2 100755 --- a/src/Rule/Between.php +++ b/src/Rule/Between.php @@ -17,7 +17,7 @@ class Between extends AbstractRule 1 => self::OPTION_MAX ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $minValidator = new LessThan(); diff --git a/src/Rule/Callback.php b/src/Rule/Callback.php index 914df9c..b226f0c 100755 --- a/src/Rule/Callback.php +++ b/src/Rule/Callback.php @@ -39,7 +39,7 @@ public function getUniqueId():string return $uniqueId; } - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! isset($this->options['callback']) || ! is_callable($this->options['callback'])) { diff --git a/src/Rule/Date.php b/src/Rule/Date.php index 2330ddf..8710896 100644 --- a/src/Rule/Date.php +++ b/src/Rule/Date.php @@ -18,7 +18,7 @@ class Date extends AbstractRule 0 => self::OPTION_FORMAT ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = $value == date( diff --git a/src/Rule/Email.php b/src/Rule/Email.php index 6a55e85..136af6e 100755 --- a/src/Rule/Email.php +++ b/src/Rule/Email.php @@ -8,7 +8,7 @@ class Email extends AbstractRule const LABELED_MESSAGE = '{label} must be a valid email address'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = (filter_var((string) $value, FILTER_VALIDATE_EMAIL) !== false); diff --git a/src/Rule/EmailDomain.php b/src/Rule/EmailDomain.php index d75de47..c83df83 100755 --- a/src/Rule/EmailDomain.php +++ b/src/Rule/EmailDomain.php @@ -7,7 +7,7 @@ class EmailDomain extends AbstractRule const MESSAGE = 'This the email address does not belong to a valid domain'; const LABELED_MESSAGE = '{label} does not belong to a valid domain'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $value = (string) $value; $this->value = $value; diff --git a/src/Rule/Equal.php b/src/Rule/Equal.php index 4ad2d3b..80bd942 100644 --- a/src/Rule/Equal.php +++ b/src/Rule/Equal.php @@ -13,7 +13,7 @@ class Equal extends AbstractRule 0 => self::OPTION_VALUE ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (isset($this->options[self::OPTION_VALUE])) { diff --git a/src/Rule/File/Extension.php b/src/Rule/File/Extension.php index 1b9d433..5cb39e0 100644 --- a/src/Rule/File/Extension.php +++ b/src/Rule/File/Extension.php @@ -3,6 +3,7 @@ namespace Sirius\Validation\Rule\File; +use Sirius\Validation\ErrorMessage; use Sirius\Validation\Rule\AbstractRule; class Extension extends AbstractRule @@ -30,7 +31,7 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! file_exists($value)) { @@ -46,7 +47,7 @@ public function validate($value, string $valueIdentifier = null) return $this->success; } - public function getPotentialMessage() + public function getPotentialMessage():ErrorMessage { $message = parent::getPotentialMessage(); $fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]); diff --git a/src/Rule/File/Image.php b/src/Rule/File/Image.php index 7fcf9cd..06ca313 100644 --- a/src/Rule/File/Image.php +++ b/src/Rule/File/Image.php @@ -3,6 +3,7 @@ namespace Sirius\Validation\Rule\File; +use Sirius\Validation\ErrorMessage; use Sirius\Validation\Rule\AbstractRule; class Image extends AbstractRule @@ -40,7 +41,7 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! file_exists($value)) { @@ -58,7 +59,7 @@ public function validate($value, string $valueIdentifier = null) return $this->success; } - public function getPotentialMessage() + public function getPotentialMessage():ErrorMessage { $message = parent::getPotentialMessage(); $imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]); diff --git a/src/Rule/File/ImageHeight.php b/src/Rule/File/ImageHeight.php index 769efc5..14a9f7c 100644 --- a/src/Rule/File/ImageHeight.php +++ b/src/Rule/File/ImageHeight.php @@ -18,7 +18,7 @@ class ImageHeight extends AbstractRule self::OPTION_MIN => 0, ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (!file_exists($value)) { diff --git a/src/Rule/File/ImageRatio.php b/src/Rule/File/ImageRatio.php index f86a07e..4152db1 100644 --- a/src/Rule/File/ImageRatio.php +++ b/src/Rule/File/ImageRatio.php @@ -36,7 +36,7 @@ protected function normalizeRatio($ratio) return 0; } - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $ratio = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]); diff --git a/src/Rule/File/ImageWidth.php b/src/Rule/File/ImageWidth.php index 04586be..178f974 100644 --- a/src/Rule/File/ImageWidth.php +++ b/src/Rule/File/ImageWidth.php @@ -18,7 +18,7 @@ class ImageWidth extends AbstractRule self::OPTION_MIN => 0, ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! file_exists($value)) { diff --git a/src/Rule/File/Size.php b/src/Rule/File/Size.php index aafd22f..b27e9cc 100644 --- a/src/Rule/File/Size.php +++ b/src/Rule/File/Size.php @@ -17,7 +17,7 @@ class Size extends AbstractRule self::OPTION_SIZE => '2M' ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! file_exists($value)) { diff --git a/src/Rule/FullName.php b/src/Rule/FullName.php index 750bcda..d6692bd 100755 --- a/src/Rule/FullName.php +++ b/src/Rule/FullName.php @@ -10,7 +10,7 @@ class FullName extends AbstractRule /** * This is not going to work with Asian names, http://en.wikipedia.org/wiki/Chinese_name. */ - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; diff --git a/src/Rule/GreaterThan.php b/src/Rule/GreaterThan.php index 4d43cac..ac3c31a 100755 --- a/src/Rule/GreaterThan.php +++ b/src/Rule/GreaterThan.php @@ -19,7 +19,7 @@ class GreaterThan extends AbstractRule 1 => self::OPTION_INCLUSIVE ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! isset($this->options['min'])) { diff --git a/src/Rule/InList.php b/src/Rule/InList.php index ec6688a..f991c5b 100755 --- a/src/Rule/InList.php +++ b/src/Rule/InList.php @@ -14,7 +14,7 @@ class InList extends AbstractRule 0 => self::OPTION_LIST ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! isset($this->options['list'])) { diff --git a/src/Rule/Integer.php b/src/Rule/Integer.php index cb6a1db..f92684a 100644 --- a/src/Rule/Integer.php +++ b/src/Rule/Integer.php @@ -7,7 +7,7 @@ class Integer extends AbstractRule const MESSAGE = 'This input must be an integer number'; const LABELED_MESSAGE = '{label} must be an integer number'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = (bool) filter_var($value, FILTER_VALIDATE_INT) || (string) $value === '0'; diff --git a/src/Rule/IpAddress.php b/src/Rule/IpAddress.php index 64ea922..99da596 100755 --- a/src/Rule/IpAddress.php +++ b/src/Rule/IpAddress.php @@ -7,7 +7,7 @@ class IpAddress extends AbstractRule const MESSAGE = 'This input is not a valid IP address'; const LABELED_MESSAGE = '{label} is not a valid IP address'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; // Do not allow private and reserved range IPs diff --git a/src/Rule/Length.php b/src/Rule/Length.php index 68cef6f..98fcdf8 100755 --- a/src/Rule/Length.php +++ b/src/Rule/Length.php @@ -19,7 +19,7 @@ class Length extends AbstractRule 2 => self::OPTION_ENCODING ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $maxValidator = new MinLength(); diff --git a/src/Rule/LessThan.php b/src/Rule/LessThan.php index e67fc91..2a64dda 100755 --- a/src/Rule/LessThan.php +++ b/src/Rule/LessThan.php @@ -19,7 +19,7 @@ class LessThan extends AbstractRule 1 => self::OPTION_INCLUSIVE ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! isset($this->options['max'])) { diff --git a/src/Rule/Match.php b/src/Rule/Match.php index 4c4f36a..2b4a189 100644 --- a/src/Rule/Match.php +++ b/src/Rule/Match.php @@ -13,7 +13,7 @@ class Match extends AbstractRule 0 => self::OPTION_ITEM ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (isset($this->options[self::OPTION_ITEM])) { diff --git a/src/Rule/MaxLength.php b/src/Rule/MaxLength.php index 2b44278..7614a51 100755 --- a/src/Rule/MaxLength.php +++ b/src/Rule/MaxLength.php @@ -17,7 +17,7 @@ class MaxLength extends AbstractStringRule 1 => self::OPTION_ENCODING ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! isset($this->options['max'])) { diff --git a/src/Rule/MinLength.php b/src/Rule/MinLength.php index e98433c..017c754 100755 --- a/src/Rule/MinLength.php +++ b/src/Rule/MinLength.php @@ -17,7 +17,7 @@ class MinLength extends AbstractStringRule 1 => self::OPTION_ENCODING ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! isset($this->options['min'])) { diff --git a/src/Rule/NotEqual.php b/src/Rule/NotEqual.php index 720b90c..936f814 100644 --- a/src/Rule/NotEqual.php +++ b/src/Rule/NotEqual.php @@ -7,7 +7,7 @@ class NotEqual extends Equal const MESSAGE = 'This input is equal to {value}'; const LABELED_MESSAGE = '{label} is equal to {value}'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { parent::validate($value, $valueIdentifier); $this->success = ! $this->success; diff --git a/src/Rule/NotInList.php b/src/Rule/NotInList.php index ac10d5c..7fd3a29 100755 --- a/src/Rule/NotInList.php +++ b/src/Rule/NotInList.php @@ -13,7 +13,7 @@ class NotInList extends InList 0 => self::OPTION_LIST ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! isset($this->options['list'])) { diff --git a/src/Rule/NotMatch.php b/src/Rule/NotMatch.php index 7e2c65a..0e09ef8 100644 --- a/src/Rule/NotMatch.php +++ b/src/Rule/NotMatch.php @@ -7,7 +7,7 @@ class NotMatch extends Match const MESSAGE = 'This input does match {item}'; const LABELED_MESSAGE = '{label} does match {item}'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { parent::validate($value, $valueIdentifier); $this->success = ! $this->success; diff --git a/src/Rule/NotRegex.php b/src/Rule/NotRegex.php index 2e76192..d84ec53 100755 --- a/src/Rule/NotRegex.php +++ b/src/Rule/NotRegex.php @@ -7,7 +7,7 @@ class NotRegex extends Regex const MESSAGE = 'This input should not match the regular expression {pattern}'; const LABELED_MESSAGE = '{label} Tshould not match the regular expression {pattern}'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { parent::validate($value, $valueIdentifier); $this->success = ! $this->success; diff --git a/src/Rule/Number.php b/src/Rule/Number.php index c25ac1e..04da72a 100644 --- a/src/Rule/Number.php +++ b/src/Rule/Number.php @@ -7,7 +7,7 @@ class Number extends AbstractRule const MESSAGE = 'This input must be a number'; const LABELED_MESSAGE = '{label} must be a number'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = (bool) filter_var($value, FILTER_VALIDATE_FLOAT) || (string) $value === '0'; diff --git a/src/Rule/Regex.php b/src/Rule/Regex.php index ec8e6ad..5f71c55 100755 --- a/src/Rule/Regex.php +++ b/src/Rule/Regex.php @@ -13,7 +13,7 @@ class Regex extends AbstractRule 0 => self::OPTION_PATTERN ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (isset($this->options['pattern'])) { diff --git a/src/Rule/Required.php b/src/Rule/Required.php index 80da45d..4124862 100755 --- a/src/Rule/Required.php +++ b/src/Rule/Required.php @@ -7,7 +7,7 @@ class Required extends AbstractRule const MESSAGE = 'This field is required'; const LABELED_MESSAGE = '{label} is required'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = ($value !== null && $value !== ''); diff --git a/src/Rule/RequiredWhen.php b/src/Rule/RequiredWhen.php index 9cc6919..1d01be6 100644 --- a/src/Rule/RequiredWhen.php +++ b/src/Rule/RequiredWhen.php @@ -43,7 +43,7 @@ public function getItemRule() return $rule; } - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; diff --git a/src/Rule/RequiredWith.php b/src/Rule/RequiredWith.php index 54ca5ef..2b2d614 100644 --- a/src/Rule/RequiredWith.php +++ b/src/Rule/RequiredWith.php @@ -13,7 +13,7 @@ class RequiredWith extends Required 0 => self::OPTION_ITEM ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; diff --git a/src/Rule/RequiredWithout.php b/src/Rule/RequiredWithout.php index 1b35ff0..78c5f8d 100644 --- a/src/Rule/RequiredWithout.php +++ b/src/Rule/RequiredWithout.php @@ -13,7 +13,7 @@ class RequiredWithout extends Required 0 => self::OPTION_ITEM ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; diff --git a/src/Rule/Upload/Extension.php b/src/Rule/Upload/Extension.php index 428e0fc..49f2be3 100644 --- a/src/Rule/Upload/Extension.php +++ b/src/Rule/Upload/Extension.php @@ -3,6 +3,7 @@ namespace Sirius\Validation\Rule\Upload; +use Sirius\Validation\ErrorMessage; use Sirius\Validation\Rule\AbstractRule; class Extension extends AbstractRule @@ -30,7 +31,7 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { @@ -48,7 +49,7 @@ public function validate($value, string $valueIdentifier = null) return $this->success; } - public function getPotentialMessage() + public function getPotentialMessage():ErrorMessage { $message = parent::getPotentialMessage(); $fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]); diff --git a/src/Rule/Upload/Image.php b/src/Rule/Upload/Image.php index a2efe1d..2be4999 100644 --- a/src/Rule/Upload/Image.php +++ b/src/Rule/Upload/Image.php @@ -3,6 +3,7 @@ namespace Sirius\Validation\Rule\Upload; +use Sirius\Validation\ErrorMessage; use Sirius\Validation\Rule\AbstractRule; class Image extends AbstractRule @@ -40,7 +41,7 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { @@ -60,7 +61,7 @@ public function validate($value, string $valueIdentifier = null) return $this->success; } - public function getPotentialMessage() + public function getPotentialMessage():ErrorMessage { $message = parent::getPotentialMessage(); $imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]); diff --git a/src/Rule/Upload/ImageHeight.php b/src/Rule/Upload/ImageHeight.php index 1a26d94..7d4b284 100644 --- a/src/Rule/Upload/ImageHeight.php +++ b/src/Rule/Upload/ImageHeight.php @@ -18,7 +18,7 @@ class ImageHeight extends AbstractRule self::OPTION_MIN => 0, ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { diff --git a/src/Rule/Upload/ImageRatio.php b/src/Rule/Upload/ImageRatio.php index 630c016..78d3798 100644 --- a/src/Rule/Upload/ImageRatio.php +++ b/src/Rule/Upload/ImageRatio.php @@ -22,7 +22,7 @@ class ImageRatio extends AbstractRule self::OPTION_ERROR_MARGIN => 0, ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $ratio = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]); diff --git a/src/Rule/Upload/ImageWidth.php b/src/Rule/Upload/ImageWidth.php index aedef62..132ea9e 100644 --- a/src/Rule/Upload/ImageWidth.php +++ b/src/Rule/Upload/ImageWidth.php @@ -18,7 +18,7 @@ class ImageWidth extends AbstractRule self::OPTION_MIN => 0, ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { diff --git a/src/Rule/Upload/Required.php b/src/Rule/Upload/Required.php index bc59b53..15d6bb4 100644 --- a/src/Rule/Upload/Required.php +++ b/src/Rule/Upload/Required.php @@ -17,7 +17,7 @@ class Required extends AbstractRule const LABELED_MESSAGE = '{label} is required'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name']) || diff --git a/src/Rule/Upload/Size.php b/src/Rule/Upload/Size.php index 8e081b5..620f3fa 100644 --- a/src/Rule/Upload/Size.php +++ b/src/Rule/Upload/Size.php @@ -17,7 +17,7 @@ class Size extends AbstractRule self::OPTION_SIZE => '2M' ]; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; if (! is_array($value) || ! isset($value['tmp_name'])) { diff --git a/src/Rule/Url.php b/src/Rule/Url.php index e416bbd..0f6dbe4 100755 --- a/src/Rule/Url.php +++ b/src/Rule/Url.php @@ -7,7 +7,7 @@ class Url extends AbstractRule const MESSAGE = 'This input is not a valid URL'; const LABELED_MESSAGE = '{label} is not a valid URL'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = (bool) filter_var($value, FILTER_VALIDATE_URL); diff --git a/src/Rule/Website.php b/src/Rule/Website.php index 0a42468..530364c 100755 --- a/src/Rule/Website.php +++ b/src/Rule/Website.php @@ -9,7 +9,7 @@ class Website extends AbstractRule const MESSAGE = 'This input must be a valid website address'; const LABELED_MESSAGE = '{label} must be a valid website address'; - public function validate($value, string $valueIdentifier = null) + public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = (substr($value, 0, 2) == '//') diff --git a/src/RuleCollection.php b/src/RuleCollection.php index 93fc75e..6e65618 100644 --- a/src/RuleCollection.php +++ b/src/RuleCollection.php @@ -29,7 +29,7 @@ public function attach($rule, $data = null) public function getHash($rule) { - /* @var $rule Rule\AbstractValidator */ + /* @var $rule Rule\AbstractRule */ return $rule->getUniqueId(); } } diff --git a/src/RuleFactory.php b/src/RuleFactory.php index daedc0d..455fcc3 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -3,6 +3,7 @@ namespace Sirius\Validation; +use Sirius\Validation\Rule\AbstractRule; use Sirius\Validation\Rule\Callback as CallbackRule; class RuleFactory @@ -106,7 +107,7 @@ protected function registerDefaultRules() * @param string $name * @param string $class * - * @return \Sirius\Validation\RuleFactory + * @return $this */ public function register($name, $class, $errorMessage = '', $labeledErrorMessage = '') { @@ -136,9 +137,9 @@ public function register($name, $class, $errorMessage = '', $labeledErrorMessage * label of the form input field or model attribute * * @throws \InvalidArgumentException - * @return \Sirius\Validation\Rule\AbstractValidator + * @return AbstractRule */ - public function createRule($name, $options = null, $messageTemplate = null, $label = null) + public function createRule($name, $options = null, $messageTemplate = null, $label = null):AbstractRule { $validator = $this->construcRuleByNameAndOptions($name, $options); diff --git a/src/Validator.php b/src/Validator.php index d9523f2..f0d1430 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Sirius\Validation; +use Sirius\Validation\DataWrapper\WrapperInterface; use Sirius\Validation\ValidatorInterface; class Validator implements ValidatorInterface @@ -114,7 +115,7 @@ class Validator implements ValidatorInterface protected $messages = []; /** - * @var \Sirius\Validation\RuleFactory + * @var RuleFactory */ protected $ruleFactory; @@ -126,7 +127,7 @@ class Validator implements ValidatorInterface /** * The object that will contain the data * - * @var \Sirius\Validation\DataWrapper\WrapperInterface + * @var WrapperInterface */ protected $dataWrapper; @@ -145,9 +146,9 @@ public function __construct(RuleFactory $ruleFactory = null, ErrorMessage $error /** * Retrieve the rule factory * - * @return \Sirius\Validation\RuleFactory + * @return RuleFactory */ - public function getRuleFactory() + public function getRuleFactory():RuleFactory { return $this->ruleFactory; } @@ -157,9 +158,9 @@ public function getRuleFactory() * * @throws \InvalidArgumentException * - * @return \Sirius\Validation\Rule\AbstractValidator + * @return $this */ - public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype) + public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype):Validator { $this->errorMessagePrototype = $errorMessagePrototype; @@ -171,7 +172,7 @@ public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype) * * @return ErrorMessage */ - public function getErroMessagePrototype() + public function getErroMessagePrototype():ErrorMessage { return $this->errorMessagePrototype; } @@ -204,9 +205,9 @@ public function getErroMessagePrototype() * * @throws \InvalidArgumentException * - * @return Validator + * @return $this */ - public function add($selector, $name = null, $options = null, $messageTemplate = null, $label = null) + public function add($selector, $name = null, $options = null, $messageTemplate = null, $label = null):Validator { // the $selector is an associative array with $selector => $rules if (func_num_args() == 1) { @@ -231,9 +232,9 @@ public function add($selector, $name = null, $options = null, $messageTemplate = /** * @param array $selectorRulesCollection * - * @return Validator + * @return $this */ - public function addMultiple($selectorRulesCollection) + public function addMultiple($selectorRulesCollection):Validator { foreach ($selectorRulesCollection as $selector => $rules) { // a single rule was passed for the $valueSelector @@ -268,7 +269,7 @@ public function addMultiple($selectorRulesCollection) * * @return self */ - public function remove($selector, $name = true, $options = null) + public function remove($selector, $name = true, $options = null):Validator { if (!array_key_exists($selector, $this->rules)) { return $this; @@ -286,9 +287,9 @@ public function remove($selector, $name = true, $options = null) * * @param mixed $data * - * @return \Sirius\Validation\DataWrapper\WrapperInterface + * @return WrapperInterface */ - public function getDataWrapper($data = null) + public function getDataWrapper($data = null):WrapperInterface { // if $data is set reconstruct the data wrapper if (!$this->dataWrapper || $data) { @@ -298,7 +299,7 @@ public function getDataWrapper($data = null) return $this->dataWrapper; } - public function setData($data) + public function setData($data):Validator { $this->getDataWrapper($data); $this->wasValidated = false; @@ -316,7 +317,7 @@ public function setData($data) * * @return boolean */ - public function validate($data = null) + public function validate($data = null):bool { if ($data !== null) { $this->setData($data); @@ -347,7 +348,7 @@ public function validate($data = null) * * @return self */ - public function addMessage($item, $message = null) + public function addMessage($item, $message = null):Validator { if ($message === null || $message === '') { return $this; @@ -367,7 +368,7 @@ public function addMessage($item, $message = null) * * @return self */ - public function clearMessages($item = null) + public function clearMessages($item = null):Validator { if (is_string($item)) { if (array_key_exists($item, $this->messages)) { @@ -386,7 +387,7 @@ public function clearMessages($item = null) * * @return array */ - public function getMessages($item = null) + public function getMessages($item = null):array { if (is_string($item)) { return array_key_exists($item, $this->messages) ? $this->messages[$item] : []; @@ -395,7 +396,7 @@ public function getMessages($item = null) return $this->messages; } - public function getRules() + public function getRules():array { return $this->rules; } diff --git a/src/ValueValidator.php b/src/ValueValidator.php index 73df074..e264d07 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -63,7 +63,7 @@ public function __construct( $this->rules = new RuleCollection; } - public function setLabel($label = null) + public function setLabel($label = null):ValueValidator { $this->label = $label; @@ -99,7 +99,7 @@ public function setLabel($label = null) * * @return ValueValidator */ - public function add($name, $options = null, $messageTemplate = null, $label = null) + public function add($name, $options = null, $messageTemplate = null, $label = null):ValueValidator { if (is_array($name) && !is_callable($name)) { return $this->addMultiple($name); @@ -130,7 +130,7 @@ public function add($name, $options = null, $messageTemplate = null, $label = nu * * @return ValueValidator */ - public function addMultiple($rules) + public function addMultiple($rules):ValueValidator { foreach ($rules as $singleRule) { // make sure the rule is an array (the parameters of subsequent calls); @@ -146,7 +146,7 @@ public function addMultiple($rules) * * @return ValueValidator */ - public function addRule(AbstractRule $validationRule) + public function addRule(AbstractRule $validationRule):ValueValidator { $validationRule->setErrorMessagePrototype($this->errorMessagePrototype); $this->rules->attach($validationRule); @@ -166,7 +166,7 @@ public function addRule(AbstractRule $validationRule) * @internal param string $selector data selector * @return self */ - public function remove($name = true, $options = null) + public function remove($name = true, $options = null):ValueValidator { if ($name === true) { $this->rules = new RuleCollection(); @@ -197,7 +197,7 @@ public function remove($name = true, $options = null) * * @return array */ - protected function parseRule($ruleAsString) + protected function parseRule($ruleAsString):array { $ruleAsString = trim($ruleAsString); $options = []; @@ -230,7 +230,7 @@ protected function parseRule($ruleAsString) } - public function validate($value, string $valueIdentifier = null, DataWrapper\WrapperInterface $context = null) + public function validate($value, string $valueIdentifier = null, DataWrapper\WrapperInterface $context = null):bool { $this->messages = []; $isRequired = false; @@ -268,7 +268,7 @@ public function validate($value, string $valueIdentifier = null, DataWrapper\Wra return count($this->messages) === 0; } - private function validateRule($rule, $value, $valueIdentifier, $context) + private function validateRule($rule, $value, $valueIdentifier, $context):bool { $rule->setContext($context); if (!$rule->validate($value, $valueIdentifier)) { @@ -278,24 +278,24 @@ private function validateRule($rule, $value, $valueIdentifier, $context) return true; } - public function getMessages() + public function getMessages():array { return $this->messages; } - public function addMessage($message) + public function addMessage($message):ValueValidator { array_push($this->messages, $message); return $this; } - public function getRules() + public function getRules():RuleCollection { return $this->rules; } - protected function isEmpty($value) + protected function isEmpty($value):bool { return in_array($value, [null, ''], true); } diff --git a/tests/src/Rule/AbstractValidatorTest.php b/tests/src/Rule/AbstractValidatorTest.php index e24f934..1ce8368 100755 --- a/tests/src/Rule/AbstractValidatorTest.php +++ b/tests/src/Rule/AbstractValidatorTest.php @@ -5,7 +5,7 @@ class FakeRule extends \Sirius\Validation\Rule\AbstractRule { - function validate($value, $valueIdentifier = null) + function validate($value, string $valueIdentifier = null):bool { $this->value = $value; $this->success = (bool) $value && isset($this->context) && $this->context->getItemValue('key'); diff --git a/tests/src/RuleFactoryTest.php b/tests/src/RuleFactoryTest.php index 845948f..f6e54e9 100644 --- a/tests/src/RuleFactoryTest.php +++ b/tests/src/RuleFactoryTest.php @@ -7,7 +7,7 @@ class TestingCustomRule extends AbstractRule { - function validate($value, $valueIdentifier = null) + function validate($value, string $valueIdentifier = null):bool { return (bool) ($value % 2); } From 6e16e6b4636abe580aee9d6529a721ee830c9e61 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 8 Jun 2020 09:23:44 +0300 Subject: [PATCH 075/112] Fixed length rule validator (issue #64) --- src/Rule/Length.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Rule/Length.php b/src/Rule/Length.php index 98fcdf8..49ca068 100755 --- a/src/Rule/Length.php +++ b/src/Rule/Length.php @@ -22,11 +22,11 @@ class Length extends AbstractRule public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; - $maxValidator = new MinLength(); + $maxValidator = new MaxLength(); if (isset($this->options['max'])) { $maxValidator->setOption('max', $this->options['max']); } - $minValidator = new MaxLength(); + $minValidator = new MinLength(); if (isset($this->options['min'])) { $minValidator->setOption('min', $this->options['min']); } From 644620b201227c37a697570c7808743e062bae38 Mon Sep 17 00:00:00 2001 From: Michael Tremblay Date: Mon, 13 Jul 2020 10:35:45 -0400 Subject: [PATCH 076/112] Implemented same check as in Helper.php --- src/Rule/RequiredWhen.php | 2 +- src/Rule/RequiredWith.php | 2 +- src/Rule/RequiredWithout.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Rule/RequiredWhen.php b/src/Rule/RequiredWhen.php index 1d01be6..d6aa0f9 100644 --- a/src/Rule/RequiredWhen.php +++ b/src/Rule/RequiredWhen.php @@ -55,7 +55,7 @@ public function validate($value, string $valueIdentifier = null):bool $itemRule = $this->getItemRule(); if ($itemRule->validate($relatedItemValue, $relatedItemPath)) { - $this->success = ($value !== null && trim($value) !== ''); + $this->success = ($value !== null && (!is_string($value) || trim($value) !== '')); } else { $this->success = true; } diff --git a/src/Rule/RequiredWith.php b/src/Rule/RequiredWith.php index 2b2d614..36eb815 100644 --- a/src/Rule/RequiredWith.php +++ b/src/Rule/RequiredWith.php @@ -21,7 +21,7 @@ public function validate($value, string $valueIdentifier = null):bool $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; if (isset($this->options[self::OPTION_ITEM]) && $relatedItemValue !== null) { - $this->success = ($value !== null && trim((string)$value) !== ''); + $this->success = ($value !== null && (!is_string($value) || trim($value) !== '')); } else { $this->success = true; } diff --git a/src/Rule/RequiredWithout.php b/src/Rule/RequiredWithout.php index 78c5f8d..8628a5c 100644 --- a/src/Rule/RequiredWithout.php +++ b/src/Rule/RequiredWithout.php @@ -21,7 +21,7 @@ public function validate($value, string $valueIdentifier = null):bool $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; if (isset($this->options[self::OPTION_ITEM]) && $relatedItemValue === null) { - $this->success = ($value !== null && trim($value) !== ''); + $this->success = ($value !== null && (!is_string($value) || trim($value) !== '')); } else { $this->success = true; } From bca3b223933823e3b1a24dfb8d444cb540595634 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 20 Nov 2020 18:05:17 +0200 Subject: [PATCH 077/112] Created CI workflow --- .github/workflows/ci.yml | 50 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..946c3b5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,50 @@ +name: PHP Composer + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + strategy: + matrix: + php: ['7.2', '7.3', '7.4', '8.0'] + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Setup PHP with fail-fast + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: xdebug + env: + fail-fast: true + - name: Validate composer.json and composer.lock + run: composer validate + + - name: Cache Composer packages + id: composer-cache + uses: actions/cache@v2 + with: + path: vendor + key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-php- + + - name: Install dependencies + if: steps.composer-cache.outputs.cache-hit != 'true' + run: composer install --prefer-dist --no-progress --no-suggest + + - name: Run test suite + run: | + wget -c https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar + composer run-script cs + mkdir -p build/logs + vendor/bin/phpunit -c tests/phpunit.xml + + - name: Upload to Scrutinizer-CI + run: wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml From 9f8274f55329097a05500aa6cf598b884c980608 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 20 Nov 2020 18:10:17 +0200 Subject: [PATCH 078/112] Update ci.yml --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 946c3b5..55345ab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ jobs: build: strategy: matrix: - php: ['7.2', '7.3', '7.4', '8.0'] + php: ['7.2'] runs-on: ubuntu-latest From 55670e7b0d92f5574c59df2d2e6f64e0b5d481d4 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 20 Nov 2020 18:12:25 +0200 Subject: [PATCH 079/112] Added php 7.3 and 7.4 --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 55345ab..1cfcf25 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ jobs: build: strategy: matrix: - php: ['7.2'] + php: ['7.2', '7.3', '7.4'] runs-on: ubuntu-latest From b81fb14c5ff8f8ffa6887c05f60f07a7e78bd731 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 20 Nov 2020 18:20:18 +0200 Subject: [PATCH 080/112] Update ci.yml --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1cfcf25..b7f91c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -name: PHP Composer +name: CI on: push: From e0316ba469c6bdadffe53228f3e0570974a82fd5 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 20 Nov 2020 18:24:27 +0200 Subject: [PATCH 081/112] Update readme.md --- readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/readme.md b/readme.md index 4b90a18..4e1cc31 100755 --- a/readme.md +++ b/readme.md @@ -3,9 +3,9 @@ [![Source Code](http://img.shields.io/badge/source-siriusphp/validation-blue.svg?style=flat-square)](https://github.com/siriusphp/validation) [![Latest Version](https://img.shields.io/packagist/v/siriusphp/validation.svg?style=flat-square)](https://github.com/siriusphp/validation/releases) [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/siriusphp/validation/blob/master/LICENSE) -[![Build Status](https://img.shields.io/travis/siriusphp/validation/master.svg?style=flat-square)](https://travis-ci.org/siriusphp/validation) -[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/siriusphp/validation.svg?style=flat-square)](https://scrutinizer-ci.com/g/siriusphp/validation/code-structure) -[![Quality Score](https://img.shields.io/scrutinizer/g/siriusphp/validation.svg?style=flat-square)](https://scrutinizer-ci.com/g/siriusphp/validation) +[![Build Status](https://github.com/siriusphp/validation/workflows/CI/badge.svg?style=flat-square)](https://github.com/siriusphp/validation/actions) +[![Coverage Status](https://scrutinizer-ci.com/g/siriusphp/validation/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/siriusphp/validation/code-structure) +[![Quality Score](https://scrutinizer-ci.com/g/siriusphp/validation/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/siriusphp/validation) [![Total Downloads](https://img.shields.io/packagist/dt/siriusphp/validation.svg?style=flat-square)](https://packagist.org/packages/siriusphp/validation) Sirius Validation is a library for data validation. It offers: From 2eda98a09e96950b4cb159edec00e59b1e690646 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 20 Nov 2020 18:33:49 +0200 Subject: [PATCH 082/112] Update readme.md --- readme.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/readme.md b/readme.md index 4e1cc31..88c66e9 100755 --- a/readme.md +++ b/readme.md @@ -1,12 +1,12 @@ # Sirius Validation -[![Source Code](http://img.shields.io/badge/source-siriusphp/validation-blue.svg?style=flat-square)](https://github.com/siriusphp/validation) -[![Latest Version](https://img.shields.io/packagist/v/siriusphp/validation.svg?style=flat-square)](https://github.com/siriusphp/validation/releases) -[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/siriusphp/validation/blob/master/LICENSE) -[![Build Status](https://github.com/siriusphp/validation/workflows/CI/badge.svg?style=flat-square)](https://github.com/siriusphp/validation/actions) +[![Source Code](http://img.shields.io/badge/source-siriusphp/validation-blue.svg)](https://github.com/siriusphp/validation) +[![Latest Version](https://img.shields.io/packagist/v/siriusphp/validation.svg)](https://github.com/siriusphp/validation/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://github.com/siriusphp/validation/blob/master/LICENSE) +[![Build Status](https://github.com/siriusphp/validation/workflows/CI/badge.svg)](https://github.com/siriusphp/validation/actions) [![Coverage Status](https://scrutinizer-ci.com/g/siriusphp/validation/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/siriusphp/validation/code-structure) [![Quality Score](https://scrutinizer-ci.com/g/siriusphp/validation/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/siriusphp/validation) -[![Total Downloads](https://img.shields.io/packagist/dt/siriusphp/validation.svg?style=flat-square)](https://packagist.org/packages/siriusphp/validation) +[![Total Downloads](https://img.shields.io/packagist/dt/siriusphp/validation.svg)](https://packagist.org/packages/siriusphp/validation) Sirius Validation is a library for data validation. It offers: From 7a5fdf3d07a9ccc31ffc1dbf58fac1471f16544c Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 20 Nov 2020 18:36:12 +0200 Subject: [PATCH 083/112] Delete .travis.yml --- .travis.yml | 25 ------------------------- 1 file changed, 25 deletions(-) delete mode 100755 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100755 index 9753d3a..0000000 --- a/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -language: php - -php: - - 7.1 - - 7.2 - - 7.3 - - 7.4 - -matrix: - allow_failures: - - php: 7.1 - -before_script: - - wget -c https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar - - composer self-update - - composer install --prefer-source - -script: - - mkdir -p build/logs - - composer run-script cs - - vendor/bin/phpunit -c tests/phpunit.xml - -after_script: - - wget https://scrutinizer-ci.com/ocular.phar - - php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml From 3b34b0bc2be92eb504c15cbb931a66024f1287ad Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Fri, 20 Nov 2020 18:58:32 +0200 Subject: [PATCH 084/112] Add PHP 8 --- .github/workflows/ci.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b7f91c0..b3c53aa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,6 +11,10 @@ jobs: strategy: matrix: php: ['7.2', '7.3', '7.4'] + include: + - php: '8.0' + composer-flags: '--ignore-platform-req=php' + phpunit-flags: '--no-coverage' runs-on: ubuntu-latest From 1f6e23e88ed5bb9e343c7b7be3395a2580f86aed Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 23 Nov 2020 17:23:25 +0200 Subject: [PATCH 085/112] Renamed the Match rule class to Matching so it works with PHP8 (match is a reserved word) --- src/Rule/{Match.php => Matching.php} | 2 +- src/Rule/NotMatch.php | 2 +- src/RuleFactory.php | 3 ++- tests/src/Rule/MatchTest.php | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) rename src/Rule/{Match.php => Matching.php} (94%) diff --git a/src/Rule/Match.php b/src/Rule/Matching.php similarity index 94% rename from src/Rule/Match.php rename to src/Rule/Matching.php index 2b4a189..a70f0c0 100644 --- a/src/Rule/Match.php +++ b/src/Rule/Matching.php @@ -2,7 +2,7 @@ declare(strict_types=1); namespace Sirius\Validation\Rule; -class Match extends AbstractRule +class Matching extends AbstractRule { const OPTION_ITEM = 'item'; diff --git a/src/Rule/NotMatch.php b/src/Rule/NotMatch.php index 0e09ef8..94cd199 100644 --- a/src/Rule/NotMatch.php +++ b/src/Rule/NotMatch.php @@ -2,7 +2,7 @@ declare(strict_types=1); namespace Sirius\Validation\Rule; -class NotMatch extends Match +class NotMatch extends Matching { const MESSAGE = 'This input does match {item}'; const LABELED_MESSAGE = '{label} does match {item}'; diff --git a/src/RuleFactory.php b/src/RuleFactory.php index 455fcc3..1bd53a1 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -5,6 +5,7 @@ use Sirius\Validation\Rule\AbstractRule; use Sirius\Validation\Rule\Callback as CallbackRule; +use Sirius\Validation\Rule\Matching; class RuleFactory { @@ -61,7 +62,6 @@ protected function registerDefaultRules() 'IpAddress', 'Length', 'LessThan', - 'Match', 'MaxLength', 'MinLength', 'NotEqual', @@ -98,6 +98,7 @@ protected function registerDefaultRules() $labeledErrorMessage = constant($fullClassName . '::LABELED_MESSAGE'); $this->register($name, $fullClassName, $errorMessage, $labeledErrorMessage); } + $this->register('match', Matching::class, Matching::MESSAGE, Matching::LABELED_MESSAGE); } diff --git a/tests/src/Rule/MatchTest.php b/tests/src/Rule/MatchTest.php index 25f0c59..07dde76 100644 --- a/tests/src/Rule/MatchTest.php +++ b/tests/src/Rule/MatchTest.php @@ -3,7 +3,7 @@ namespace Sirius\Validation\Rule; use Sirius\Validation\DataWrapper\ArrayWrapper; -use Sirius\Validation\Rule\Match as Rule; +use Sirius\Validation\Rule\Matching as Rule; class MatchTest extends \PHPUnit\Framework\TestCase { From 0585c9946e6380cd9eced56354da58e1742b83a6 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 23 Nov 2020 18:04:14 +0200 Subject: [PATCH 086/112] Another attempt to fix support for PHP8 and added issue templates --- .github/ISSUE_TEMPLATE/Bug.md | 24 +++++++++++++++++++++++ .github/ISSUE_TEMPLATE/Feature_Request.md | 21 ++++++++++++++++++++ .github/ISSUE_TEMPLATE/Question.md | 8 ++++++++ .github/workflows/ci.yml | 7 +++---- 4 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/Bug.md create mode 100644 .github/ISSUE_TEMPLATE/Feature_Request.md create mode 100644 .github/ISSUE_TEMPLATE/Question.md diff --git a/.github/ISSUE_TEMPLATE/Bug.md b/.github/ISSUE_TEMPLATE/Bug.md new file mode 100644 index 0000000..f563f05 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Bug.md @@ -0,0 +1,24 @@ +--- +name: 🐛 Bug +about: Did you encounter a bug? +--- + +### Bug Report + + + +| Q | A +|------------ | ------ +| BC Break | yes/no +| Version | x.y.z + +#### Summary + + + +#### How to reproduce + + diff --git a/.github/ISSUE_TEMPLATE/Feature_Request.md b/.github/ISSUE_TEMPLATE/Feature_Request.md new file mode 100644 index 0000000..de0f669 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Feature_Request.md @@ -0,0 +1,21 @@ +--- +name: 🎉 Feature Request +about: Do you have a new feature in mind? +--- + +### Feature Request + + + +| Q | A +|------------ | ------ +| New Feature | yes/no +| BC Break | yes/no + +#### Scenario / Use-case + + + +#### Summary + + diff --git a/.github/ISSUE_TEMPLATE/Question.md b/.github/ISSUE_TEMPLATE/Question.md new file mode 100644 index 0000000..fa8e763 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Question.md @@ -0,0 +1,8 @@ +--- +name: ❓ Question +about: Are you unsure about something? +--- + +### Question + + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b3c53aa..1a242f2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,7 @@ jobs: phpunit-flags: '--no-coverage' runs-on: ubuntu-latest + continue-on-failure: true steps: - uses: actions/checkout@v2 @@ -45,10 +46,8 @@ jobs: - name: Run test suite run: | - wget -c https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar - composer run-script cs mkdir -p build/logs vendor/bin/phpunit -c tests/phpunit.xml - + - name: Upload to Scrutinizer-CI - run: wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml + run: wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml From 3b2804dc7f20e4f0b805843a3cb643b422aaf790 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 23 Nov 2020 18:05:59 +0200 Subject: [PATCH 087/112] Update ci.yml --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a242f2..9785733 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,6 @@ jobs: phpunit-flags: '--no-coverage' runs-on: ubuntu-latest - continue-on-failure: true steps: - uses: actions/checkout@v2 From 62cd3669fb5936190b04cced41927eabbe22316f Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 23 Nov 2020 18:07:20 +0200 Subject: [PATCH 088/112] Removed support for php8 --- .github/workflows/ci.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9785733..b4076c5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,10 +11,10 @@ jobs: strategy: matrix: php: ['7.2', '7.3', '7.4'] - include: - - php: '8.0' - composer-flags: '--ignore-platform-req=php' - phpunit-flags: '--no-coverage' + #include: + # - php: '8.0' + # composer-flags: '--ignore-platform-req=php' + # phpunit-flags: '--no-coverage' runs-on: ubuntu-latest From 4bf195e422e23c02cb7e7763bbbd574ef793176a Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Tue, 24 Nov 2020 16:27:38 +0200 Subject: [PATCH 089/112] Added workflow for publishing the documentation --- .editorconfig | 3 +++ .github/workflows/docs.yml | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 .github/workflows/docs.yml diff --git a/.editorconfig b/.editorconfig index cd8eb86..c451dda 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,3 +13,6 @@ trim_trailing_whitespace = true [*.md] trim_trailing_whitespace = false + +[*.yml] +indent_size = 2 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..f9e77fd --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,28 @@ +name: Publish docs + +on: + push: + tags: + - 'v*.*.*' +jobs: + docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + + - name: Build docs + run: | + curl -OS https://couscous.io/couscous.phar + php couscous.phar generate --target=build/docs/ ./docs + + - name: FTP Deployer + uses: sand4rt/ftp-deployer@v1.1 + with: + host: ${{ secrets.DOCS_FTP_HOST }} + username: ${{ secrets.DOCS_FTP_USERNAME }} + password: ${{ secrets.DOCS_FTP_PASSWORD }} + remote_folder: validation + # The local folder location + local_folder: docs/.couscous + # Remove existing files inside FTP remote folder + cleanup: false # optional From 212ea03401a991f7306967677b01f3bcbbab982c Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Tue, 24 Nov 2020 16:36:38 +0200 Subject: [PATCH 090/112] Fixed workflow --- .github/workflows/docs.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index f9e77fd..57e39cb 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -11,9 +11,9 @@ jobs: - uses: actions/checkout@v1 - name: Build docs - run: | - curl -OS https://couscous.io/couscous.phar - php couscous.phar generate --target=build/docs/ ./docs + run: | + curl -OS https://couscous.io/couscous.phar + php couscous.phar generate --target=build/docs/ ./docs - name: FTP Deployer uses: sand4rt/ftp-deployer@v1.1 From 7b1a220982fa29f6aba79b37781011b875c3bda1 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Tue, 24 Nov 2020 16:43:21 +0200 Subject: [PATCH 091/112] Updated the publish docs workflow --- .github/workflows/docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 57e39cb..eee1c7e 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -3,7 +3,7 @@ name: Publish docs on: push: tags: - - 'v*.*.*' + - '*.*.*' jobs: docs: runs-on: ubuntu-latest From ac6f5bd185e4e0242b601c372c13b6cf159e430b Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Tue, 24 Nov 2020 16:46:32 +0200 Subject: [PATCH 092/112] Update docs.yml --- .github/workflows/docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index eee1c7e..e6f5f9a 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -19,7 +19,7 @@ jobs: uses: sand4rt/ftp-deployer@v1.1 with: host: ${{ secrets.DOCS_FTP_HOST }} - username: ${{ secrets.DOCS_FTP_USERNAME }} + username: ${{ secrets.DOCS_FTP_USER }} password: ${{ secrets.DOCS_FTP_PASSWORD }} remote_folder: validation # The local folder location From 3b83d737beaa8697f3003be91338ea0a247c6b52 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Tue, 24 Nov 2020 16:50:28 +0200 Subject: [PATCH 093/112] Updated docs workflow --- .github/workflows/docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index e6f5f9a..dfb2eff 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -23,6 +23,6 @@ jobs: password: ${{ secrets.DOCS_FTP_PASSWORD }} remote_folder: validation # The local folder location - local_folder: docs/.couscous + local_folder: build/docs/ # Remove existing files inside FTP remote folder cleanup: false # optional From 1d03185dfbf34a45d7c415b43605a699cfc3af71 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Tue, 24 Nov 2020 16:58:51 +0200 Subject: [PATCH 094/112] Fixed documentation config --- docs/couscous.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/couscous.yml b/docs/couscous.yml index 88eb964..38aa5c7 100644 --- a/docs/couscous.yml +++ b/docs/couscous.yml @@ -12,7 +12,7 @@ exclude: # Base URL of the published website (no "/" at the end!) # You are advised to set and use this variable to write your links in the HTML layouts -baseUrl: http://www.sirius.ro/php/sirius/validation +baseUrl: //www.sirius.ro/php/sirius/validation paypal: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=SGXDKNJCXFPJU gacode: UA-535999-18 From 05a78b89501c3b8d1d270db02d8489b1810c20d2 Mon Sep 17 00:00:00 2001 From: nanawel Date: Sun, 29 Nov 2020 11:18:08 +0100 Subject: [PATCH 095/112] Add support for WEBP images --- src/Rule/File/Image.php | 1 + src/Rule/Upload/Image.php | 1 + 2 files changed, 2 insertions(+) diff --git a/src/Rule/File/Image.php b/src/Rule/File/Image.php index 06ca313..065e624 100644 --- a/src/Rule/File/Image.php +++ b/src/Rule/File/Image.php @@ -26,6 +26,7 @@ class Image extends AbstractRule IMAGETYPE_PSD => 'psd', IMAGETYPE_BMP => 'bmp', IMAGETYPE_ICO => 'ico', + IMAGETYPE_WEBP => 'webp', ]; public function setOption($name, $value) diff --git a/src/Rule/Upload/Image.php b/src/Rule/Upload/Image.php index 2be4999..d9b9319 100644 --- a/src/Rule/Upload/Image.php +++ b/src/Rule/Upload/Image.php @@ -26,6 +26,7 @@ class Image extends AbstractRule IMAGETYPE_PSD => 'psd', IMAGETYPE_BMP => 'bmp', IMAGETYPE_ICO => 'ico', + IMAGETYPE_WEBP => 'webp', ]; public function setOption($name, $value) From 97cd3f47c3efecc14ee9e9b5a56ee04c98017a51 Mon Sep 17 00:00:00 2001 From: bokunodev Date: Fri, 8 Jul 2022 18:27:35 +0700 Subject: [PATCH 096/112] fix incompatible error between Sirius\Validation\RuleCollection and SplObjectStorage in php8 modified: src/RuleCollection.php --- src/RuleCollection.php | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/RuleCollection.php b/src/RuleCollection.php index 6e65618..ee8d551 100644 --- a/src/RuleCollection.php +++ b/src/RuleCollection.php @@ -1,10 +1,19 @@ contains($rule)) { @@ -24,12 +33,16 @@ public function attach($rule, $data = null) return; } - return parent::attach($rule); + parent::attach($rule); } + /** + * @param object $rule + */ + #[ReturnTypeWillChange] public function getHash($rule) { - /* @var $rule Rule\AbstractRule */ + /* @var $rule Sirius\Validation\Rule\AbstractRule */ return $rule->getUniqueId(); } } From bcffec5e64d069a96a75fe18938f030047ebe84d Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 21 Sep 2022 22:39:42 +0300 Subject: [PATCH 097/112] Fix IP address validation test --- tests/src/HelperTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/src/HelperTest.php b/tests/src/HelperTest.php index 8bd039d..9caf77c 100755 --- a/tests/src/HelperTest.php +++ b/tests/src/HelperTest.php @@ -587,7 +587,7 @@ function testOfIp() true ), array( - '256.5765.53.21', + '256.576a.53.21', false ), array( From fbe3655183a5e6560f87f57eaef265c51fa46883 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 21 Sep 2022 22:41:04 +0300 Subject: [PATCH 098/112] Update HelperTest.php --- tests/src/HelperTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/src/HelperTest.php b/tests/src/HelperTest.php index 9caf77c..2dd37d2 100755 --- a/tests/src/HelperTest.php +++ b/tests/src/HelperTest.php @@ -597,6 +597,7 @@ function testOfIp() ); foreach ($pool as $sample) { + print_r($sample); $this->assertSame(Helper::ipAddress($sample[0]), $sample[1]); } } From d5cdc9de9caeae0d91479656f7327e0ade6df433 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 21 Sep 2022 22:42:29 +0300 Subject: [PATCH 099/112] Update HelperTest.php --- tests/src/HelperTest.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/src/HelperTest.php b/tests/src/HelperTest.php index 2dd37d2..e29b34a 100755 --- a/tests/src/HelperTest.php +++ b/tests/src/HelperTest.php @@ -597,8 +597,7 @@ function testOfIp() ); foreach ($pool as $sample) { - print_r($sample); - $this->assertSame(Helper::ipAddress($sample[0]), $sample[1]); + $this->assertSame(Helper::ipAddress($sample[0]), $sample[1], $sample[0]); } } From 5581bbd76435d84954ffa49d91e4314dd6faa10e Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 21 Sep 2022 22:47:42 +0300 Subject: [PATCH 100/112] Update IpAddress.php --- src/Rule/IpAddress.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Rule/IpAddress.php b/src/Rule/IpAddress.php index 99da596..e39a7db 100755 --- a/src/Rule/IpAddress.php +++ b/src/Rule/IpAddress.php @@ -13,9 +13,9 @@ public function validate($value, string $valueIdentifier = null):bool // Do not allow private and reserved range IPs $flags = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; if (strpos($value, ':') !== false) { - $this->success = (bool) filter_var($value, FILTER_VALIDATE_IP, $flags | FILTER_FLAG_IPV6); + $this->success = (bool) filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE | FILTER_FLAG_IPV6); } else { - $this->success = (bool) filter_var($value, FILTER_VALIDATE_IP, $flags | FILTER_FLAG_IPV4); + $this->success = (bool) filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE | FILTER_FLAG_IPV4); } return $this->success; From 14dd292b10053d6269126f4cb6e334f78d4686c4 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Wed, 21 Sep 2022 22:51:46 +0300 Subject: [PATCH 101/112] Update HelperTest.php --- tests/src/HelperTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/src/HelperTest.php b/tests/src/HelperTest.php index e29b34a..748ff0f 100755 --- a/tests/src/HelperTest.php +++ b/tests/src/HelperTest.php @@ -591,7 +591,7 @@ function testOfIp() false ), array( - '2001:db8:85a3:8d3:1319:8a2e:370:7348', + '2002:51c4:7c3c:0000:0000:0000:0000:0000', true ) //IPv6 ); From 725c48a8c532b0251e1ba2ff26906fb4ca83fbdc Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 17 Apr 2023 10:17:21 +0300 Subject: [PATCH 102/112] Added php 8 to supported versions --- .github/workflows/ci.yml | 2 +- composer.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b4076c5..81cc778 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ jobs: build: strategy: matrix: - php: ['7.2', '7.3', '7.4'] + php: ['7.4', '8.0', '8.1', '8.2'] #include: # - php: '8.0' # composer-flags: '--ignore-platform-req=php' diff --git a/composer.json b/composer.json index ea9ac8b..06d892e 100755 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ } ], "require": { - "php": ">=7.1" + "php": "^7.2|^8.0" }, "require-dev": { "phpunit/phpunit": "^8.5" From 263e07c7e617c8f0168be5d2437357974ee3820f Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 17 Apr 2023 10:30:28 +0300 Subject: [PATCH 103/112] Fixed PHP 8.* issues --- src/ErrorMessage.php | 2 +- src/Rule/Alpha.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ErrorMessage.php b/src/ErrorMessage.php index dc3386f..1eb241a 100755 --- a/src/ErrorMessage.php +++ b/src/ErrorMessage.php @@ -48,7 +48,7 @@ public function __toString() $result = $this->template; foreach ($this->variables as $k => $v) { if (strpos($result, "{{$k}}") !== false) { - $result = str_replace("{{$k}}", $v, $result); + $result = str_replace("{{$k}}", $v, (string) $result); } } diff --git a/src/Rule/Alpha.php b/src/Rule/Alpha.php index 2115b82..14a214f 100755 --- a/src/Rule/Alpha.php +++ b/src/Rule/Alpha.php @@ -10,7 +10,7 @@ class Alpha extends AbstractRule public function validate($value, string $valueIdentifier = null):bool { $this->value = $value; - $this->success = (bool) ctype_alpha((string) str_replace(' ', '', $value)); + $this->success = (bool) ctype_alpha((string) str_replace(' ', '', (string) $value)); return $this->success; } From a46103cc8714c30114533e92ddd28f1ad63222ea Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 17 Apr 2023 10:36:49 +0300 Subject: [PATCH 104/112] Fixed var typing error with PHP 8.* --- src/ErrorMessage.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ErrorMessage.php b/src/ErrorMessage.php index 1eb241a..bfb1ac2 100755 --- a/src/ErrorMessage.php +++ b/src/ErrorMessage.php @@ -48,7 +48,7 @@ public function __toString() $result = $this->template; foreach ($this->variables as $k => $v) { if (strpos($result, "{{$k}}") !== false) { - $result = str_replace("{{$k}}", $v, (string) $result); + $result = str_replace("{{$k}}", (string) $v, (string) $result); } } From 7fc57e84a92abb17da6100e07dc38ce3442826f8 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 17 Apr 2023 10:53:45 +0300 Subject: [PATCH 105/112] Update ci.yml --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 81cc778..e9f63e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -49,4 +49,5 @@ jobs: vendor/bin/phpunit -c tests/phpunit.xml - name: Upload to Scrutinizer-CI + if: "php-version == 7.4" run: wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml From 840a32e1f6bd62d8cd76ff2cdab238ba24d0ebc7 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 17 Apr 2023 10:54:49 +0300 Subject: [PATCH 106/112] Update ci.yml --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e9f63e3..4c79c29 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -49,5 +49,5 @@ jobs: vendor/bin/phpunit -c tests/phpunit.xml - name: Upload to Scrutinizer-CI - if: "php-version == 7.4" + if: ${{ php-version == "7.4" }} run: wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml From b4f0a7d97ed23e32fb82b3858ea2d9e189d90394 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 17 Apr 2023 11:00:50 +0300 Subject: [PATCH 107/112] Changed the CI config --- .github/workflows/ci.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4c79c29..adc2f0c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,10 +11,10 @@ jobs: strategy: matrix: php: ['7.4', '8.0', '8.1', '8.2'] - #include: - # - php: '8.0' - # composer-flags: '--ignore-platform-req=php' - # phpunit-flags: '--no-coverage' + phpunit-flags: '--no-coverage' + include: + - php: '8.0' + send-to-scrutinizer: 'yes' runs-on: ubuntu-latest @@ -49,5 +49,5 @@ jobs: vendor/bin/phpunit -c tests/phpunit.xml - name: Upload to Scrutinizer-CI - if: ${{ php-version == "7.4" }} + if: matrix.send-to-scrutinizer == "yes" run: wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml From 0510832d6ed7ada04f9785dbc05681f8025c3d6b Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 17 Apr 2023 11:02:49 +0300 Subject: [PATCH 108/112] Updated ci.yml --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index adc2f0c..e06ec36 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,6 @@ jobs: strategy: matrix: php: ['7.4', '8.0', '8.1', '8.2'] - phpunit-flags: '--no-coverage' include: - php: '8.0' send-to-scrutinizer: 'yes' @@ -23,6 +22,8 @@ jobs: - name: Setup PHP with fail-fast uses: shivammathur/setup-php@v2 with: + send-to-scrutinizer: 'no' + phpunit-flags: '--no-coverage' php-version: ${{ matrix.php }} coverage: xdebug env: From 6421579c3974598875c388925e9de5576a29ca05 Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 17 Apr 2023 11:03:59 +0300 Subject: [PATCH 109/112] Updated ci.yml --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e06ec36..934ad00 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,5 +50,5 @@ jobs: vendor/bin/phpunit -c tests/phpunit.xml - name: Upload to Scrutinizer-CI - if: matrix.send-to-scrutinizer == "yes" + if: matrix.send-to-scrutinizer == 'yes' run: wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml From 8bd3f8d7527753fef8c98b8f1f6f79e96b08cf4f Mon Sep 17 00:00:00 2001 From: Adrian Miu Date: Mon, 17 Apr 2023 11:05:13 +0300 Subject: [PATCH 110/112] Removed scrutinizer from CI steps --- .github/workflows/ci.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 934ad00..face5d4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,7 +48,3 @@ jobs: run: | mkdir -p build/logs vendor/bin/phpunit -c tests/phpunit.xml - - - name: Upload to Scrutinizer-CI - if: matrix.send-to-scrutinizer == 'yes' - run: wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml From 4f08d961cd5fda4581500bb750e408b277f51213 Mon Sep 17 00:00:00 2001 From: adrianmiu Date: Fri, 17 Nov 2023 11:46:40 +0200 Subject: [PATCH 111/112] Moved code to PHP 8.1. Added PHPStan level 8. Replaced PHPUnit with Pest --- .github/workflows/ci.yml | 7 +- .gitignore | 2 + composer.json | 84 +- phpstan.neon | 5 + phpunit.xml | 18 + src/DataWrapper/ArrayWrapper.php | 17 +- src/DataWrapper/WrapperInterface.php | 8 +- src/ErrorMessage.php | 35 +- src/Helper.php | 140 ++- src/Rule/AbstractRule.php | 99 +- src/Rule/AbstractStringRule.php | 5 +- src/Rule/Alpha.php | 7 +- src/Rule/AlphaNumHyphen.php | 11 +- src/Rule/AlphaNumeric.php | 7 +- src/Rule/ArrayLength.php | 15 +- src/Rule/ArrayMaxLength.php | 9 +- src/Rule/ArrayMinLength.php | 9 +- src/Rule/Between.php | 15 +- src/Rule/Callback.php | 17 +- src/Rule/Date.php | 31 +- src/Rule/DateTime.php | 3 +- src/Rule/Email.php | 7 +- src/Rule/EmailDomain.php | 12 +- src/Rule/Equal.php | 5 +- src/Rule/File/Extension.php | 20 +- src/Rule/File/Image.php | 35 +- src/Rule/File/ImageHeight.php | 13 +- src/Rule/File/ImageRatio.php | 19 +- src/Rule/File/ImageWidth.php | 15 +- src/Rule/File/Size.php | 11 +- src/Rule/FullName.php | 3 +- src/Rule/GreaterThan.php | 9 +- src/Rule/InList.php | 6 +- src/Rule/Integer.php | 7 +- src/Rule/IpAddress.php | 7 +- src/Rule/Length.php | 15 +- src/Rule/LessThan.php | 9 +- src/Rule/Matching.php | 7 +- src/Rule/MaxLength.php | 9 +- src/Rule/MinLength.php | 9 +- src/Rule/NotEqual.php | 5 +- src/Rule/NotInList.php | 9 +- src/Rule/NotMatch.php | 5 +- src/Rule/NotRegex.php | 5 +- src/Rule/Number.php | 7 +- src/Rule/Regex.php | 7 +- src/Rule/Required.php | 5 +- src/Rule/RequiredWhen.php | 30 +- src/Rule/RequiredWith.php | 9 +- src/Rule/RequiredWithout.php | 9 +- src/Rule/Time.php | 2 +- src/Rule/Upload/Extension.php | 22 +- src/Rule/Upload/Image.php | 35 +- src/Rule/Upload/ImageHeight.php | 17 +- src/Rule/Upload/ImageRatio.php | 17 +- src/Rule/Upload/ImageWidth.php | 17 +- src/Rule/Upload/Required.php | 6 +- src/Rule/Upload/Size.php | 13 +- src/Rule/Url.php | 7 +- src/Rule/Website.php | 13 +- src/RuleCollection.php | 16 +- src/RuleFactory.php | 60 +- src/Util/Arr.php | 70 +- src/Util/RuleHelper.php | 58 +- src/Validator.php | 154 +-- src/ValidatorInterface.php | 28 +- src/ValueValidator.php | 152 ++- tests/Pest.php | 45 + tests/TestCase.php | 10 + tests/src/ComplexTest.php | 88 +- tests/src/ErrorMessageTest.php | 43 +- tests/src/HelperTest.php | 1349 ++++++++++----------- tests/src/Rule/AbstractValidatorTest.php | 118 +- tests/src/Rule/ArrayMaxLengthTest.php | 19 +- tests/src/Rule/ArrayMinLengthTest.php | 19 +- tests/src/Rule/BetweenTest.php | 28 +- tests/src/Rule/CallbackTest.php | 97 +- tests/src/Rule/EmailTest.php | 22 +- tests/src/Rule/EqualTest.php | 33 +- tests/src/Rule/File/ExtensionTest.php | 60 +- tests/src/Rule/File/ImageHeightTest.php | 42 +- tests/src/Rule/File/ImageRatioTest.php | 109 +- tests/src/Rule/File/ImageTest.php | 82 +- tests/src/Rule/File/ImageWidthTest.php | 42 +- tests/src/Rule/File/SizeTest.php | 66 +- tests/src/Rule/GreaterThanTest.php | 82 +- tests/src/Rule/InListTest.php | 19 +- tests/src/Rule/IntegerTest.php | 23 +- tests/src/Rule/LessThanTest.php | 81 +- tests/src/Rule/MatchTest.php | 45 +- tests/src/Rule/NotEqualTest.php | 33 +- tests/src/Rule/NotInListTest.php | 19 +- tests/src/Rule/NotMatchTest.php | 45 +- tests/src/Rule/NumberTest.php | 23 +- tests/src/Rule/RegexTest.php | 21 +- tests/src/Rule/RequiredTest.php | 38 +- tests/src/Rule/RequiredWhenTest.php | 143 +-- tests/src/Rule/RequiredWithTest.php | 89 +- tests/src/Rule/RequiredWithoutTest.php | 90 +- tests/src/Rule/Upload/ExtensionTest.php | 133 +- tests/src/Rule/Upload/ImageHeightTest.php | 117 +- tests/src/Rule/Upload/ImageRatioTest.php | 210 ++-- tests/src/Rule/Upload/ImageTest.php | 145 +-- tests/src/Rule/Upload/ImageWidthTest.php | 117 +- tests/src/Rule/Upload/RequiredTest.php | 133 +- tests/src/Rule/Upload/SizeTest.php | 133 +- tests/src/Rule/UrlTest.php | 28 +- tests/src/Rule/WebsiteTest.php | 19 +- tests/src/RuleCollectionTest.php | 50 +- tests/src/RuleFactoryTest.php | 57 +- tests/src/Util/ArrTest.php | 211 ++-- tests/src/ValidatorTest.php | 506 ++++---- tests/src/ValueValidatorTest.php | 142 +-- tools/php-cs-fixer/composer.json | 5 + 114 files changed, 3027 insertions(+), 3542 deletions(-) create mode 100644 phpstan.neon create mode 100644 phpunit.xml create mode 100644 tests/Pest.php create mode 100644 tests/TestCase.php create mode 100644 tools/php-cs-fixer/composer.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index face5d4..3fa51b5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,9 +10,9 @@ jobs: build: strategy: matrix: - php: ['7.4', '8.0', '8.1', '8.2'] + php: ['8.1', '8.2', '8.3'] include: - - php: '8.0' + - php: '8.1' send-to-scrutinizer: 'yes' runs-on: ubuntu-latest @@ -47,4 +47,5 @@ jobs: - name: Run test suite run: | mkdir -p build/logs - vendor/bin/phpunit -c tests/phpunit.xml + composer run stan + composer run test diff --git a/.gitignore b/.gitignore index 77ee47a..8c1a9f2 100755 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,5 @@ php-cs-fixer.phar phpcbf.phar phpcs.phar phpmd.phar +.phpunit.result.cache +.php_cs.cache diff --git a/composer.json b/composer.json index 06d892e..e902d5d 100755 --- a/composer.json +++ b/composer.json @@ -1,44 +1,48 @@ { - "name": "siriusphp/validation", - "description": "Data validation library. Validate arrays, array objects, domain models etc using a simple API. Easily add your own validators on top of the already dozens built-in validation rules", - "type": "library", - "license": "MIT", - "keywords": [ - "form", - "validation", - "sanitization", - "security", - "modeling" - ], - "authors": [ - { - "name": "Adrian Miu", - "email": "adrian@adrianmiu.ro" - } - ], - "require": { - "php": "^7.2|^8.0" - }, - "require-dev": { - "phpunit/phpunit": "^8.5" - }, - "autoload": { - "psr-4": { - "Sirius\\Validation\\": "src/" - } - }, - "scripts": { - "cs": [ - "php phpcs.phar --standard=PSR2 ./src" + "name": "siriusphp/validation", + "description": "Data validation library. Validate arrays, array objects, domain models etc using a simple API. Easily add your own validators on top of the already dozens built-in validation rules", + "type": "library", + "license": "MIT", + "keywords": [ + "form", + "validation", + "sanitization", + "security", + "modeling" ], - "md": [ - "php phpmd.phar ./src xml phpmd.xml" + "authors": [ + { + "name": "Adrian Miu", + "email": "adrian@adrianmiu.ro" + } ], - "cbf": [ - "php phpcbf.phar ./src --standard=PSR2 -w" - ], - "csfix": [ - "php php-cs-fixer.phar fix ./src --rules=@PSR2" - ] - } + "require": { + "php": ">=8.0" + }, + "autoload": { + "psr-4": { + "Sirius\\Validation\\": "src/" + } + }, + "scripts": { + "stan": [ + "php vendor/bin/phpstan analyse" + ], + "csfix": [ + "tools/php-cs-fixer/vendor/bin/php-cs-fixer fix --standard=PSR-2 src" + ], + "test": [ + "php vendor/bin/pest" + ] + }, + "require-dev": { + "pestphp/pest": "*", + "phpstan/phpstan": "^1.10", + "pestphp/pest-plugin-drift": "^2.5" + }, + "config": { + "allow-plugins": { + "pestphp/pest-plugin": true + } + } } diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..6615f46 --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,5 @@ +parameters: + level: 8 + checkGenericClassInNonGenericObjectType: false + paths: + - src diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..7d0904f --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,18 @@ + + + + + ./tests + + + + + ./app + ./src + + + diff --git a/src/DataWrapper/ArrayWrapper.php b/src/DataWrapper/ArrayWrapper.php index 0992620..42985e6 100644 --- a/src/DataWrapper/ArrayWrapper.php +++ b/src/DataWrapper/ArrayWrapper.php @@ -4,22 +4,21 @@ namespace Sirius\Validation\DataWrapper; use Sirius\Validation\Util\Arr; -use Sirius\Validation\DataWrapper\WrapperInterface; class ArrayWrapper implements WrapperInterface { /** - * @var array + * @var array */ - protected $data = []; + protected array $data = []; /** - * @param array|\ArrayObject|object $data + * @param array|\ArrayObject|object $data * * @throws \InvalidArgumentException */ - public function __construct($data = []) + public function __construct(mixed $data) { if (is_object($data)) { if ($data instanceof \ArrayObject) { @@ -28,19 +27,23 @@ public function __construct($data = []) $data = $data->toArray(); } } - if (! is_array($data)) { + if (!is_array($data)) { throw new \InvalidArgumentException('Data passed to validator is not an array or an ArrayObject'); } $this->data = $data; } - public function getItemValue(string $item) + public function getItemValue(string $item): mixed { return Arr::getByPath($this->data, $item); } + /** + * @return array + */ public function getItemsBySelector(string $selector): array { return Arr::getBySelector($this->data, $selector); } + } diff --git a/src/DataWrapper/WrapperInterface.php b/src/DataWrapper/WrapperInterface.php index 1ea636c..1ccdb93 100644 --- a/src/DataWrapper/WrapperInterface.php +++ b/src/DataWrapper/WrapperInterface.php @@ -9,8 +9,6 @@ interface WrapperInterface /** * Get value from the data container using the path * - * @param string $item - * * @return mixed */ public function getItemValue(string $item); @@ -18,9 +16,7 @@ public function getItemValue(string $item); /** * Get items by selector * - * @param string $selector - * - * @return array + * @return array */ - public function getItemsBySelector(string $selector); + public function getItemsBySelector(string $selector): array; } diff --git a/src/ErrorMessage.php b/src/ErrorMessage.php index bfb1ac2..967cb1d 100755 --- a/src/ErrorMessage.php +++ b/src/ErrorMessage.php @@ -5,31 +5,41 @@ class ErrorMessage { - protected $template = 'Invalid'; - protected $variables = []; + protected string $template = 'Invalid'; - public function __construct($template = '', $variables = []) + /** + * @var array + */ + protected array $variables = []; + + /** + * @param array $variables + */ + public function __construct(string $template = '', array $variables = []) { $this->setTemplate($template) - ->setVariables($variables); + ->setVariables($variables); } - public function setTemplate($template) + public function setTemplate(string $template): self { - $template = trim((string) $template); + $template = trim($template); if ($template) { - $this->template = (string) $template; + $this->template = $template; } return $this; } - public function getTemplate() + public function getTemplate(): string { return $this->template; } - public function setVariables($variables = []) + /** + * @param array $variables + */ + public function setVariables(array $variables = []): self { foreach ($variables as $k => $v) { $this->variables[$k] = $v; @@ -38,7 +48,10 @@ public function setVariables($variables = []) return $this; } - public function getVariables() + /** + * @return array + */ + public function getVariables(): array { return $this->variables; } @@ -48,7 +61,7 @@ public function __toString() $result = $this->template; foreach ($this->variables as $k => $v) { if (strpos($result, "{{$k}}") !== false) { - $result = str_replace("{{$k}}", (string) $v, (string) $result); + $result = str_replace("{{$k}}", (string)$v, (string)$result); } } diff --git a/src/Helper.php b/src/Helper.php index af5ddcb..45eefe1 100755 --- a/src/Helper.php +++ b/src/Helper.php @@ -1,30 +1,39 @@ + */ + protected static array $methods = []; - public static function addMethod($ruleName, $callback):bool + /** + * @param callable|\Closure $callback + */ + public static function addMethod(string $ruleName, mixed $callback): void { if (is_callable($callback)) { self::$methods[$ruleName] = $callback; - - return true; + return; } - return false; + throw new \InvalidArgumentException(sprintf('Validation method "%s" is not callable', $ruleName)); // @phpstan-ignore-line } - public static function methodExists($name):bool + public static function methodExists(string $name): bool { return method_exists(__CLASS__, $name) || array_key_exists($name, self::$methods); } - public static function __callStatic($name, $arguments):bool + /** + * @param array $arguments + */ + public static function __callStatic(string $name, array $arguments = []): mixed { if (array_key_exists($name, self::$methods)) { return call_user_func_array(self::$methods[$name], $arguments); @@ -32,7 +41,10 @@ public static function __callStatic($name, $arguments):bool throw new \InvalidArgumentException(sprintf('Validation method "%s" does not exist', $name)); } - public static function callback($value, $callback, $context = []):bool + /** + * @param array $context + */ + public static function callback(mixed $value, callable $callback, array $context = []): bool { $validator = new Rule\Callback(); $validator->setOption('callback', $callback); @@ -41,46 +53,46 @@ public static function callback($value, $callback, $context = []):bool return $validator->validate($value); } - public static function required($value):bool + public static function required(mixed $value): bool { return $value !== null && (!is_string($value) || trim($value) !== ''); } - public static function truthy($value):bool + public static function truthy(mixed $value): bool { - return (bool) $value; + return (bool)$value; } - public static function falsy($value):bool + public static function falsy(mixed $value): bool { - return ! static::truthy($value); + return !static::truthy($value); } - public static function number($value):bool + public static function number(mixed $value): bool { return $value == '0' || is_numeric($value); } - public static function integer($value):bool + public static function integer(mixed $value): bool { - return $value == '0' || (int) $value == $value; + return $value == '0' || (int)$value == $value; } - public static function lessThan($value, $max):bool + public static function lessThan(mixed $value, int|float $max): bool { $validator = new Rule\LessThan(['max' => $max]); return $validator->validate($value); } - public static function greaterThan($value, $min):bool + public static function greaterThan(mixed $value, int|float $min): bool { $validator = new Rule\GreaterThan(['min' => $min]); return $validator->validate($value); } - public static function between($value, $min, $max):bool + public static function between(mixed $value, int|float $min, int|float $max): bool { $validator = new Rule\Between([ 'min' => $min, @@ -90,52 +102,52 @@ public static function between($value, $min, $max):bool return $validator->validate($value); } - public static function exactly($value, $otherValue):bool + public static function exactly(mixed $value, mixed $otherValue): bool { return $value == $otherValue; } - public static function not($value, $otherValue):bool + public static function not(mixed $value, mixed $otherValue): bool { - return ! self::exactly($value, $otherValue); + return !self::exactly($value, $otherValue); } - public static function alpha($value):bool + public static function alpha(mixed $value): bool { $validator = new Rule\Alpha(); return $validator->validate($value); } - public static function alphanumeric($value):bool + public static function alphanumeric(mixed $value): bool { $validator = new Rule\AlphaNumeric(); return $validator->validate($value); } - public static function alphanumhyphen($value):bool + public static function alphanumhyphen(mixed $value): bool { $validator = new Rule\AlphaNumHyphen(); return $validator->validate($value); } - public static function minLength($value, $min):bool + public static function minLength(string $value, int $min): bool { $validator = new Rule\MinLength(['min' => $min]); return $validator->validate($value); } - public static function maxLength($value, $max):bool + public static function maxLength(string $value, int $max): bool { $validator = new Rule\MaxLength(['max' => $max]); return $validator->validate($value); } - public static function length($value, $min, $max):bool + public static function length(string $value, int $min, int $max): bool { $validator = new Rule\Length([ 'min' => $min, @@ -145,21 +157,30 @@ public static function length($value, $min, $max):bool return $validator->validate($value); } - public static function setMinSize($value, $min):bool + /** + * @param array $value + */ + public static function setMinSize(array $value, int $min): bool { $validator = new Rule\ArrayMinLength(['min' => $min]); return $validator->validate($value); } - public static function setMaxSize($value, $max):bool + /** + * @param array $value + */ + public static function setMaxSize(array $value, int $max): bool { $validator = new Rule\ArrayMaxLength(['max' => $max]); return $validator->validate($value); } - public static function setSize($value, $min, $max):bool + /** + * @param array $value + */ + public static function setSize(array $value, int $min, int $max): bool { $validator = new Rule\ArrayLength([ 'min' => $min, @@ -169,35 +190,44 @@ public static function setSize($value, $min, $max):bool return $validator->validate($value); } - public static function inList($value, $values):bool + /** + * @param list $values + */ + public static function inList(mixed $value, array $values): bool { $validator = new Rule\InList(['list' => $values]); return $validator->validate($value); } - public static function notInList($value, $values):bool + /** + * @param list $values + */ + public static function notInList(mixed $value, array $values): bool { $validator = new Rule\NotInList(['list' => $values]); return $validator->validate($value); } - public static function regex($value, $pattern):bool + public static function regex(mixed $value, string $pattern): bool { $validator = new Rule\Regex(['pattern' => $pattern]); return $validator->validate($value); } - public static function notRegex($value, $pattern):bool + public static function notRegex(mixed $value, string $pattern): bool { $validator = new Rule\NotRegex(['pattern' => $pattern]); return $validator->validate($value); } - public static function equalTo($value, $otherElementOrValue, $context = null):bool + /** + * @param array $context + */ + public static function equalTo(mixed $value, mixed $otherElementOrValue, array $context = []): bool { if (func_num_args() == 2) { return $value == $otherElementOrValue; @@ -206,7 +236,10 @@ public static function equalTo($value, $otherElementOrValue, $context = null):bo return $value == Arr::getByPath($context, $otherElementOrValue); } - public static function notEqualTo($value, $otherElementOrValue, $context = null):bool + /** + * @param array $context + */ + public static function notEqualTo(mixed $value, mixed $otherElementOrValue, array $context = []): bool { if (func_num_args() == 2) { return $value != $otherElementOrValue; @@ -215,56 +248,49 @@ public static function notEqualTo($value, $otherElementOrValue, $context = null) return $value != Arr::getByPath($context, $otherElementOrValue); } - public static function date($value, $format = 'Y-m-d'):bool + public static function date(mixed $value, string $format = 'Y-m-d'): bool { $validator = new Rule\Date(['format' => $format]); return $validator->validate($value); } - public static function dateTime($value, $format = 'Y-m-d H:i:s'):bool + public static function dateTime(mixed $value, string $format = 'Y-m-d H:i:s'): bool { $validator = new Rule\DateTime(['format' => $format]); return $validator->validate($value); } - public static function time($value, $format = 'H:i:s'):bool + public static function time(mixed $value, string $format = 'H:i:s'): bool { $validator = new Rule\Time(['format' => $format]); return $validator->validate($value); } - public static function website($value):bool + public static function website(mixed $value): bool { $validator = new Rule\Website(); return $validator->validate($value); } - public static function url($value):bool + public static function url(mixed $value): bool { $validator = new Rule\Url(); return $validator->validate($value); } - /** - * Test if a variable is a valid IP address - * - * @param string $value - * - * @return bool - */ - public static function ipAddress($value):bool + public static function ipAddress(mixed $value): bool { $validator = new Rule\IpAddress(); return $validator->validate($value); } - public static function email($value):bool + public static function email(mixed $value): bool { $validator = new Rule\Email(); @@ -274,12 +300,8 @@ public static function email($value):bool /** * Test if a variable is a full name * Criterias: at least 6 characters, 2 words - * - * @param mixed $value - * - * @return bool */ - public static function fullName($value):bool + public static function fullName(mixed $value): bool { $validator = new Rule\FullName(); @@ -288,12 +310,8 @@ public static function fullName($value):bool /** * Test if the domain of an email address is available - * - * @param string $value - * - * @return bool */ - public static function emailDomain($value):bool + public static function emailDomain(mixed $value): bool { $validator = new Rule\EmailDomain(); diff --git a/src/Rule/AbstractRule.php b/src/Rule/AbstractRule.php index 5480192..a61fd4d 100644 --- a/src/Rule/AbstractRule.php +++ b/src/Rule/AbstractRule.php @@ -1,5 +1,6 @@ */ - protected $options = []; + protected array $options = []; /** * Custom error message template for the validator instance * If you don't agree with the default messages that were provided - * - * @var string */ - protected $messageTemplate; + protected string $messageTemplate; /** * Result of the last validation - * - * @var boolean */ - protected $success = false; + protected bool $success = false; /** * Last value validated with the validator. * Stored in order to be passed to the errorMessage so that you get error * messages like '"abc" is not a valid email' - * - * @var mixed */ - protected $value; + protected mixed $value = null; /** * The error message prototype that will be used to generate the error message - * - * @var ErrorMessage */ - protected $errorMessagePrototype; + protected ?ErrorMessage $errorMessagePrototype = null; /** * Options map in case the options are passed as list instead of associative array * - * @var array + * @var array */ - protected $optionsIndexMap = []; + protected array $optionsIndexMap = []; - public function __construct($options = []) + /** + * @param array|string|null $options + */ + public function __construct(mixed $options = null) { $options = RuleHelper::normalizeOptions($options, $this->optionsIndexMap); - if (is_array($options) && ! empty($options)) { + if (is_array($options) && !empty($options)) { foreach ($options as $k => $v) { - $this->setOption($k, $v); + $this->setOption((string) $k, $v); } } } @@ -81,8 +77,6 @@ public function __construct($options = []) /** * Generates a unique string to identify the validator. * It is used to compare 2 validators so you don't add the same rule twice in a validator object - * - * @return string */ public function getUniqueId(): string { @@ -93,13 +87,8 @@ public function getUniqueId(): string * Set an option for the validator. * * The options are also be passed to the error message. - * - * @param string $name - * @param mixed $value - * - * @return AbstractRule */ - public function setOption($name, $value) + public function setOption(string $name, mixed $value): static { $this->options[$name] = $value; @@ -109,11 +98,9 @@ public function setOption($name, $value) /** * Get an option for the validator. * - * @param string $name - * * @return mixed */ - public function getOption($name) + public function getOption(string $name) { if (isset($this->options[$name])) { return $this->options[$name]; @@ -128,12 +115,11 @@ public function getOption($name) * For example, when you need to validate an email field matches another email field, * to confirm the email address * - * @param array|object $context + * @param array|WrapperInterface $context * - * @return AbstractRule - *@throws \InvalidArgumentException + * @throws \InvalidArgumentException */ - public function setContext($context = null) + public function setContext(mixed $context = null): self { if ($context === null) { return $this; @@ -141,7 +127,7 @@ public function setContext($context = null) if (is_array($context)) { $context = new ArrayWrapper($context); } - if (! is_object($context) || ! $context instanceof WrapperInterface) { + if (!$context instanceof WrapperInterface) { throw new \InvalidArgumentException( 'Validator context must be either an array or an instance of ' . WrapperInterface::class @@ -173,7 +159,7 @@ public function setMessageTemplate($messageTemplate) */ public function getMessageTemplate(): string { - if ($this->messageTemplate) { + if (isset($this->messageTemplate)) { return $this->messageTemplate; } if (isset($this->options['label'])) { @@ -185,25 +171,15 @@ public function getMessageTemplate(): string /** * Validates a value - * - * @param mixed $value - * @param null|mixed $valueIdentifier - * - * @return mixed */ - abstract public function validate($value, string $valueIdentifier = null):bool; + abstract public function validate(mixed $value, string $valueIdentifier = null): bool; /** - * Sets the error message prototype that will be used when returning the error message - * when validation fails. + * Sets the error message prototype that will be used when + * returning the error message if validation fails. * This option can be used when you need translation - * - * @param ErrorMessage $errorMessagePrototype - * - * @return AbstractRule - * @throws \InvalidArgumentException */ - public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype) + public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype): self { $this->errorMessagePrototype = $errorMessagePrototype; @@ -216,9 +192,9 @@ public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype) * * @return ErrorMessage */ - public function getErrorMessagePrototype():ErrorMessage + public function getErrorMessagePrototype(): ErrorMessage { - if (! $this->errorMessagePrototype) { + if (!$this->errorMessagePrototype) { $this->errorMessagePrototype = new ErrorMessage(); } @@ -227,10 +203,8 @@ public function getErrorMessagePrototype():ErrorMessage /** * Retrieve the error message if validation failed - * - * @return NULL|ErrorMessage */ - public function getMessage() + public function getMessage(): ?ErrorMessage { if ($this->success) { return null; @@ -262,16 +236,11 @@ public function getPotentialMessage(): ErrorMessage * Method for determining the path to a related item. * Eg: for `lines[5][price]` the related item `lines[*][quantity]` * has the value identifier as `lines[5][quantity]` - * - * @param $valueIdentifier - * @param $relatedItem - * - * @return string|null */ - protected function getRelatedValueIdentifier($valueIdentifier, $relatedItem) + protected function getRelatedValueIdentifier(string $valueIdentifier, string $relatedItem): string|null { // in case we don't have a related path - if (strpos($relatedItem, '*') === false) { + if (!str_contains($relatedItem, '*')) { return $relatedItem; } @@ -295,12 +264,10 @@ protected function getRelatedValueIdentifier($valueIdentifier, $relatedItem) } $relatedValueIdentifier = implode('][', $relatedValueIdentifierParts) . ']'; - $relatedValueIdentifier = str_replace( + return str_replace( $relatedValueIdentifierParts[0] . ']', $relatedValueIdentifierParts[0], $relatedValueIdentifier ); - - return $relatedValueIdentifier; } } diff --git a/src/Rule/AbstractStringRule.php b/src/Rule/AbstractStringRule.php index 4f04419..67fca90 100644 --- a/src/Rule/AbstractStringRule.php +++ b/src/Rule/AbstractStringRule.php @@ -5,13 +5,12 @@ abstract class AbstractStringRule extends AbstractRule { - protected function getStringLength($str) + protected function getStringLength(string $str): int { if (function_exists('mb_strlen')) { return mb_strlen( $str, - (isset($this->options['encoding']) && $this->options['encoding']) ? - $this->options['encoding'] : mb_internal_encoding() + $this->options['encoding'] ?? mb_internal_encoding() ); } diff --git a/src/Rule/Alpha.php b/src/Rule/Alpha.php index 14a214f..76f216c 100755 --- a/src/Rule/Alpha.php +++ b/src/Rule/Alpha.php @@ -1,5 +1,6 @@ value = $value; - $this->success = (bool) ctype_alpha((string) str_replace(' ', '', (string) $value)); + $this->value = $value; + $this->success = (bool)ctype_alpha((string)str_replace(' ', '', (string)$value)); return $this->success; } diff --git a/src/Rule/AlphaNumHyphen.php b/src/Rule/AlphaNumHyphen.php index d07b908..a9a8423 100755 --- a/src/Rule/AlphaNumHyphen.php +++ b/src/Rule/AlphaNumHyphen.php @@ -1,5 +1,6 @@ value = $value; - $this->success = (bool) ctype_alnum( - (string) str_replace( + $this->value = $value; + $this->success = (bool)ctype_alnum( + str_replace( [ ' ', '_', '-' ], '', - $value + (string) $value ) ); diff --git a/src/Rule/AlphaNumeric.php b/src/Rule/AlphaNumeric.php index 004e9f2..a8ef000 100755 --- a/src/Rule/AlphaNumeric.php +++ b/src/Rule/AlphaNumeric.php @@ -1,5 +1,6 @@ value = $value; - $this->success = (bool) ctype_alnum((string) str_replace(' ', '', $value)); + $this->value = $value; + $this->success = (bool)ctype_alnum((string)str_replace(' ', '', $value)); return $this->success; } diff --git a/src/Rule/ArrayLength.php b/src/Rule/ArrayLength.php index 36ae64c..5934a8f 100755 --- a/src/Rule/ArrayLength.php +++ b/src/Rule/ArrayLength.php @@ -1,5 +1,6 @@ self::OPTION_MIN, 1 => self::OPTION_MAX ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { - $this->value = $value; + $this->value = $value; $maxValidator = new ArrayMaxLength(); if (isset($this->options['max'])) { $maxValidator->setOption('max', $this->options['max']); @@ -29,9 +28,9 @@ public function validate($value, string $valueIdentifier = null):bool $minValidator->setOption('min', $this->options['min']); } $this->success = $minValidator->validate($value, $valueIdentifier) && $maxValidator->validate( - $value, - $valueIdentifier - ); + $value, + $valueIdentifier + ); return $this->success; } diff --git a/src/Rule/ArrayMaxLength.php b/src/Rule/ArrayMaxLength.php index 53cbf50..d4f7df9 100755 --- a/src/Rule/ArrayMaxLength.php +++ b/src/Rule/ArrayMaxLength.php @@ -1,5 +1,6 @@ value = $value; - if (! isset($this->options['max'])) { + if (!isset($this->options['max'])) { $this->success = true; } else { $this->success = is_array($value) && count($value) <= $this->options['max']; diff --git a/src/Rule/ArrayMinLength.php b/src/Rule/ArrayMinLength.php index 12ac939..efb8495 100755 --- a/src/Rule/ArrayMinLength.php +++ b/src/Rule/ArrayMinLength.php @@ -1,5 +1,6 @@ self::OPTION_MIN ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! isset($this->options['min'])) { + if (!isset($this->options['min'])) { $this->success = true; } else { $this->success = is_array($value) && count($value) >= $this->options['min']; diff --git a/src/Rule/Between.php b/src/Rule/Between.php index d1d2cc2..fd1b1cc 100755 --- a/src/Rule/Between.php +++ b/src/Rule/Between.php @@ -1,5 +1,6 @@ self::OPTION_MIN, 1 => self::OPTION_MAX ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { - $this->value = $value; + $this->value = $value; $minValidator = new LessThan(); if (isset($this->options['max'])) { $minValidator->setOption('max', $this->options['max']); @@ -29,9 +28,9 @@ public function validate($value, string $valueIdentifier = null):bool $maxValidator->setOption('min', $this->options['min']); } $this->success = $minValidator->validate($value, $valueIdentifier) && $maxValidator->validate( - $value, - $valueIdentifier - ); + $value, + $valueIdentifier + ); return $this->success; } diff --git a/src/Rule/Callback.php b/src/Rule/Callback.php index b226f0c..7b873f8 100755 --- a/src/Rule/Callback.php +++ b/src/Rule/Callback.php @@ -1,5 +1,6 @@ options['callback']); } elseif (is_object($this->options['callback'][0])) { $uniqueId .= '|' . spl_object_hash( - $this->options['callback'][0] - ) . '->' . $this->options['callback'][1]; + $this->options['callback'][0] + ) . '->' . $this->options['callback'][1]; } } elseif (is_object($this->options['callback']) && $this->options['callback'] instanceof \Closure) { $uniqueId .= '|' . spl_object_hash($this->options['callback']); } if (isset($this->options['arguments'])) { - $args = (array) $this->options['arguments']; + $args = (array)$this->options['arguments']; ksort($args); $uniqueId .= '|' . json_encode($args); } @@ -39,16 +40,16 @@ public function getUniqueId():string return $uniqueId; } - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! isset($this->options['callback']) || ! is_callable($this->options['callback'])) { + if (!isset($this->options['callback']) || !is_callable($this->options['callback'])) { $this->success = true; } else { - $args = (isset($this->options['arguments'])) ? (array) $this->options['arguments'] : []; + $args = (isset($this->options['arguments'])) ? (array)$this->options['arguments'] : []; array_unshift($args, $value); array_push($args, $valueIdentifier, $this->context); - $this->success = (bool) call_user_func_array($this->options['callback'], $args); + $this->success = (bool)call_user_func_array($this->options['callback'], $args); } return $this->success; diff --git a/src/Rule/Date.php b/src/Rule/Date.php index 8710896..303ff48 100644 --- a/src/Rule/Date.php +++ b/src/Rule/Date.php @@ -1,5 +1,6 @@ 'Y-m-d' ]; - protected $optionsIndexMap = [ + protected array $optionsIndexMap = [ 0 => self::OPTION_FORMAT ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { - $this->value = $value; + $this->value = $value; $this->success = $value == date( - $this->options['format'], - $this->getTimestampFromFormatedString($value, $this->options['format']) - ); + (string) $this->options['format'], + $this->getTimestampFromFormatedString($value, $this->options['format']) + ); return $this->success; } - protected function getTimestampFromFormatedString($string, $format) + protected function getTimestampFromFormatedString(mixed $string, mixed $format): ?int { $result = date_parse_from_format($format, $string); return mktime( - (int) $result['hour'], - (int) $result['minute'], - (int) $result['second'], - (int) $result['month'], - (int) $result['day'], - (int) $result['year'] - ); + (int)$result['hour'], + (int)$result['minute'], + (int)$result['second'], + (int)$result['month'], + (int)$result['day'], + (int)$result['year'] + ) ?: null; } } diff --git a/src/Rule/DateTime.php b/src/Rule/DateTime.php index 48c44c4..c6d63f6 100644 --- a/src/Rule/DateTime.php +++ b/src/Rule/DateTime.php @@ -1,5 +1,6 @@ 'Y-m-d H:i:s' ]; } diff --git a/src/Rule/Email.php b/src/Rule/Email.php index 136af6e..77d7b43 100755 --- a/src/Rule/Email.php +++ b/src/Rule/Email.php @@ -1,5 +1,6 @@ value = $value; - $this->success = (filter_var((string) $value, FILTER_VALIDATE_EMAIL) !== false); + $this->value = $value; + $this->success = (filter_var((string)$value, FILTER_VALIDATE_EMAIL) !== false); return $this->success; } diff --git a/src/Rule/EmailDomain.php b/src/Rule/EmailDomain.php index c83df83..a7cf903 100755 --- a/src/Rule/EmailDomain.php +++ b/src/Rule/EmailDomain.php @@ -1,5 +1,6 @@ value = $value; // Check if the email domain has a valid MX record - $this->success = (bool) checkdnsrr(preg_replace('/^[^@]+@/', '', $value), 'MX'); + $host = preg_replace('/^[^@]+@/', '', $value); + if ($host) { + $this->success = (bool)checkdnsrr($host, 'MX'); + } else { + $this->success = false; + } return $this->success; } diff --git a/src/Rule/Equal.php b/src/Rule/Equal.php index 80bd942..f6adc57 100644 --- a/src/Rule/Equal.php +++ b/src/Rule/Equal.php @@ -1,5 +1,6 @@ self::OPTION_VALUE ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; if (isset($this->options[self::OPTION_VALUE])) { diff --git a/src/Rule/File/Extension.php b/src/Rule/File/Extension.php index 5cb39e0..69c1c80 100644 --- a/src/Rule/File/Extension.php +++ b/src/Rule/File/Extension.php @@ -14,11 +14,11 @@ class Extension extends AbstractRule const LABELED_MESSAGE = '{label} does not have an acceptable extension ({file_extensions})'; - protected $options = [ + protected array $options = [ self::OPTION_ALLOWED_EXTENSIONS => [] ]; - public function setOption($name, $value) + public function setOption(string $name, mixed $value): static { if ($name == self::OPTION_ALLOWED_EXTENSIONS) { if (is_string($value)) { @@ -31,25 +31,25 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! file_exists($value)) { + if (!file_exists($value)) { $this->success = false; } else { - $extension = strtolower(substr($value, strrpos($value, '.') + 1, 10)); + $extension = strtolower(substr($value, strrpos($value, '.') + 1, 10)); $this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array( - $extension, - $this->options[self::OPTION_ALLOWED_EXTENSIONS] - ); + $extension, + $this->options[self::OPTION_ALLOWED_EXTENSIONS] + ); } return $this->success; } - public function getPotentialMessage():ErrorMessage + public function getPotentialMessage(): ErrorMessage { - $message = parent::getPotentialMessage(); + $message = parent::getPotentialMessage(); $fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]); $message->setVariables([ 'file_extensions' => implode(', ', $fileExtensions) diff --git a/src/Rule/File/Image.php b/src/Rule/File/Image.php index 065e624..0454609 100644 --- a/src/Rule/File/Image.php +++ b/src/Rule/File/Image.php @@ -14,22 +14,25 @@ class Image extends AbstractRule const LABELED_MESSAGE = '{label} is not a valid image (only {image_types} are allowed)'; - protected $options = [ + protected array $options = [ self::OPTION_ALLOWED_IMAGES => ['jpg', 'png', 'gif'] ]; - protected $imageTypesMap = [ - IMAGETYPE_GIF => 'gif', - IMAGETYPE_JPEG => 'jpg', + /** + * @var array + */ + protected array $imageTypesMap = [ + IMAGETYPE_GIF => 'gif', + IMAGETYPE_JPEG => 'jpg', IMAGETYPE_JPEG2000 => 'jpg', - IMAGETYPE_PNG => 'png', - IMAGETYPE_PSD => 'psd', - IMAGETYPE_BMP => 'bmp', - IMAGETYPE_ICO => 'ico', - IMAGETYPE_WEBP => 'webp', + IMAGETYPE_PNG => 'png', + IMAGETYPE_PSD => 'psd', + IMAGETYPE_BMP => 'bmp', + IMAGETYPE_ICO => 'ico', + IMAGETYPE_WEBP => 'webp', ]; - public function setOption($name, $value) + public function setOption(string $name, mixed $value): static { if ($name == self::OPTION_ALLOWED_IMAGES) { if (is_string($value)) { @@ -42,17 +45,17 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! file_exists($value)) { + if (!file_exists($value)) { $this->success = false; } else { - $imageInfo = getimagesize($value); + $imageInfo = getimagesize($value); if (!is_array($imageInfo)) { $this->success = false; } else { - $extension = $this->imageTypesMap[$imageInfo[2]] ?? false; + $extension = $this->imageTypesMap[$imageInfo[2]] ?? false; $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); } } @@ -60,9 +63,9 @@ public function validate($value, string $valueIdentifier = null):bool return $this->success; } - public function getPotentialMessage():ErrorMessage + public function getPotentialMessage(): ErrorMessage { - $message = parent::getPotentialMessage(); + $message = parent::getPotentialMessage(); $imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]); $message->setVariables([ 'image_types' => implode(', ', $imageTypes) diff --git a/src/Rule/File/ImageHeight.php b/src/Rule/File/ImageHeight.php index 14a9f7c..1675bfc 100644 --- a/src/Rule/File/ImageHeight.php +++ b/src/Rule/File/ImageHeight.php @@ -1,5 +1,6 @@ 1000000, self::OPTION_MIN => 0, ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; if (!file_exists($value)) { $this->success = false; } else { - $imageInfo = getimagesize($value); - $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; + $imageInfo = getimagesize($value); + $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; $this->success = $height && - $height <= $this->options[self::OPTION_MAX] && - $height >= $this->options[self::OPTION_MIN]; + $height <= $this->options[self::OPTION_MAX] && + $height >= $this->options[self::OPTION_MIN]; } return $this->success; diff --git a/src/Rule/File/ImageRatio.php b/src/Rule/File/ImageRatio.php index 4152db1..706b865 100644 --- a/src/Rule/File/ImageRatio.php +++ b/src/Rule/File/ImageRatio.php @@ -1,5 +1,6 @@ 0, + protected array $options = [ + self::OPTION_RATIO => 0, self::OPTION_ERROR_MARGIN => 0, ]; - protected function normalizeRatio($ratio) + protected function normalizeRatio(mixed $ratio): float { if (is_numeric($ratio) || $ratio == filter_var($ratio, FILTER_SANITIZE_NUMBER_FLOAT)) { return floatval($ratio); @@ -30,25 +31,25 @@ protected function normalizeRatio($ratio) if (strpos($ratio, ':') !== false) { list($width, $height) = explode(':', $ratio); - return $width / $height; + return (float) $width / (float) $height; } return 0; } - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - $ratio = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]); - if (! file_exists($value)) { + $ratio = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]); + if (!file_exists($value)) { $this->success = false; } elseif ($ratio == 0) { $this->success = true; } else { - $imageInfo = getimagesize($value); + $imageInfo = getimagesize($value); if (is_array($imageInfo)) { - $actualRatio = $imageInfo[0] / $imageInfo[1]; + $actualRatio = $imageInfo[0] / $imageInfo[1]; $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; } else { // no image size computed => no valid image diff --git a/src/Rule/File/ImageWidth.php b/src/Rule/File/ImageWidth.php index 178f974..b44b592 100644 --- a/src/Rule/File/ImageWidth.php +++ b/src/Rule/File/ImageWidth.php @@ -1,5 +1,6 @@ 1000000, self::OPTION_MIN => 0, ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! file_exists($value)) { + if (!file_exists($value)) { $this->success = false; } else { - $imageInfo = getimagesize($value); - $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; + $imageInfo = getimagesize($value); + $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; $this->success = $width && - $width <= $this->options[self::OPTION_MAX] && - $width >= $this->options[self::OPTION_MIN]; + $width <= $this->options[self::OPTION_MAX] && + $width >= $this->options[self::OPTION_MIN]; } return $this->success; diff --git a/src/Rule/File/Size.php b/src/Rule/File/Size.php index b27e9cc..f53bd83 100644 --- a/src/Rule/File/Size.php +++ b/src/Rule/File/Size.php @@ -1,5 +1,6 @@ '2M' ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! file_exists($value)) { + if (!file_exists($value)) { $this->success = false; } else { - $fileSize = @filesize($value); - $limit = RuleHelper::normalizeFileSize($this->options[self::OPTION_SIZE]); + $fileSize = @filesize($value); + $limit = RuleHelper::normalizeFileSize($this->options[self::OPTION_SIZE]); $this->success = $fileSize && $fileSize <= $limit; } diff --git a/src/Rule/FullName.php b/src/Rule/FullName.php index d6692bd..b93905d 100755 --- a/src/Rule/FullName.php +++ b/src/Rule/FullName.php @@ -1,5 +1,6 @@ value = $value; diff --git a/src/Rule/GreaterThan.php b/src/Rule/GreaterThan.php index ac3c31a..62b77ab 100755 --- a/src/Rule/GreaterThan.php +++ b/src/Rule/GreaterThan.php @@ -1,5 +1,6 @@ true ]; - protected $optionsIndexMap = [ + protected array $optionsIndexMap = [ 0 => self::OPTION_MIN, 1 => self::OPTION_INCLUSIVE ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! isset($this->options['min'])) { + if (!isset($this->options['min'])) { $this->success = true; } else { if ($this->options['inclusive']) { diff --git a/src/Rule/InList.php b/src/Rule/InList.php index f991c5b..6fe8772 100755 --- a/src/Rule/InList.php +++ b/src/Rule/InList.php @@ -10,14 +10,14 @@ class InList extends AbstractRule const MESSAGE = 'This input is not one of the accepted values'; const LABELED_MESSAGE = '{label} is not one of the accepted values'; - protected $optionsIndexMap = [ + protected array $optionsIndexMap = [ 0 => self::OPTION_LIST ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! isset($this->options['list'])) { + if (!isset($this->options['list'])) { $this->success = true; } else { if (is_array($this->options['list'])) { diff --git a/src/Rule/Integer.php b/src/Rule/Integer.php index f92684a..58dc2b5 100644 --- a/src/Rule/Integer.php +++ b/src/Rule/Integer.php @@ -1,5 +1,6 @@ value = $value; - $this->success = (bool) filter_var($value, FILTER_VALIDATE_INT) || (string) $value === '0'; + $this->value = $value; + $this->success = (bool)filter_var($value, FILTER_VALIDATE_INT) || $value === '0'; return $this->success; } diff --git a/src/Rule/IpAddress.php b/src/Rule/IpAddress.php index e39a7db..648dea6 100755 --- a/src/Rule/IpAddress.php +++ b/src/Rule/IpAddress.php @@ -1,5 +1,6 @@ value = $value; // Do not allow private and reserved range IPs $flags = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; if (strpos($value, ':') !== false) { - $this->success = (bool) filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE | FILTER_FLAG_IPV6); + $this->success = (bool)filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE | FILTER_FLAG_IPV6); } else { - $this->success = (bool) filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE | FILTER_FLAG_IPV4); + $this->success = (bool)filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE | FILTER_FLAG_IPV4); } return $this->success; diff --git a/src/Rule/Length.php b/src/Rule/Length.php index 49ca068..b963f9c 100755 --- a/src/Rule/Length.php +++ b/src/Rule/Length.php @@ -1,5 +1,6 @@ self::OPTION_MIN, 1 => self::OPTION_MAX, 2 => self::OPTION_ENCODING ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { - $this->value = $value; + $this->value = $value; $maxValidator = new MaxLength(); if (isset($this->options['max'])) { $maxValidator->setOption('max', $this->options['max']); @@ -31,9 +30,9 @@ public function validate($value, string $valueIdentifier = null):bool $minValidator->setOption('min', $this->options['min']); } $this->success = $minValidator->validate($value, $valueIdentifier) && $maxValidator->validate( - $value, - $valueIdentifier - ); + $value, + $valueIdentifier + ); return $this->success; } diff --git a/src/Rule/LessThan.php b/src/Rule/LessThan.php index 2a64dda..08d14aa 100755 --- a/src/Rule/LessThan.php +++ b/src/Rule/LessThan.php @@ -1,5 +1,6 @@ true ]; - protected $optionsIndexMap = [ + protected array $optionsIndexMap = [ 0 => self::OPTION_MAX, 1 => self::OPTION_INCLUSIVE ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! isset($this->options['max'])) { + if (!isset($this->options['max'])) { $this->success = true; } else { if ($this->options['inclusive']) { diff --git a/src/Rule/Matching.php b/src/Rule/Matching.php index a70f0c0..4df3900 100644 --- a/src/Rule/Matching.php +++ b/src/Rule/Matching.php @@ -1,5 +1,6 @@ self::OPTION_ITEM ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; if (isset($this->options[self::OPTION_ITEM])) { - $this->success = ($value == $this->context->getItemValue($this->options[self::OPTION_ITEM])); + $this->success = $this->context && ($value == $this->context->getItemValue($this->options[self::OPTION_ITEM])); } else { $this->success = true; } diff --git a/src/Rule/MaxLength.php b/src/Rule/MaxLength.php index 7614a51..90ecbc6 100755 --- a/src/Rule/MaxLength.php +++ b/src/Rule/MaxLength.php @@ -1,5 +1,6 @@ self::OPTION_MAX, 1 => self::OPTION_ENCODING ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! isset($this->options['max'])) { + if (!isset($this->options['max'])) { $this->success = true; } else { $this->success = $this->getStringLength($value) <= $this->options['max']; diff --git a/src/Rule/MinLength.php b/src/Rule/MinLength.php index 017c754..9c58134 100755 --- a/src/Rule/MinLength.php +++ b/src/Rule/MinLength.php @@ -1,5 +1,6 @@ self::OPTION_MIN, 1 => self::OPTION_ENCODING ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! isset($this->options['min'])) { + if (!isset($this->options['min'])) { $this->success = true; } else { $this->success = $this->getStringLength($value) >= $this->options['min']; diff --git a/src/Rule/NotEqual.php b/src/Rule/NotEqual.php index 936f814..436898e 100644 --- a/src/Rule/NotEqual.php +++ b/src/Rule/NotEqual.php @@ -1,5 +1,6 @@ success = ! $this->success; + $this->success = !$this->success; return $this->success; } diff --git a/src/Rule/NotInList.php b/src/Rule/NotInList.php index 7fd3a29..165b5c1 100755 --- a/src/Rule/NotInList.php +++ b/src/Rule/NotInList.php @@ -1,5 +1,6 @@ self::OPTION_LIST ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! isset($this->options['list'])) { + if (!isset($this->options['list'])) { $this->success = true; } else { if (is_array($this->options['list'])) { - $this->success = ! in_array($value, $this->options['list']); + $this->success = !in_array($value, $this->options['list']); } } diff --git a/src/Rule/NotMatch.php b/src/Rule/NotMatch.php index 94cd199..207ef71 100644 --- a/src/Rule/NotMatch.php +++ b/src/Rule/NotMatch.php @@ -1,5 +1,6 @@ success = ! $this->success; + $this->success = !$this->success; return $this->success; } diff --git a/src/Rule/NotRegex.php b/src/Rule/NotRegex.php index d84ec53..6197e65 100755 --- a/src/Rule/NotRegex.php +++ b/src/Rule/NotRegex.php @@ -1,5 +1,6 @@ success = ! $this->success; + $this->success = !$this->success; return $this->success; } diff --git a/src/Rule/Number.php b/src/Rule/Number.php index 04da72a..04b7dcf 100644 --- a/src/Rule/Number.php +++ b/src/Rule/Number.php @@ -1,5 +1,6 @@ value = $value; - $this->success = (bool) filter_var($value, FILTER_VALIDATE_FLOAT) || (string) $value === '0'; + $this->value = $value; + $this->success = (bool)filter_var($value, FILTER_VALIDATE_FLOAT) || (string)$value === '0'; return $this->success; } diff --git a/src/Rule/Regex.php b/src/Rule/Regex.php index 5f71c55..eb4d9c9 100755 --- a/src/Rule/Regex.php +++ b/src/Rule/Regex.php @@ -1,5 +1,6 @@ self::OPTION_PATTERN ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; if (isset($this->options['pattern'])) { - $this->success = (bool) preg_match($this->options['pattern'], $value); + $this->success = (bool)preg_match($this->options['pattern'], $value); } else { $this->success = true; } diff --git a/src/Rule/Required.php b/src/Rule/Required.php index 4124862..e84f07e 100755 --- a/src/Rule/Required.php +++ b/src/Rule/Required.php @@ -1,5 +1,6 @@ value = $value; + $this->value = $value; $this->success = ($value !== null && $value !== ''); return $this->success; diff --git a/src/Rule/RequiredWhen.php b/src/Rule/RequiredWhen.php index d6aa0f9..58a8c93 100644 --- a/src/Rule/RequiredWhen.php +++ b/src/Rule/RequiredWhen.php @@ -1,5 +1,6 @@ options[self::OPTION_RULE_OPTIONS])) ? - (array) $this->options[self::OPTION_RULE_OPTIONS] : + (array)$this->options[self::OPTION_RULE_OPTIONS] : []; if (is_string($this->options[self::OPTION_RULE])) { @@ -25,36 +25,36 @@ public function getItemRule() $rule = new $ruleClass($ruleOptions); } elseif (class_exists('Sirius\\Validation\\Rule\\' . $ruleClass)) { $ruleClass = 'Sirius\\Validation\\Rule\\' . $ruleClass; - $rule = new $ruleClass($ruleOptions); + $rule = new $ruleClass($ruleOptions); } } elseif (is_object($this->options[self::OPTION_RULE]) - && $this->options[self::OPTION_RULE] instanceof AbstractRule + && $this->options[self::OPTION_RULE] instanceof AbstractRule ) { $rule = $this->options[self::OPTION_RULE]; } - if (! $rule) { + if (!$rule) { throw new \InvalidArgumentException( 'Validator for the other item is not valid or cannot be constructed based on the data provided' ); } - $context = $this->context ? $this->context : []; - $rule->setContext($context); + /* @var $rule AbstractRule */ + $rule->setContext($this->context ?? []); // @phpstan-ignore-line - return $rule; + return $rule; // @phpstan-ignore-line } - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! isset($this->options[self::OPTION_ITEM])) { + if (!isset($this->options[self::OPTION_ITEM])) { $this->success = true; } else { - $relatedItemPath = $this->getRelatedValueIdentifier($valueIdentifier, $this->options[self::OPTION_ITEM]); - $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; + $relatedItemPath = $this->getRelatedValueIdentifier((string)$valueIdentifier, $this->options[self::OPTION_ITEM]); + $relatedItemValue = $this->context && $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; $itemRule = $this->getItemRule(); - if ($itemRule->validate($relatedItemValue, $relatedItemPath)) { + if ($itemRule && $itemRule->validate($relatedItemValue, $relatedItemPath)) { $this->success = ($value !== null && (!is_string($value) || trim($value) !== '')); } else { $this->success = true; diff --git a/src/Rule/RequiredWith.php b/src/Rule/RequiredWith.php index 36eb815..bb5cd27 100644 --- a/src/Rule/RequiredWith.php +++ b/src/Rule/RequiredWith.php @@ -1,5 +1,6 @@ self::OPTION_ITEM ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - $relatedItemPath = $this->getRelatedValueIdentifier($valueIdentifier, $this->options[self::OPTION_ITEM]); - $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; + $relatedItemPath = $this->getRelatedValueIdentifier((string) $valueIdentifier, $this->options[self::OPTION_ITEM]); + $relatedItemValue = $this->context && $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; if (isset($this->options[self::OPTION_ITEM]) && $relatedItemValue !== null) { $this->success = ($value !== null && (!is_string($value) || trim($value) !== '')); diff --git a/src/Rule/RequiredWithout.php b/src/Rule/RequiredWithout.php index 8628a5c..384e0b6 100644 --- a/src/Rule/RequiredWithout.php +++ b/src/Rule/RequiredWithout.php @@ -1,5 +1,6 @@ self::OPTION_ITEM ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - $relatedItemPath = $this->getRelatedValueIdentifier($valueIdentifier, $this->options[self::OPTION_ITEM]); - $relatedItemValue = $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; + $relatedItemPath = $this->getRelatedValueIdentifier((string) $valueIdentifier, $this->options[self::OPTION_ITEM]); + $relatedItemValue = $this->context && $relatedItemPath !== null ? $this->context->getItemValue($relatedItemPath) : null; if (isset($this->options[self::OPTION_ITEM]) && $relatedItemValue === null) { $this->success = ($value !== null && (!is_string($value) || trim($value) !== '')); diff --git a/src/Rule/Time.php b/src/Rule/Time.php index 2bf1285..0439f3c 100644 --- a/src/Rule/Time.php +++ b/src/Rule/Time.php @@ -8,7 +8,7 @@ class Time extends Date const MESSAGE = 'This input must be a time having the format {format}'; const LABELED_MESSAGE = '{label} must be a time having the format {format}'; - protected $options = [ + protected array $options = [ 'format' => 'H:i:s' ]; } diff --git a/src/Rule/Upload/Extension.php b/src/Rule/Upload/Extension.php index 49f2be3..34b99ce 100644 --- a/src/Rule/Upload/Extension.php +++ b/src/Rule/Upload/Extension.php @@ -14,11 +14,11 @@ class Extension extends AbstractRule const LABELED_MESSAGE = '{label} does not have an acceptable extension ({file_extensions})'; - protected $options = [ + protected array $options = [ self::OPTION_ALLOWED_EXTENSIONS => [] ]; - public function setOption($name, $value) + public function setOption(string $name, mixed $value): static { if ($name == self::OPTION_ALLOWED_EXTENSIONS) { if (is_string($value)) { @@ -31,27 +31,27 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! is_array($value) || ! isset($value['tmp_name'])) { + if (!is_array($value) || !isset($value['tmp_name'])) { $this->success = false; - } elseif (! file_exists($value['tmp_name'])) { + } elseif (!file_exists($value['tmp_name'])) { $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { - $extension = strtolower(substr($value['name'], strrpos($value['name'], '.') + 1, 10)); + $extension = strtolower(substr($value['name'], strrpos($value['name'], '.') + 1, 10)); $this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array( - $extension, - $this->options[self::OPTION_ALLOWED_EXTENSIONS] - ); + $extension, + $this->options[self::OPTION_ALLOWED_EXTENSIONS] + ); } return $this->success; } - public function getPotentialMessage():ErrorMessage + public function getPotentialMessage(): ErrorMessage { - $message = parent::getPotentialMessage(); + $message = parent::getPotentialMessage(); $fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]); $message->setVariables([ 'file_extensions' => implode(', ', $fileExtensions) diff --git a/src/Rule/Upload/Image.php b/src/Rule/Upload/Image.php index d9b9319..99ae24c 100644 --- a/src/Rule/Upload/Image.php +++ b/src/Rule/Upload/Image.php @@ -14,22 +14,25 @@ class Image extends AbstractRule const LABELED_MESSAGE = '{label} is not a valid image (only {image_types} are allowed)'; - protected $options = [ + protected array $options = [ self::OPTION_ALLOWED_IMAGES => ['jpg', 'png', 'gif'] ]; + /** + * @var array + */ protected $imageTypesMap = [ - IMAGETYPE_GIF => 'gif', - IMAGETYPE_JPEG => 'jpg', + IMAGETYPE_GIF => 'gif', + IMAGETYPE_JPEG => 'jpg', IMAGETYPE_JPEG2000 => 'jpg', - IMAGETYPE_PNG => 'png', - IMAGETYPE_PSD => 'psd', - IMAGETYPE_BMP => 'bmp', - IMAGETYPE_ICO => 'ico', - IMAGETYPE_WEBP => 'webp', + IMAGETYPE_PNG => 'png', + IMAGETYPE_PSD => 'psd', + IMAGETYPE_BMP => 'bmp', + IMAGETYPE_ICO => 'ico', + IMAGETYPE_WEBP => 'webp', ]; - public function setOption($name, $value) + public function setOption(string $name, mixed $value): static { if ($name == self::OPTION_ALLOWED_IMAGES) { if (is_string($value)) { @@ -42,19 +45,19 @@ public function setOption($name, $value) return parent::setOption($name, $value); } - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! is_array($value) || ! isset($value['tmp_name'])) { + if (!is_array($value) || !isset($value['tmp_name'])) { $this->success = false; - } elseif (! file_exists($value['tmp_name'])) { + } elseif (!file_exists($value['tmp_name'])) { $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { - $imageInfo = getimagesize($value['tmp_name']); + $imageInfo = getimagesize($value['tmp_name']); if (!is_array($imageInfo)) { $this->success = false; } else { - $extension = $this->imageTypesMap[$imageInfo[2]] ?? false; + $extension = $this->imageTypesMap[$imageInfo[2]] ?? false; $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); } } @@ -62,9 +65,9 @@ public function validate($value, string $valueIdentifier = null):bool return $this->success; } - public function getPotentialMessage():ErrorMessage + public function getPotentialMessage(): ErrorMessage { - $message = parent::getPotentialMessage(); + $message = parent::getPotentialMessage(); $imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]); $message->setVariables([ 'image_types' => implode(', ', $imageTypes) diff --git a/src/Rule/Upload/ImageHeight.php b/src/Rule/Upload/ImageHeight.php index 7d4b284..ba28835 100644 --- a/src/Rule/Upload/ImageHeight.php +++ b/src/Rule/Upload/ImageHeight.php @@ -1,5 +1,6 @@ 1000000, self::OPTION_MIN => 0, ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! is_array($value) || ! isset($value['tmp_name'])) { + if (!is_array($value) || !isset($value['tmp_name'])) { $this->success = false; - } elseif (! file_exists($value['tmp_name'])) { + } elseif (!file_exists($value['tmp_name'])) { $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { - $imageInfo = getimagesize($value['tmp_name']); - $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; + $imageInfo = getimagesize($value['tmp_name']); + $height = isset($imageInfo[1]) ? $imageInfo[1] : 0; $this->success = $height && - $height <= $this->options[self::OPTION_MAX] && - $height >= $this->options[self::OPTION_MIN]; + $height <= $this->options[self::OPTION_MAX] && + $height >= $this->options[self::OPTION_MIN]; } return $this->success; diff --git a/src/Rule/Upload/ImageRatio.php b/src/Rule/Upload/ImageRatio.php index 78d3798..865c260 100644 --- a/src/Rule/Upload/ImageRatio.php +++ b/src/Rule/Upload/ImageRatio.php @@ -1,5 +1,6 @@ 0, + protected array $options = [ + self::OPTION_RATIO => 0, self::OPTION_ERROR_MARGIN => 0, ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - $ratio = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]); - if (! is_array($value) || ! isset($value['tmp_name'])) { + $ratio = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]); + if (!is_array($value) || !isset($value['tmp_name'])) { $this->success = false; - } elseif (! file_exists($value['tmp_name'])) { + } elseif (!file_exists($value['tmp_name'])) { $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } elseif ($ratio == 0) { $this->success = true; } else { - $imageInfo = getimagesize($value['tmp_name']); + $imageInfo = getimagesize($value['tmp_name']); if (is_array($imageInfo)) { - $actualRatio = $imageInfo[0] / $imageInfo[1]; + $actualRatio = $imageInfo[0] / $imageInfo[1]; $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; } else { // no image size computed => no valid image diff --git a/src/Rule/Upload/ImageWidth.php b/src/Rule/Upload/ImageWidth.php index 132ea9e..753d495 100644 --- a/src/Rule/Upload/ImageWidth.php +++ b/src/Rule/Upload/ImageWidth.php @@ -1,5 +1,6 @@ 1000000, self::OPTION_MIN => 0, ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! is_array($value) || ! isset($value['tmp_name'])) { + if (!is_array($value) || !isset($value['tmp_name'])) { $this->success = false; - } elseif (! file_exists($value['tmp_name'])) { + } elseif (!file_exists($value['tmp_name'])) { $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { - $imageInfo = getimagesize($value['tmp_name']); - $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; + $imageInfo = getimagesize($value['tmp_name']); + $width = isset($imageInfo[0]) ? $imageInfo[0] : 0; $this->success = $width && - $width <= $this->options[self::OPTION_MAX] && - $width >= $this->options[self::OPTION_MIN]; + $width <= $this->options[self::OPTION_MAX] && + $width >= $this->options[self::OPTION_MIN]; } return $this->success; diff --git a/src/Rule/Upload/Required.php b/src/Rule/Upload/Required.php index 15d6bb4..253b820 100644 --- a/src/Rule/Upload/Required.php +++ b/src/Rule/Upload/Required.php @@ -17,11 +17,11 @@ class Required extends AbstractRule const LABELED_MESSAGE = '{label} is required'; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! is_array($value) || ! isset($value['tmp_name']) || - ! file_exists($value['tmp_name']) || $value['error'] !== UPLOAD_ERR_OK) { + if (!is_array($value) || !isset($value['tmp_name']) || + !file_exists($value['tmp_name']) || $value['error'] !== UPLOAD_ERR_OK) { $this->success = false; } else { $this->success = true; diff --git a/src/Rule/Upload/Size.php b/src/Rule/Upload/Size.php index 620f3fa..b9fc0a6 100644 --- a/src/Rule/Upload/Size.php +++ b/src/Rule/Upload/Size.php @@ -1,5 +1,6 @@ '2M' ]; - public function validate($value, string $valueIdentifier = null):bool + public function validate(mixed $value, string $valueIdentifier = null): bool { $this->value = $value; - if (! is_array($value) || ! isset($value['tmp_name'])) { + if (!is_array($value) || !isset($value['tmp_name'])) { $this->success = false; - } elseif (! file_exists($value['tmp_name'])) { + } elseif (!file_exists($value['tmp_name'])) { $this->success = $value['error'] === UPLOAD_ERR_NO_FILE; } else { - $fileSize = @filesize($value['tmp_name']); - $limit = RuleHelper::normalizeFileSize($this->options[self::OPTION_SIZE]); + $fileSize = @filesize($value['tmp_name']); + $limit = RuleHelper::normalizeFileSize($this->options[self::OPTION_SIZE]); $this->success = $fileSize && $fileSize <= $limit; } diff --git a/src/Rule/Url.php b/src/Rule/Url.php index 0f6dbe4..ce9bd8f 100755 --- a/src/Rule/Url.php +++ b/src/Rule/Url.php @@ -1,5 +1,6 @@ value = $value; - $this->success = (bool) filter_var($value, FILTER_VALIDATE_URL); + $this->value = $value; + $this->success = (bool)filter_var($value, FILTER_VALIDATE_URL); return $this->success; } diff --git a/src/Rule/Website.php b/src/Rule/Website.php index 530364c..591ac86 100755 --- a/src/Rule/Website.php +++ b/src/Rule/Website.php @@ -1,5 +1,6 @@ value = $value; + $this->value = $value; $this->success = (substr($value, 0, 2) == '//') - || (preg_match(static::WEBSITE_REGEX, $value) && filter_var( - $value, - FILTER_VALIDATE_URL - )); + || (preg_match(static::WEBSITE_REGEX, $value) && filter_var( + $value, + FILTER_VALIDATE_URL + )); return $this->success; } diff --git a/src/RuleCollection.php b/src/RuleCollection.php index ee8d551..a7109ec 100644 --- a/src/RuleCollection.php +++ b/src/RuleCollection.php @@ -4,17 +4,14 @@ namespace Sirius\Validation; -use SplObjectStorage; use ReturnTypeWillChange; +use Sirius\Validation\Rule\AbstractRule; +use SplObjectStorage; class RuleCollection extends SplObjectStorage { - /** - * @param null|object $rule - * @param null|mixed $data - */ #[ReturnTypeWillChange] - public function attach($rule, $data = null) + public function attach(mixed $rule, mixed $data = null): void { if ($this->contains($rule)) { return; @@ -36,13 +33,10 @@ public function attach($rule, $data = null) parent::attach($rule); } - /** - * @param object $rule - */ #[ReturnTypeWillChange] - public function getHash($rule) + public function getHash($rule): string { - /* @var $rule Sirius\Validation\Rule\AbstractRule */ + /** @var AbstractRule $rule */ return $rule->getUniqueId(); } } diff --git a/src/RuleFactory.php b/src/RuleFactory.php index 1bd53a1..2cb5360 100644 --- a/src/RuleFactory.php +++ b/src/RuleFactory.php @@ -14,19 +14,19 @@ class RuleFactory * You can use 'required' instead of 'required' for the name of the rule * or 'minLength'/'minlength' instead of 'MinLength' * - * @var array + * @var array */ - protected $validatorsMap = []; + protected array $validatorsMap = []; /** - * @var array + * @var array */ - protected $errorMessages = []; + protected array $errorMessages = []; /** - * @var array + * @var array */ - protected $labeledErrorMessages = []; + protected array $labeledErrorMessages = []; /** * Constructor @@ -39,7 +39,7 @@ public function __construct() /** * Set up the default rules that come with the library */ - protected function registerDefaultRules() + protected function registerDefaultRules(): void { $rulesClasses = [ 'Alpha', @@ -92,9 +92,9 @@ protected function registerDefaultRules() 'Upload\Size', ]; foreach ($rulesClasses as $class) { - $fullClassName = '\\' . __NAMESPACE__ . '\Rule\\' . $class; - $name = strtolower(str_replace('\\', '', $class)); - $errorMessage = constant($fullClassName . '::MESSAGE'); + $fullClassName = '\\' . __NAMESPACE__ . '\Rule\\' . $class; + $name = strtolower(str_replace('\\', '', $class)); + $errorMessage = constant($fullClassName . '::MESSAGE'); $labeledErrorMessage = constant($fullClassName . '::LABELED_MESSAGE'); $this->register($name, $fullClassName, $errorMessage, $labeledErrorMessage); } @@ -106,11 +106,11 @@ protected function registerDefaultRules() * Register a class to be used when creating validation rules * * @param string $name - * @param string $class + * @param string|class-string $class * * @return $this */ - public function register($name, $class, $errorMessage = '', $labeledErrorMessage = '') + public function register(string $name, string $class, string $errorMessage = '', string $labeledErrorMessage = ''): self { if (is_subclass_of($class, '\Sirius\Validation\Rule\AbstractRule')) { $this->validatorsMap[$name] = $class; @@ -128,19 +128,15 @@ public function register($name, $class, $errorMessage = '', $labeledErrorMessage /** * Factory method to construct a validator based on options that are used most of the times * - * @param string|callable $name + * @param string|callable|mixed $name * name of a validator class or a callable object/function - * @param string|array $options + * @param string|array|null $options * validator options (an array, JSON string or QUERY string) - * @param string $messageTemplate - * error message template - * @param string $label - * label of the form input field or model attribute * - * @throws \InvalidArgumentException * @return AbstractRule + * @throws \InvalidArgumentException */ - public function createRule($name, $options = null, $messageTemplate = null, $label = null):AbstractRule + public function createRule(mixed $name, mixed $options = null, string $messageTemplate = null, string $label = null): AbstractRule { $validator = $this->construcRuleByNameAndOptions($name, $options); @@ -162,13 +158,9 @@ public function createRule($name, $options = null, $messageTemplate = null, $lab /** * Set default error message for a rule * - * @param string $rule - * @param string|null $messageWithoutLabel - * @param string|null $messageWithLabel - * * @return $this */ - public function setMessages($rule, $messageWithoutLabel = null, $messageWithLabel = null) + public function setMessages(string $rule, string $messageWithoutLabel = null, string $messageWithLabel = null) { if ($messageWithoutLabel) { $this->errorMessages[$rule] = $messageWithoutLabel; @@ -183,13 +175,8 @@ public function setMessages($rule, $messageWithoutLabel = null, $messageWithLabe /** * Get the error message saved in the registry for a rule, where the message * is with or without a the label - * - * @param string $name name of the rule - * @param bool $withLabel - * - * @return string|NULL */ - protected function getSuggestedMessageTemplate($name, $withLabel) + protected function getSuggestedMessageTemplate(string $name, bool $withLabel): ?string { $noLabelMessage = is_string($name) && isset($this->errorMessages[$name]) ? $this->errorMessages[$name] : null; if ($withLabel) { @@ -202,16 +189,15 @@ protected function getSuggestedMessageTemplate($name, $withLabel) } /** - * @param $name - * @param $options + * @param string|array|null $options * - * @return CallbackRule + * @return CallbackRule|AbstractRule */ - protected function construcRuleByNameAndOptions($name, $options) + protected function construcRuleByNameAndOptions(string $name, mixed $options = null) { if (is_callable($name)) { $validator = new CallbackRule([ - 'callback' => $name, + 'callback' => $name, 'arguments' => $options ]); } elseif (is_string($name)) { @@ -232,7 +218,7 @@ protected function construcRuleByNameAndOptions($name, $options) if (!isset($validator)) { throw new \InvalidArgumentException( - sprintf('Impossible to determine the validator based on the name: %s', (string) $name) + sprintf('Impossible to determine the validator based on the name: %s', (string)$name) ); } diff --git a/src/Util/Arr.php b/src/Util/Arr.php index ef7e2b6..62876e5 100644 --- a/src/Util/Arr.php +++ b/src/Util/Arr.php @@ -12,22 +12,20 @@ class Arr const PATH_ROOT = '/'; /** - * @param $selector - * - * @return array + * @return array */ - protected static function getSelectorParts($selector) + protected static function getSelectorParts(string $selector): array { $firstOpen = strpos($selector, '['); if ($firstOpen === false) { return [$selector, '']; } - $firstClose = strpos($selector, ']'); - $container = substr($selector, 0, $firstOpen); + $firstClose = strpos($selector, ']'); + $container = substr($selector, 0, $firstOpen); $subselector = substr($selector, $firstOpen + 1, $firstClose - $firstOpen - 1) . substr( - $selector, - $firstClose + 1 - ); + $selector, + $firstClose + 1 + ); return [$container, $subselector]; } @@ -39,57 +37,49 @@ protected static function getSelectorParts($selector) * key[subkey] * key[0][subkey] * - * @param array $array - * @param string $path + * @param array $array * * @return mixed */ - public static function getByPath($array, $path = self::PATH_ROOT) + public static function getByPath(array $array, string $path = self::PATH_ROOT) { $path = trim($path); - if (! $path || $path == self::PATH_ROOT) { + if (!$path || $path === self::PATH_ROOT) { return $array; } // fix the path in case it was provided as `[item][subitem]` - if (strpos($path, '[') === 0) { + if (str_starts_with($path, '[')) { $path = preg_replace('/]/', '', ltrim($path, '['), 1); } - list($container, $subpath) = self::getSelectorParts($path); + list($container, $subpath) = self::getSelectorParts($path ?? ''); + $subarray = $array[$container] ?? null; if ($subpath === '') { - return array_key_exists($container, $array) ? $array[$container] : null; + return $subarray; } - return array_key_exists($container, $array) ? self::getByPath($array[$container], $subpath) : null; + return is_array($subarray) ? self::getByPath($subarray, $subpath) : null; } /** * Set values in the array by selector * + * @param array $array + * @param bool $overwrite true if the $value should overwrite the existing value + * + * @return array * @example * Arr::setBySelector($data, 'email', 'my@domain.com'); * Arr::setBySelector($data, 'addresses[0][line]', null); * Arr::setBySelector($data, 'addresses[*][line]', null); * - * @param array $array - * @param string $selector - * @param mixed $value - * @param bool $overwrite true if the $value should overwrite the existing value - * - * @return array */ - public static function setBySelector($array, $selector, $value, $overwrite = false) + public static function setBySelector(array $array, string $selector, mixed $value, bool $overwrite = false): array { - // make sure the array is an array in case we got here through a subsequent call - // so arraySetElementBySelector(array(), 'item[subitem]', 'value'); - // will call arraySetElementBySelector(null, 'subitem', 'value'); - if (! is_array($array)) { - $array = []; - } list($container, $subselector) = self::getSelectorParts($selector); - if (! $subselector) { + if (!$subselector) { if ($container !== '*') { - if ($overwrite === true || ! array_key_exists($container, $array)) { + if ($overwrite === true || !array_key_exists($container, $array)) { $array[$container] = $value; } } @@ -98,7 +88,7 @@ public static function setBySelector($array, $selector, $value, $overwrite = fal } // if we have a subselector the $array[$container] must be an array - if ($container !== '*' && ! array_key_exists($container, $array)) { + if ($container !== '*' && !array_key_exists($container, $array)) { $array[$container] = []; } // we got here through something like *[subitem] @@ -116,30 +106,28 @@ public static function setBySelector($array, $selector, $value, $overwrite = fal /** * Get values in the array by selector * + * @param array $array + * @return array * @example * Arr::getBySelector($data, 'email'); * Arr::getBySelector($data, 'addresses[0][line]'); * Arr::getBySelector($data, 'addresses[*][line]'); * - * @param $array - * @param $selector - * - * @return array */ - public static function getBySelector($array, $selector) + public static function getBySelector(array $array, string $selector): array { - if (strpos($selector, '[*]') === false) { + if (!str_contains($selector, '[*]')) { return [$selector => self::getByPath($array, $selector)]; } $result = []; list($preffix, $suffix) = explode('[*]', $selector, 2); $base = self::getByPath($array, $preffix); - if (! is_array($base)) { + if (!is_array($base)) { $base = []; } // we don't have a suffix, the selector was something like path[subpath][*] - if (! $suffix) { + if (!$suffix) { foreach ($base as $k => $v) { $result["{$preffix}[{$k}]"] = $v; } diff --git a/src/Util/RuleHelper.php b/src/Util/RuleHelper.php index fbbd332..9a0bca5 100644 --- a/src/Util/RuleHelper.php +++ b/src/Util/RuleHelper.php @@ -13,16 +13,17 @@ class RuleHelper * - a CSV string: '5,true' (for this scenario the 'optionsIndexMap' property is required) * * @param mixed $options + * @param array $optionsIndexMap * - * @return array + * @return array * @throws \InvalidArgumentException */ - public static function normalizeOptions($options, array $optionsIndexMap = []) + public static function normalizeOptions(mixed $options, array $optionsIndexMap = []): array { if ('0' === $options && count($optionsIndexMap) > 0) { $options = [$optionsIndexMap[0] => '0']; } - if (! $options) { + if (!$options) { return []; } @@ -42,7 +43,7 @@ public static function normalizeOptions($options, array $optionsIndexMap = []) } } - if (! is_array($result)) { + if (!is_array($result)) { throw new \InvalidArgumentException('Validator options should be an array, JSON string or query string'); } @@ -52,11 +53,9 @@ public static function normalizeOptions($options, array $optionsIndexMap = []) /** * Converts a HTTP query string to an array * - * @param $str - * - * @return array + * @return array|bool */ - public static function parseHttpQueryString(string $str) + public static function parseHttpQueryString(string $str): array|bool { parse_str($str, $arr); @@ -68,12 +67,12 @@ public static function parseHttpQueryString(string $str) * * @param $arr * - * @return bool|array + * @return bool|array|mixed */ - public static function convertBooleanStrings($arr) + public static function convertBooleanStrings(mixed $arr): mixed { if (is_array($arr)) { - return array_map([ __CLASS__, 'convertBooleanStrings'], $arr); + return array_map([__CLASS__, 'convertBooleanStrings'], $arr); } if ($arr === 'true') { return true; @@ -90,24 +89,22 @@ public static function convertBooleanStrings($arr) * Parses a CSV string and converts the result into an "options" array * (an associative array that contains the options for the validation rule) * - * @param $str - * - * @param array $optionsIndexMap + * @param array $optionsIndexMap * - * @return array + * @return array|bool */ - public static function parseCsvString($str, array $optionsIndexMap = []) + public static function parseCsvString(string $str, array $optionsIndexMap = []): array|bool { - if (! isset($optionsIndexMap) || ! is_array($optionsIndexMap) || empty($optionsIndexMap)) { + if (empty($optionsIndexMap)) { throw new \InvalidArgumentException( '`$optionsIndexMap` argument must be provided for CSV-type parameters' ); } $options = explode(',', $str); - $result = []; + $result = []; foreach ($options as $k => $v) { - if (! isset($optionsIndexMap[$k])) { + if (!isset($optionsIndexMap[$k])) { throw new \InvalidArgumentException(sprintf( '`$optionsIndexMap` for the validator is missing the %s index', $k @@ -122,33 +119,32 @@ public static function parseCsvString($str, array $optionsIndexMap = []) /** * Checks if an array is associative (ie: the keys are not numbers in sequence) * - * @param array $arr + * @param array $arr * * @return bool */ - public static function arrayIsAssoc($arr) + public static function arrayIsAssoc(array $arr): bool { return array_keys($arr) !== range(0, count($arr)); } - public static function normalizeFileSize($size) + public static function normalizeFileSize(string|int|float $size): int { - $size = (string) $size; - $units = ['B' => 0, 'K' => 1, 'M' => 2, 'G' => 3 ]; - $unit = strtoupper(substr($size, strlen($size) - 1, 1)); - if (! isset($units[$unit])) { + $size = (string)$size; + $units = ['B' => 0, 'K' => 1, 'M' => 2, 'G' => 3]; + $unit = strtoupper(substr($size, strlen($size) - 1, 1)); + if (!isset($units[$unit])) { $normalizedSize = filter_var($size, FILTER_SANITIZE_NUMBER_INT); } else { - $size = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); + $size = (float) filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT); $normalizedSize = $size * pow(1024, $units[$unit]); } - return $normalizedSize; + return (int) $normalizedSize; } - - public static function normalizeImageRatio($ratio) + public static function normalizeImageRatio(mixed $ratio): float { if (is_numeric($ratio) || $ratio == filter_var($ratio, FILTER_SANITIZE_NUMBER_FLOAT)) { return floatval($ratio); @@ -156,7 +152,7 @@ public static function normalizeImageRatio($ratio) if (strpos($ratio, ':') !== false) { list($width, $height) = explode(':', $ratio); - return $width / $height; + return (float) $width / (float) $height; } return 0; diff --git a/src/Validator.php b/src/Validator.php index f0d1430..6441a01 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -1,9 +1,9 @@ */ - protected $rules = []; + protected array $rules = []; /** - * @var array + * @var array */ - protected $messages = []; + protected array $messages = []; - /** - * @var RuleFactory - */ - protected $ruleFactory; + protected ?RuleFactory $ruleFactory = null; - /** - * @var ErrorMessage - */ - protected $errorMessagePrototype; + protected ?ErrorMessage $errorMessagePrototype = null; /** * The object that will contain the data - * - * @var WrapperInterface */ - protected $dataWrapper; + protected ?WrapperInterface $dataWrapper = null; public function __construct(RuleFactory $ruleFactory = null, ErrorMessage $errorMessagePrototype = null) { @@ -145,34 +137,20 @@ public function __construct(RuleFactory $ruleFactory = null, ErrorMessage $error /** * Retrieve the rule factory - * - * @return RuleFactory */ - public function getRuleFactory():RuleFactory + public function getRuleFactory(): ?RuleFactory { return $this->ruleFactory; } - /** - * @param ErrorMessage $errorMessagePrototype - * - * @throws \InvalidArgumentException - * - * @return $this - */ - public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype):Validator + public function setErrorMessagePrototype(ErrorMessage $errorMessagePrototype): static { $this->errorMessagePrototype = $errorMessagePrototype; return $this; } - /** - * Retrieve the error message prototype - * - * @return ErrorMessage - */ - public function getErroMessagePrototype():ErrorMessage + public function getErrorMessagePrototype(): ?ErrorMessage { return $this->errorMessagePrototype; } @@ -197,17 +175,8 @@ public function getErroMessagePrototype():ErrorMessage * // add validator with string and parameters as query string * $validator->add('field:label', 'minlength(min=2)({label} should have at least {min} characters)'); * - * @param string|array $selector - * @param string|callback $name - * @param string|array $options - * @param string $messageTemplate - * @param string $label - * - * @throws \InvalidArgumentException - * - * @return $this */ - public function add($selector, $name = null, $options = null, $messageTemplate = null, $label = null):Validator + public function add($selector, $name = null, $options = null, $messageTemplate = null, $label = null): static { // the $selector is an associative array with $selector => $rules if (func_num_args() == 1) { @@ -218,27 +187,26 @@ public function add($selector, $name = null, $options = null, $messageTemplate = return $this->addMultiple($selector); } + $selector = (string)$selector; // @phpstan-ignore-line // check if the selector is in the form of 'selector:Label' - if (strpos($selector, ':') !== false) { + if (str_contains($selector, ':')) { list($selector, $label) = explode(':', $selector, 2); } - $this->ensureSelectorRulesExist($selector, $label); - call_user_func(array( $this->rules[$selector], 'add' ), $name, $options, $messageTemplate, $label); + $this->ensureSelectorRulesExist($selector, $label ?? ''); + call_user_func([$this->rules[$selector], 'add'], $name, $options, $messageTemplate, $label); // @phpstan-ignore-line return $this; } /** - * @param array $selectorRulesCollection - * - * @return $this + * @param array $selectorRulesCollection */ - public function addMultiple($selectorRulesCollection):Validator + public function addMultiple(array $selectorRulesCollection): static { foreach ($selectorRulesCollection as $selector => $rules) { // a single rule was passed for the $valueSelector - if (! is_array($rules)) { + if (!is_array($rules)) { $this->add($selector, $rules); continue; } @@ -249,7 +217,7 @@ public function addMultiple($selectorRulesCollection):Validator if (is_array($rule)) { array_unshift($rule, $selector); call_user_func_array([$this, 'add'], $rule); - // the rule is only the name of the validator + // the rule is only the name of the validator } else { $this->add($selector, $rule); } @@ -259,17 +227,7 @@ public function addMultiple($selectorRulesCollection):Validator return $this; } - /** - * @param string $selector - * data selector - * @param mixed $name - * rule name or true if all rules should be deleted for that selector - * @param mixed $options - * rule options, necessary for rules that depend on params for their ID - * - * @return self - */ - public function remove($selector, $name = true, $options = null):Validator + public function remove($selector, $name = true, $options = null): self { if (!array_key_exists($selector, $this->rules)) { return $this; @@ -289,7 +247,7 @@ public function remove($selector, $name = true, $options = null):Validator * * @return WrapperInterface */ - public function getDataWrapper($data = null):WrapperInterface + public function getDataWrapper($data = null): WrapperInterface { // if $data is set reconstruct the data wrapper if (!$this->dataWrapper || $data) { @@ -299,7 +257,10 @@ public function getDataWrapper($data = null):WrapperInterface return $this->dataWrapper; } - public function setData($data):Validator + /** + * @param array|\ArrayObject|object $data + */ + public function setData(mixed $data): static { $this->getDataWrapper($data); $this->wasValidated = false; @@ -310,45 +271,32 @@ public function setData($data):Validator } /** - * Performs the validation - * - * @param mixed $data - * array to be validated - * - * @return boolean + * @param array|\ArrayObject|object|null $data */ - public function validate($data = null):bool + public function validate(mixed $data = null): bool { if ($data !== null) { $this->setData($data); } // data was already validated, return the results immediately - if ($this->wasValidated === true) { - return $this->wasValidated && count($this->messages) === 0; - } - foreach ($this->rules as $selector => $valueValidator) { - foreach ($this->getDataWrapper()->getItemsBySelector($selector) as $valueIdentifier => $value) { - /* @var $valueValidator \Sirius\Validation\ValueValidator */ - if (!$valueValidator->validate($value, $valueIdentifier, $this->getDataWrapper())) { - foreach ($valueValidator->getMessages() as $message) { - $this->addMessage($valueIdentifier, $message); + if (!$this->wasValidated === true) { + foreach ($this->rules as $selector => $valueValidator) { + foreach ($this->getDataWrapper()->getItemsBySelector($selector) as $valueIdentifier => $value) { + /* @var $valueValidator \Sirius\Validation\ValueValidator */ + if (!$valueValidator->validate($value, $valueIdentifier, $this->getDataWrapper())) { + foreach ($valueValidator->getMessages() as $message) { + $this->addMessage($valueIdentifier, $message); + } } } + $this->wasValidated = true; } } - $this->wasValidated = true; - return $this->wasValidated && count($this->messages) === 0; + return count($this->messages) === 0; } - /** - * @param string $item - * data identifier (eg: 'email', 'addresses[0][state]') - * @param string $message - * - * @return self - */ - public function addMessage($item, $message = null):Validator + public function addMessage(string $item, string|ErrorMessage $message = null): static { if ($message === null || $message === '') { return $this; @@ -363,12 +311,8 @@ public function addMessage($item, $message = null):Validator /** * Clears the messages of an item - * - * @param string $item - * - * @return self */ - public function clearMessages($item = null):Validator + public function clearMessages(string $item = null): static { if (is_string($item)) { if (array_key_exists($item, $this->messages)) { @@ -385,9 +329,10 @@ public function clearMessages($item = null):Validator * @param string $item * key of the messages array (eg: 'password', 'addresses[0][line_1]') * - * @return array + * @return array */ - public function getMessages($item = null):array + public + function getMessages(string $item = null): array { if (is_string($item)) { return array_key_exists($item, $this->messages) ? $this->messages[$item] : []; @@ -396,21 +341,20 @@ public function getMessages($item = null):array return $this->messages; } - public function getRules():array + /** + * @return array + */ + public function getRules(): array { return $this->rules; } - /** - * @param string $selector - * @param string $label - */ - protected function ensureSelectorRulesExist($selector, $label = null) + protected function ensureSelectorRulesExist(string $selector, string $label = ''): void { if (!isset($this->rules[$selector])) { $this->rules[$selector] = new ValueValidator( $this->getRuleFactory(), - $this->getErroMessagePrototype(), + $this->getErrorMessagePrototype(), $label ); } diff --git a/src/ValidatorInterface.php b/src/ValidatorInterface.php index 872393d..7f6aec9 100644 --- a/src/ValidatorInterface.php +++ b/src/ValidatorInterface.php @@ -5,9 +5,31 @@ interface ValidatorInterface { - public function add($selector, $name = null, $options = null, $messageTemplate = null, $label = null); + /** + * @param string|array $selector + * @param string|callable $name + * @param string|array $options + * @param string $messageTemplate + * @param string $label + * + * @throws \InvalidArgumentException + */ + public function add($selector, $name = null, $options = null, $messageTemplate = null, $label = null): self; - public function remove($selector, $name = true, $options = null); + /** + * @param string $selector + * data selector + * @param mixed $name + * rule name or true if all rules should be deleted for that selector + * @param mixed $options + * rule options, necessary for rules that depend on params for their ID + * + * @return self + */ + public function remove($selector, $name = true, $options = null): self; - public function validate($data = []); + /** + * @param array $data + */ + public function validate(array $data = []): bool; } diff --git a/src/ValueValidator.php b/src/ValueValidator.php index e264d07..dde50e1 100644 --- a/src/ValueValidator.php +++ b/src/ValueValidator.php @@ -4,6 +4,7 @@ namespace Sirius\Validation; use Sirius\Validation\Rule\AbstractRule; +use Sirius\Validation\Rule\AbstractValidator; class ValueValidator { @@ -11,44 +12,24 @@ class ValueValidator /** * The error messages generated after validation or set manually * - * @var array + * @var array */ protected $messages = []; - /** - * Will be used to construct the rules - * - * @var \Sirius\Validation\RuleFactory - */ - protected $ruleFactory; + protected RuleFactory $ruleFactory; - /** - * The prototype that will be used to generate the error message - * - * @var \Sirius\Validation\ErrorMessage - */ - protected $errorMessagePrototype; + protected ErrorMessage $errorMessagePrototype; - /** - * The rule collections for the validation - * - * @var \Sirius\Validation\RuleCollection - */ - protected $rules; - - /** - * The label of the value to be validated - * - * @var string - */ - protected $label; + protected RuleCollection $rules; + protected string $label; public function __construct( - RuleFactory $ruleFactory = null, + RuleFactory $ruleFactory = null, ErrorMessage $errorMessagePrototype = null, - $label = null - ) { + string $label = '' + ) + { if (!$ruleFactory) { $ruleFactory = new RuleFactory(); } @@ -63,7 +44,7 @@ public function __construct( $this->rules = new RuleCollection; } - public function setLabel($label = null):ValueValidator + public function setLabel(string $label = ''): self { $this->label = $label; @@ -73,6 +54,12 @@ public function setLabel($label = null):ValueValidator /** * Add 1 or more validation rules * + * @param string|callable $name + * @param string|array|null $options + * @param string|null $messageTemplate + * @param string|null $label + * + * @return ValueValidator * @example * // add multiple rules at once * $validator->add(array( @@ -92,16 +79,10 @@ public function setLabel($label = null):ValueValidator * // add validator with string and parameters as query string * $validator->add('minlength(min=2)({label} should have at least {min} characters)(Field label)'); * - * @param string|callback $name - * @param string|array $options - * @param string $messageTemplate - * @param string $label - * - * @return ValueValidator */ - public function add($name, $options = null, $messageTemplate = null, $label = null):ValueValidator + public function add(mixed $name, $options = null, string $messageTemplate = null, string $label = null): self { - if (is_array($name) && !is_callable($name)) { + if (is_array($name)) { return $this->addMultiple($name); } if (is_string($name)) { @@ -116,7 +97,7 @@ public function add($name, $options = null, $messageTemplate = null, $label = nu } // check for the default label - if (!$label && $this->label) { + if (!$label && isset($this->label)) { $label = $this->label; } @@ -126,11 +107,9 @@ public function add($name, $options = null, $messageTemplate = null, $label = nu } /** - * @param array $rules - * - * @return ValueValidator + * @param array $rules */ - public function addMultiple($rules):ValueValidator + public function addMultiple($rules): self { foreach ($rules as $singleRule) { // make sure the rule is an array (the parameters of subsequent calls); @@ -141,12 +120,7 @@ public function addMultiple($rules):ValueValidator return $this; } - /** - * @param AbstractValidator $validationRule - * - * @return ValueValidator - */ - public function addRule(AbstractRule $validationRule):ValueValidator + public function addRule(AbstractRule $validationRule): self { $validationRule->setErrorMessagePrototype($this->errorMessagePrototype); $this->rules->attach($validationRule); @@ -159,14 +133,14 @@ public function addRule(AbstractRule $validationRule):ValueValidator * * @param mixed $name * rule name or true if all rules should be deleted for that selector - * @param mixed $options + * @param string|array $options * rule options, necessary for rules that depend on params for their ID * + * @return self * @throws \InvalidArgumentException * @internal param string $selector data selector - * @return self */ - public function remove($name = true, $options = null):ValueValidator + public function remove($name = true, $options = null): self { if ($name === true) { $this->rules = new RuleCollection(); @@ -182,6 +156,9 @@ public function remove($name = true, $options = null):ValueValidator /** * Converts a rule that was supplied as string into a set of options that define the rule * + * @param string $ruleAsString + * + * @return array * @example 'minLength({"min":2})({label} must have at least {min} characters)(Street)' * * will be converted into @@ -193,31 +170,31 @@ public function remove($name = true, $options = null):ValueValidator * 'Street' // label * ] * - * @param string $ruleAsString - * - * @return array */ - protected function parseRule($ruleAsString):array + protected function parseRule($ruleAsString): array { - $ruleAsString = trim($ruleAsString); - $options = []; + $ruleAsString = trim($ruleAsString); + $name = $ruleAsString; + $options = []; $messageTemplate = null; - $label = null; + $label = null; - $name = substr($ruleAsString, 0, strpos($ruleAsString, '(')); - $ruleAsString = substr($ruleAsString, strpos($ruleAsString, '(')); - $matches = []; - preg_match_all('/\(([^\)]*)\)/', $ruleAsString, $matches); + if (str_contains($ruleAsString, '(')) { + $name = substr($ruleAsString, 0, strpos($ruleAsString, '(')); //@phpstan-ignore-line + $ruleAsString = substr($ruleAsString, strpos($ruleAsString, '(')); //@phpstan-ignore-line + $matches = []; + preg_match_all('/\(([^\)]*)\)/', $ruleAsString, $matches); - if (isset($matches[1])) { - if (isset($matches[1][0]) && $matches[1][0] !== '') { - $options = $matches[1][0]; - } - if (isset($matches[1][1]) && $matches[1][1]) { - $messageTemplate = $matches[1][1]; - } - if (isset($matches[1][2]) && $matches[1][2]) { - $label = $matches[1][2]; + if (isset($matches[1])) { + if (isset($matches[1][0]) && $matches[1][0] !== '') { + $options = $matches[1][0]; + } + if (isset($matches[1][1]) && $matches[1][1]) { + $messageTemplate = $matches[1][1]; + } + if (isset($matches[1][2]) && $matches[1][2]) { + $label = $matches[1][2]; + } } } @@ -230,13 +207,16 @@ protected function parseRule($ruleAsString):array } - public function validate($value, string $valueIdentifier = null, DataWrapper\WrapperInterface $context = null):bool + /** + * @param DataWrapper\WrapperInterface|null $context + */ + public function validate(mixed $value, string $valueIdentifier = '', DataWrapper\WrapperInterface $context = null): bool { $this->messages = []; - $isRequired = false; + $isRequired = false; // evaluate the required rules - /* @var $rule \Sirius\Validation\Rule\AbstractValidator */ + /** @var AbstractRule $rule */ foreach ($this->rules as $rule) { if ($rule instanceof Rule\Required) { $isRequired = true; @@ -253,13 +233,14 @@ public function validate($value, string $valueIdentifier = null, DataWrapper\Wra } // evaluate the non-required rules + /** @var AbstractRule $rule */ foreach ($this->rules as $rule) { if (!($rule instanceof Rule\Required)) { $this->validateRule($rule, $value, $valueIdentifier, $context); // if field is required and we have an error, // do not continue with the rest of rules - if ($isRequired && count($this->messages)) { + if ($isRequired && count($this->messages)) { //@phpstan-ignore-line break; } } @@ -268,7 +249,10 @@ public function validate($value, string $valueIdentifier = null, DataWrapper\Wra return count($this->messages) === 0; } - private function validateRule($rule, $value, $valueIdentifier, $context):bool + /** + * @param DataWrapper\WrapperInterface|null $context + */ + private function validateRule(AbstractRule $rule, mixed $value, string $valueIdentifier, $context): bool { $rule->setContext($context); if (!$rule->validate($value, $valueIdentifier)) { @@ -278,24 +262,30 @@ private function validateRule($rule, $value, $valueIdentifier, $context):bool return true; } - public function getMessages():array + /** + * @return mixed[] + */ + public function getMessages(): array { return $this->messages; } - public function addMessage($message):ValueValidator + public function addMessage(mixed $message): ValueValidator { array_push($this->messages, $message); return $this; } - public function getRules():RuleCollection + public function getRules(): RuleCollection { return $this->rules; } - protected function isEmpty($value):bool + /** + * @param mixed $value + */ + protected function isEmpty($value): bool { return in_array($value, [null, ''], true); } diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..5949c61 --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,45 @@ +in('Feature'); + +/* +|-------------------------------------------------------------------------- +| Expectations +|-------------------------------------------------------------------------- +| +| When you're writing tests, you often need to check that values meet certain conditions. The +| "expect()" function gives you access to a set of "expectations" methods that you can use +| to assert different things. Of course, you may extend the Expectation API at any time. +| +*/ + +expect()->extend('toBeOne', function () { + return $this->toBe(1); +}); + +/* +|-------------------------------------------------------------------------- +| Functions +|-------------------------------------------------------------------------- +| +| While Pest is very powerful out-of-the-box, you may have some testing code specific to your +| project that you don't want to repeat in every file. Here you can also expose helpers as +| global functions to help you to reduce the number of lines of code in your test files. +| +*/ + +function something() +{ + // .. +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..cfb05b6 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,10 @@ +validator = new Validator(); + $this->validator + ->add('email', 'email | required')// does the order matter? + ->add('email_confirm', 'required | email | match(item=email)') + ->add('password', 'required | notmatch(item=email)') + ->add('password_confirm', 'required | match(item=password)') + ->add('feedback', 'requiredwith(item=agree_to_provide_feedback)') + ->add('birthday', 'requiredwhen', array( 'item' => 'email_confirm', 'rule' => 'Email' )) + // the lines below don't match the example but that's ok, + // the individual rules have tests + ->add('lines[*][price]', 'requiredwith(item=lines[*][quantity])'); +}); -class ComplexTest extends \PHPUnit\Framework\TestCase -{ +test('with invalid data', function () { + $data = array( + 'email' => 'me@domain.com', + 'password' => 'me@domain.com', + 'password_confirm' => '123456', + 'agree_to_provide_feedback' => true, + 'lines' => array( + array( 'quantity' => 10, 'price' => null ) + ) + ); + $this->validator->validate($data); + $messages = $this->validator->getMessages(); - protected function setUp(): void - { - $this->validator = new Validator(); - $this->validator - ->add('email', 'email | required')// does the order matter? - ->add('email_confirm', 'required | email | match(item=email)') - ->add('password', 'required | notmatch(item=email)') - ->add('password_confirm', 'required | match(item=password)') - ->add('feedback', 'requiredwith(item=agree_to_provide_feedback)') - ->add('birthday', 'requiredwhen', array( 'item' => 'email_confirm', 'rule' => 'Email' )) - // the lines below don't match the example but that's ok, - // the individual rules have tests - ->add('lines[*][price]', 'requiredwith(item=lines[*][quantity])'); - } - - function notestWithCorrectData() - { - $data = array( - 'email' => 'me@domain.com', - 'email_confirm' => 'me@domain.com', - 'password' => '1234', - 'password_confirm' => '1234', - 'agree_to_provide_feedback' => true, - 'feedback' => 'This is great!', - 'birthday' => '1980-01-01', - 'lines' => array( - array( 'quantity' => 10, 'price' => 20 ) - ) - ); - $this->assertTrue($this->validator->validate($data)); - } - - function testWithInvalidData() - { - $data = array( - 'email' => 'me@domain.com', - 'password' => 'me@domain.com', - 'password_confirm' => '123456', - 'agree_to_provide_feedback' => true, - 'lines' => array( - array( 'quantity' => 10, 'price' => null ) - ) - ); - $this->validator->validate($data); - $messages = $this->validator->getMessages(); - - $this->assertEquals('This field is required', (string) $messages['email_confirm'][0]); - $this->assertEquals('This input does match email', (string) $messages['password'][0]); - $this->assertEquals('This input does not match password', (string) $messages['password_confirm'][0]); - $this->assertEquals('This field is required', (string) $messages['feedback'][0]); - $this->assertEquals('This field is required', (string) $messages['lines[0][price]'][0]); - } -} + expect((string) $messages['email_confirm'][0])->toEqual('This field is required'); + expect((string) $messages['password'][0])->toEqual('This input does match email'); + expect((string) $messages['password_confirm'][0])->toEqual('This input does not match password'); + expect((string) $messages['feedback'][0])->toEqual('This field is required'); + expect((string) $messages['lines[0][price]'][0])->toEqual('This field is required'); +}); diff --git a/tests/src/ErrorMessageTest.php b/tests/src/ErrorMessageTest.php index ad51a16..15bdfe8 100644 --- a/tests/src/ErrorMessageTest.php +++ b/tests/src/ErrorMessageTest.php @@ -1,36 +1,25 @@ validator = new Validator(); - $this->validator->setErrorMessagePrototype(new CustomErrorMessage()); - } +beforeEach(function () { + $this->validator = new Validator(); + $this->validator->setErrorMessagePrototype(new CustomErrorMessage()); +}); - function testErrorMessage() - { - $this->validator->add('email', 'email'); - $this->validator->validate(array( 'email' => 'not_an_email' )); +test('error message', function () { + $this->validator->add('email', 'email'); + $this->validator->validate(array( 'email' => 'not_an_email' )); - $messages = $this->validator->getMessages('email'); - $this->assertEquals(1, count($messages)); + $messages = $this->validator->getMessages('email'); + expect(count($messages))->toEqual(1); - $this->assertEquals('!!!This input must be a valid email address', (string) $messages[0]); - } - - -} + expect((string) $messages[0])->toEqual('!!!This input must be a valid email address'); +}); diff --git a/tests/src/HelperTest.php b/tests/src/HelperTest.php index 748ff0f..873f5d3 100755 --- a/tests/src/HelperTest.php +++ b/tests/src/HelperTest.php @@ -1,735 +1,678 @@ assertTrue(Helper::methodExists('email')); - $this->assertFalse(Helper::methodExists('nonExistingMethod')); - } - - function testOfRequired() - { - $pool = array( - 'abc' => true, - 1.2 => true, - '' => false - ); - foreach ($pool as $key => $value) { - $this->assertSame(Helper::required($key), $value); - } - $this->assertSame(Helper::required(null), false); - } - - function testOfTruthy() - { - $pool = array( - 'abc' => true, - 1.2 => true, - 0 => false, - '' => false - ); - foreach ($pool as $key => $value) { - $this->assertSame(Helper::truthy($key), $value); - } - } - - function testOfFalsy() - { - $pool = array( - 'abc' => false, - 1.2 => false, - 0 => true, - '' => true - ); - foreach ($pool as $key => $value) { - $this->assertSame(Helper::falsy($key), $value); - } - } - - function testOfCallback() - { - $this->assertTrue( - Helper::callback( - 3, - function ($value) { - return $value === 3; - } - ) - ); - } - - function testOfEmail() - { - $pool = array( - '-fa /lse@gmail.com' => false, - '12345@hotmail.com' => true, - 'xxx.yyyy-zzz@domain.com.noc' => true, - 'weird.name-99-@yahoo.com' => true, - 'shit' => false - ); - foreach ($pool as $key => $value) { - if ($value) { - $message = $key . ' is a valid email'; - } else { - $message = $key . ' is NOT a valid email'; - } - $this->assertSame(Helper::email($key), $value, $message); +use \Sirius\Validation\Helper; + +test('method exists', function () { + expect(Helper::methodExists('email'))->toBeTrue(); + expect(Helper::methodExists('nonExistingMethod'))->toBeFalse(); +}); + +test('required', function () { + $pool = array( + ['abc', true], + [1.2, true], + ['', false] + ); + foreach ($pool as list($key, $value)) { + expect($value)->toBe(Helper::required($key)); + } + expect(false)->toBe(Helper::required(null)); +}); + +test('truthy', function () { + $pool = array( + ['abc', true], + [1.2, true], + [0, false], + ['', false], + ); + foreach ($pool as list($key, $value)) { + expect($value)->toBe(Helper::truthy($key)); + } +}); + +test('falsy', function () { + $pool = array( + ['abc', false], + [1.2, false], + [0, true], + ['', true], + ); + foreach ($pool as list($key, $value)) { + expect($value)->toBe(Helper::falsy($key)); + } +}); + +test('callback', function () { + expect(Helper::callback( + 3, + function ($value) { + return $value === 3; } - } - - function testOfNumber() - { - $pool = array( - '1' => true, - '1,5' => false, - '2.5' => true, - 'abc' => false - ); - foreach ($pool as $key => $value) { - if ($value) { - $message = $key . ' is a valid number'; - } else { - $message = $key . ' is NOT a valid number'; - } - $this->assertSame(Helper::number($key), $value, $message); + ))->toBeTrue(); +}); + +test('email', function () { + $pool = array( + '-fa /lse@gmail.com' => false, + '12345@hotmail.com' => true, + 'xxx.yyyy-zzz@domain.com.noc' => true, + 'weird.name-99-@yahoo.com' => true, + 'shit' => false + ); + foreach ($pool as $key => $value) { + if ($value) { + $message = $key . ' is a valid email'; + } else { + $message = $key . ' is NOT a valid email'; } - } - - function testOfInteger() - { - $pool = array( - '1' => true, - '12345' => true, - '1.00' => true, - '1.24' => false - ); - foreach ($pool as $key => $value) { - if ($value) { - $message = $key . ' is a valid integer'; - } else { - $message = $key . ' is NOT a valid integer'; - } - $this->assertSame(Helper::integer($key), $value, $message); + expect($value)->toBe(Helper::email($key), $message); + } +}); + +test('number', function () { + $pool = array( + '1' => true, + '1,5' => false, + '2.5' => true, + 'abc' => false + ); + foreach ($pool as $key => $value) { + if ($value) { + $message = $key . ' is a valid number'; + } else { + $message = $key . ' is NOT a valid number'; } - } - - function testOfLessThan() - { - $pool = array( - array( - 1, - 0.5, - false - ), - array( - 1, - 1.2, - true - ) - ); - foreach ($pool as $sample) { - if ($sample[2]) { - $message = $sample[0] . ' is less than ' . $sample[1]; - } else { - $message = $sample[0] . ' is NOT less than ' . $sample[1]; - } - $this->assertSame(Helper::lessThan($sample[0], $sample[1]), $sample[2], $message); + expect($value)->toBe(Helper::number($key), $message); + } +}); + +test('integer', function () { + $pool = array( + '1' => true, + '12345' => true, + '1.00' => true, + '1.24' => false + ); + foreach ($pool as $key => $value) { + if ($value) { + $message = $key . ' is a valid integer'; + } else { + $message = $key . ' is NOT a valid integer'; } - } - - function testOfGreaterThan() - { - $pool = array( - array( - 1, - 0.5, - true - ), - array( - 1, - 1.2, - false - ) - ); - foreach ($pool as $sample) { - if ($sample[2]) { - $message = $sample[0] . ' is less than ' . $sample[1]; - } else { - $message = $sample[0] . ' is NOT less than ' . $sample[1]; - } - $this->assertSame(Helper::greaterThan($sample[0], $sample[1]), $sample[2], $message); + expect($value)->toBe(Helper::integer($key), $message); + } +}); + +test('less than', function () { + $pool = array( + array( + 1, + 0.5, + false + ), + array( + 1, + 1.2, + true + ) + ); + foreach ($pool as $sample) { + if ($sample[2]) { + $message = $sample[0] . ' is less than ' . $sample[1]; + } else { + $message = $sample[0] . ' is NOT less than ' . $sample[1]; } - } - - function testOfBetween() - { - $pool = array( - array( - 1, - 0.5, - 0.8, - false - ), - array( - 1, - 0.9, - 1.2, - true - ) - ); - foreach ($pool as $sample) { - if ($sample[2]) { - $message = $sample[0] . ' is between ' . $sample[1] . ' and ' . $sample[2]; - } else { - $message = $sample[0] . ' is NOT between ' . $sample[1] . ' and ' . $sample[2]; - } - $this->assertSame(Helper::between($sample[0], $sample[1], $sample[2]), $sample[3], $message); + expect($sample[2])->toBe(Helper::lessThan($sample[0], $sample[1]), $message); + } +}); + +test('greater than', function () { + $pool = array( + array( + 1, + 0.5, + true + ), + array( + 1, + 1.2, + false + ) + ); + foreach ($pool as $sample) { + if ($sample[2]) { + $message = $sample[0] . ' is less than ' . $sample[1]; + } else { + $message = $sample[0] . ' is NOT less than ' . $sample[1]; } - } - - function testOfExactly() - { - $pool = array( - array( - 1, - '1', - true - ), - array( - 1, - 1.0, - true - ), - array( - 1, - 01, - true - ), - array( - 1, - 'a', - false - ) - ); - foreach ($pool as $sample) { - if ($sample[2]) { - $message = $sample[0] . ' is exactly ' . $sample[1]; - } else { - $message = $sample[0] . ' is NOT exactly ' . $sample[1]; - } - $this->assertSame(Helper::exactly($sample[0], $sample[1]), $sample[2], $message); + expect($sample[2])->toBe(Helper::greaterThan($sample[0], $sample[1]), $message); + } +}); + +test('between', function () { + $pool = array( + array( + 1, + 0.5, + 0.8, + false + ), + array( + 1, + 0.9, + 1.2, + true + ) + ); + foreach ($pool as $sample) { + if ($sample[2]) { + $message = $sample[0] . ' is between ' . $sample[1] . ' and ' . $sample[2]; + } else { + $message = $sample[0] . ' is NOT between ' . $sample[1] . ' and ' . $sample[2]; } - } - - function testOfNot() - { - $pool = array( - array( - 1, - '1', - false - ), - array( - 1, - 1.0, - false - ), - array( - 1, - 01, - false - ), - array( - 1, - 'a', - true - ) - ); - foreach ($pool as $sample) { - if ($sample[2]) { - $message = $sample[0] . ' is not ' . $sample[1]; - } else { - $message = $sample[0] . ' is ' . $sample[1]; - } - $this->assertSame(Helper::not($sample[0], $sample[1]), $sample[2], $message); + expect($sample[3])->toBe(Helper::between($sample[0], $sample[1], $sample[2]), $message); + } +}); + +test('exactly', function () { + $pool = array( + array( + 1, + '1', + true + ), + array( + 1, + 1.0, + true + ), + array( + 1, + 01, + true + ), + array( + 1, + 'a', + false + ) + ); + foreach ($pool as $sample) { + if ($sample[2]) { + $message = $sample[0] . ' is exactly ' . $sample[1]; + } else { + $message = $sample[0] . ' is NOT exactly ' . $sample[1]; } - } - - function testOfAlpha() - { - $pool = array( - 'Some Random String ' => true, - '123' => false, - 'With other chars :' => false - ); - foreach ($pool as $key => $value) { - if ($value) { - $message = $key . ' is a alphabetic'; - } else { - $message = $key . ' is NOT a alphabetic'; - } - $this->assertSame(Helper::alpha($key), $value, $message); + expect($sample[2])->toBe(Helper::exactly($sample[0], $sample[1]), $message); + } +}); + +test('not', function () { + $pool = array( + array( + 1, + '1', + false + ), + array( + 1, + 1.0, + false + ), + array( + 1, + 01, + false + ), + array( + 1, + 'a', + true + ) + ); + foreach ($pool as $sample) { + if ($sample[2]) { + $message = $sample[0] . ' is not ' . $sample[1]; + } else { + $message = $sample[0] . ' is ' . $sample[1]; } - } - - function testOfAlphanumeric() - { - $pool = array( - 'Some Random String ' => true, - 'Letters and 123' => true, - 'With other chars :' => false - ); - foreach ($pool as $key => $value) { - if ($value) { - $message = $key . ' is a alphanumeric'; - } else { - $message = $key . ' is NOT a alphanumeric'; - } - $this->assertSame(Helper::alphanumeric($key), $value, $message); + expect($sample[2])->toBe(Helper::not($sample[0], $sample[1]), $message); + } +}); + +test('alpha', function () { + $pool = array( + 'Some Random String ' => true, + '123' => false, + 'With other chars :' => false + ); + foreach ($pool as $key => $value) { + if ($value) { + $message = $key . ' is a alphabetic'; + } else { + $message = $key . ' is NOT a alphabetic'; } - } - - function testOfAlphanumhyphen() - { - $pool = array( - 'Some Random String ' => true, - 'Letters and 123' => true, - 'With other hyphens _ -' => true, - '? - this is not acceptable' => false - ); - foreach ($pool as $key => $value) { - if ($value) { - $message = $key . ' is a alphanumhyphen'; - } else { - $message = $key . ' is NOT a alphanumhyphen'; - } - $this->assertSame(Helper::alphanumhyphen($key), $value, $message); + expect($value)->toBe(Helper::alpha($key), $message); + } +}); + +test('alphanumeric', function () { + $pool = array( + 'Some Random String ' => true, + 'Letters and 123' => true, + 'With other chars :' => false + ); + foreach ($pool as $key => $value) { + if ($value) { + $message = $key . ' is a alphanumeric'; + } else { + $message = $key . ' is NOT a alphanumeric'; } - } - - function testOfLength() - { - $this->assertTrue(Helper::length('abc', 1, 5)); - } - - function testOfMinLength() - { - $pool = array( - array( - 'abcde', - 7, - false - ), - array( - 'abcde', - 4, - true - ) - ); - foreach ($pool as $sample) { - if ($sample[2]) { - $message = $sample[0] . ' has more than ' . $sample[1] . ' characters'; - } else { - $message = $sample[0] . ' does NOT have more than ' . $sample[1] . ' characters'; - } - $this->assertSame(Helper::minLength($sample[0], $sample[1]), $sample[2], $message); + expect($value)->toBe(Helper::alphanumeric($key), $message); + } +}); + +test('alphanumhyphen', function () { + $pool = array( + 'Some Random String ' => true, + 'Letters and 123' => true, + 'With other hyphens _ -' => true, + '? - this is not acceptable' => false + ); + foreach ($pool as $key => $value) { + if ($value) { + $message = $key . ' is a alphanumhyphen'; + } else { + $message = $key . ' is NOT a alphanumhyphen'; } - } - - function testOfMaxLength() - { - $pool = array( - array( - 'abcde', - 4, - false - ), - array( - 'abcde', - 6, - true - ) - ); - foreach ($pool as $sample) { - if ($sample[2]) { - $message = $sample[0] . ' has less than ' . $sample[1] . ' characters'; - } else { - $message = $sample[0] . ' does NOT have less than ' . $sample[1] . ' characters'; - } - $this->assertSame(Helper::maxLength($sample[0], $sample[1]), $sample[2], $message); + expect($value)->toBe(Helper::alphanumhyphen($key), $message); + } +}); + +test('length', function () { + expect(Helper::length('abc', 1, 5))->toBeTrue(); +}); + +test('min length', function () { + $pool = array( + array( + 'abcde', + 7, + false + ), + array( + 'abcde', + 4, + true + ) + ); + foreach ($pool as $sample) { + if ($sample[2]) { + $message = $sample[0] . ' has more than ' . $sample[1] . ' characters'; + } else { + $message = $sample[0] . ' does NOT have more than ' . $sample[1] . ' characters'; } - } - - function testOfIn() - { - $pool = array( - array( - '6', - array( - '5', - '8' - ), - false - ), - array( - '5', - array( - '5', - '8' - ), - true - ) - ); - foreach ($pool as $sample) { - $this->assertSame(Helper::inList($sample[0], $sample[1]), $sample[2]); + expect($sample[2])->toBe(Helper::minLength($sample[0], $sample[1]), $message); + } +}); + +test('max length', function () { + $pool = array( + array( + 'abcde', + 4, + false + ), + array( + 'abcde', + 6, + true + ) + ); + foreach ($pool as $sample) { + if ($sample[2]) { + $message = $sample[0] . ' has less than ' . $sample[1] . ' characters'; + } else { + $message = $sample[0] . ' does NOT have less than ' . $sample[1] . ' characters'; } + expect($sample[2])->toBe(Helper::maxLength($sample[0], $sample[1]), $message); } +}); - function testOfNotIn() - { - $pool = array( +test('in', function () { + $pool = array( + array( + '6', array( '5', - array( - '5', - '8' - ), - false - ), - array( - '6', - array( - '5', - '8' - ), - true - ) - ); - foreach ($pool as $sample) { - $this->assertSame(Helper::notInList($sample[0], $sample[1]), $sample[2]); - } - } - - function testOfRegex() - { - $pool = array( - array( - 'abc', - '/[0-9]+/', - false - ), - array( - '123', - '/[0-9]+/', - true - ) - ); - foreach ($pool as $sample) { - $this->assertSame(Helper::regex($sample[0], $sample[1]), $sample[2]); - } - } - - function testOfNotRegex() - { - $pool = array( - array( - 'abc', - '/[0-9]+/', - true - ), - array( - '123', - '/[0-9]+/', - false - ) - ); - foreach ($pool as $sample) { - $this->assertSame(Helper::notRegex($sample[0], $sample[1]), $sample[2]); - } - } - - function testOfEqualToWithContext() - { - $pool = array( - array( - 'value', - 'element_1', - true - ), - array( - 'value', - 'element_2', - false - ), - array( - 'new value', - 'element_3[sub_element_1][sub_element_2]', - true - ) - ); - $context = array( - 'element_1' => 'value', - 'element_2' => 'another_value', - 'element_3' => array( - 'sub_element_1' => array( - 'sub_element_2' => 'new value' - ) - ) - ); - foreach ($pool as $sample) { - $this->assertSame( - Helper::equalTo($sample[0], $sample[1], $context), - $sample[2], - sprintf("%s %s", $sample[0], $sample[1]) - ); - } - } - - function testOfNotEqualToWithContext() - { - $pool = array( - array( - 'value', - 'element_1', - false - ), - array( - 'value', - 'element_2', - true - ), - array( - 'new value', - 'element_3[sub_element_1][sub_element_2]', - false - ) - ); - $context = array( - 'element_1' => 'value', - 'element_2' => 'another_value', - 'element_3' => array( - 'sub_element_1' => array( - 'sub_element_2' => 'new value' - ) - ) - ); - foreach ($pool as $sample) { - $this->assertSame( - Helper::notEqualTo($sample[0], $sample[1], $context), - $sample[2], - sprintf("%s %s", $sample[0], $sample[1]) - ); - } - } - - function testOfEqualToWithoutContext() - { - $this->assertTrue(Helper::equalTo(5, '5')); - $this->assertFalse(Helper::equalTo(5, 'a')); - } - - function testOfNotEqualToWithoutContext() - { - $this->assertTrue(Helper::NotEqualTo(5, 'a')); - $this->assertFalse(Helper::NotEqualTo(5, '5')); - } - - function testOfWebsite() - { - $pool = array( - array( - 'https://www.domain.co.uk/', - true - ), - array( - 'https://www.domain.co.uk/folder/page.html?var=value#!fragment', - true - ), - array( - '123', - false - ) - ); - foreach ($pool as $sample) { - $this->assertSame(Helper::website($sample[0]), $sample[1]); - } - } - - function testOfUrl() - { - $pool = array( - array( - 'ftp://ftp.domain.co.uk/', - true - ), - array( - 'ftp://username:password@domain.co.uk/folder/', - true - ), - array( - '123', - false - ) - ); - foreach ($pool as $sample) { - $this->assertSame(Helper::url($sample[0]), $sample[1]); - } - } - - function testOfIp() - { - $pool = array( - array( - '196.168.100.1', - true - ), - array( - '256.576a.53.21', - false + '8' ), + false + ), + array( + '5', array( - '2002:51c4:7c3c:0000:0000:0000:0000:0000', - true - ) //IPv6 - ); - - foreach ($pool as $sample) { - $this->assertSame(Helper::ipAddress($sample[0]), $sample[1], $sample[0]); - } - } - - function testOfSetMaxSize() - { - $set = array( - 'element_1' => 'value', - 'element_2' => 'another_value', - 'element_3' => array( - 'sub_element_1' => 'new value' - ) - ); - $pool = array( - array( - '4', - true + '5', + '8' ), - array( - '2', - false - ) - ); - foreach ($pool as $sample) { - $this->assertSame(Helper::setMaxSize($set, $sample[0]), $sample[1]); - } + true + ) + ); + foreach ($pool as $sample) { + expect($sample[2])->toBe(Helper::inList($sample[0], $sample[1])); } +}); - function testOfSetMinSize() - { - $set = array( - 'element_1' => 'value', - 'element_2' => 'another_value', - 'element_3' => array( - 'sub_element_1' => 'new value' - ) - ); - $pool = array( +test('not in', function () { + $pool = array( + array( + '5', array( - '4', - false + '5', + '8' ), + false + ), + array( + '6', array( - '2', - true - ) - ); - foreach ($pool as $sample) { - $this->assertSame(Helper::setMinSize($set, $sample[0]), $sample[1]); - } - } - - function testOfSetSize() - { - $set = array( - 'element_1' => 'value', - 'element_2' => 'another_value', - 'element_3' => array( - 'sub_element_1' => 'new value' - ) - ); - $pool = array( - array( - 2, - 5, - true + '5', + '8' ), - array( - 6, - 8, - false + true + ) + ); + foreach ($pool as $sample) { + expect($sample[2])->toBe(Helper::notInList($sample[0], $sample[1])); + } +}); + +test('regex', function () { + $pool = array( + array( + 'abc', + '/[0-9]+/', + false + ), + array( + '123', + '/[0-9]+/', + true + ) + ); + foreach ($pool as $sample) { + expect($sample[2])->toBe(Helper::regex($sample[0], $sample[1])); + } +}); + +test('not regex', function () { + $pool = array( + array( + 'abc', + '/[0-9]+/', + true + ), + array( + '123', + '/[0-9]+/', + false + ) + ); + foreach ($pool as $sample) { + expect($sample[2])->toBe(Helper::notRegex($sample[0], $sample[1])); + } +}); + +test('equal to with context', function () { + $pool = array( + array( + 'value', + 'element_1', + true + ), + array( + 'value', + 'element_2', + false + ), + array( + 'new value', + 'element_3[sub_element_1][sub_element_2]', + true + ) + ); + $context = array( + 'element_1' => 'value', + 'element_2' => 'another_value', + 'element_3' => array( + 'sub_element_1' => array( + 'sub_element_2' => 'new value' ) - ); - foreach ($pool as $sample) { - $this->assertSame(Helper::setSize($set, $sample[0], $sample[1]), $sample[2]); - } - } - - function validationCallback($value, $options = false, $context = null) - { - return ($value == 5 and $options = 3 and $context == null); - } - - function testOfValidAddMethodCalls() - { - Helper::addMethod( - 'myValidation', - array( - $this, - 'validationCallback' + ) + ); + foreach ($pool as $sample) { + expect($sample[2])->toBe(Helper::equalTo($sample[0], $sample[1], $context), sprintf("%s %s", $sample[0], $sample[1])); + } +}); + +test('not equal to with context', function () { + $pool = array( + array( + 'value', + 'element_1', + false + ), + array( + 'value', + 'element_2', + true + ), + array( + 'new value', + 'element_3[sub_element_1][sub_element_2]', + false + ) + ); + $context = array( + 'element_1' => 'value', + 'element_2' => 'another_value', + 'element_3' => array( + 'sub_element_1' => array( + 'sub_element_2' => 'new value' ) - ); - $this->assertTrue(Helper::myValidation(5, 3)); - $this->assertFalse(Helper::myValidation(5, 3, 3)); - } - - function testOfInvalidAddMethodCalls() - { - $this->expectException('InvalidArgumentException'); - Helper::addMethod('mySecondValidation', 'nonexistantcallback'); - $this->assertTrue(Helper::mySecondValidation(5)); - } - - function testOfFullName() - { - $this->assertTrue(Helper::fullName('First Last')); - $this->assertFalse(Helper::fullName('F Last')); - $this->assertFalse(Helper::fullName('First L')); - $this->assertFalse(Helper::fullName('Fi La')); - } - - function testOfEmailDomain() - { - $this->assertTrue(Helper::emailDomain('me@hotmail.com')); - $this->assertFalse(Helper::emailDomain('me@hotmail.com.not.valid')); - } - - function testOfDate() - { - $this->assertTrue(Helper::date('2012-07-13', 'Y-m-d')); - $this->assertFalse(Helper::date('2012-07-13', 'Y/m/d')); - } - - function testOfDateTime() - { - $this->assertTrue(Helper::dateTime('2012-07-13 20:00:15', 'Y-m-d H:i:s')); - $this->assertFalse(Helper::dateTime('2012-07-13')); - } - - function testOfTime() - { - $this->assertTrue(Helper::time('20:00:15', 'H:i:s')); - $this->assertFalse(Helper::time('20:00:99')); - } - + ) + ); + foreach ($pool as $sample) { + expect($sample[2])->toBe(Helper::notEqualTo($sample[0], $sample[1], $context), sprintf("%s %s", $sample[0], $sample[1])); + } +}); + +test('equal to without context', function () { + expect(Helper::equalTo(5, '5'))->toBeTrue(); + expect(Helper::equalTo(5, 'a'))->toBeFalse(); +}); + +test('not equal to without context', function () { + expect(Helper::NotEqualTo(5, 'a'))->toBeTrue(); + expect(Helper::NotEqualTo(5, '5'))->toBeFalse(); +}); + +test('website', function () { + $pool = array( + array( + 'https://www.domain.co.uk/', + true + ), + array( + 'https://www.domain.co.uk/folder/page.html?var=value#!fragment', + true + ), + array( + '123', + false + ) + ); + foreach ($pool as $sample) { + expect($sample[1])->toBe(Helper::website($sample[0])); + } +}); + +test('url', function () { + $pool = array( + array( + 'ftp://ftp.domain.co.uk/', + true + ), + array( + 'ftp://username:password@domain.co.uk/folder/', + true + ), + array( + '123', + false + ) + ); + foreach ($pool as $sample) { + expect($sample[1])->toBe(Helper::url($sample[0])); + } +}); + +test('ip', function () { + $pool = array( + array( + '196.168.100.1', + true + ), + array( + '256.576a.53.21', + false + ), + array( + '2002:51c4:7c3c:0000:0000:0000:0000:0000', + true + ) //IPv6 + ); + + foreach ($pool as $sample) { + expect($sample[1])->toBe(Helper::ipAddress($sample[0]), $sample[0]); + } +}); + +test('set max size', function () { + $set = array( + 'element_1' => 'value', + 'element_2' => 'another_value', + 'element_3' => array( + 'sub_element_1' => 'new value' + ) + ); + $pool = array( + array( + '4', + true + ), + array( + '2', + false + ) + ); + foreach ($pool as $sample) { + expect($sample[1])->toBe(Helper::setMaxSize($set, $sample[0])); + } +}); + +test('set min size', function () { + $set = array( + 'element_1' => 'value', + 'element_2' => 'another_value', + 'element_3' => array( + 'sub_element_1' => 'new value' + ) + ); + $pool = array( + array( + '4', + false + ), + array( + '2', + true + ) + ); + foreach ($pool as $sample) { + expect($sample[1])->toBe(Helper::setMinSize($set, $sample[0])); + } +}); + +test('set size', function () { + $set = array( + 'element_1' => 'value', + 'element_2' => 'another_value', + 'element_3' => array( + 'sub_element_1' => 'new value' + ) + ); + $pool = array( + array( + 2, + 5, + true + ), + array( + 6, + 8, + false + ) + ); + foreach ($pool as $sample) { + expect($sample[2])->toBe(Helper::setSize($set, $sample[0], $sample[1])); + } +}); + +function validationCallback($value, $options = false, $context = null) +{ + return ($value == 5 and $options = 3 and $context == null); } + +test('valid add method calls', function () { + Helper::addMethod( + 'myValidation', + 'validationCallback' + ); + expect(Helper::myValidation(5, 3))->toBeTrue(); + expect(Helper::myValidation(5, 3, 3))->toBeFalse(); +}); + +test('invalid add method calls', function () { + $this->expectException('InvalidArgumentException'); + Helper::addMethod('mySecondValidation', 'nonexistantcallback'); + expect(Helper::mySecondValidation(5))->toBeTrue(); +}); + +test('full name', function () { + expect(Helper::fullName('First Last'))->toBeTrue(); + expect(Helper::fullName('F Last'))->toBeFalse(); + expect(Helper::fullName('First L'))->toBeFalse(); + expect(Helper::fullName('Fi La'))->toBeFalse(); +}); + +test('email domain', function () { + expect(Helper::emailDomain('me@hotmail.com'))->toBeTrue(); + expect(Helper::emailDomain('me@hotmail.com.not.valid'))->toBeFalse(); +}); + +test('date', function () { + expect(Helper::date('2012-07-13', 'Y-m-d'))->toBeTrue(); + expect(Helper::date('2012-07-13', 'Y/m/d'))->toBeFalse(); +}); + +test('date time', function () { + expect(Helper::dateTime('2012-07-13 20:00:15', 'Y-m-d H:i:s'))->toBeTrue(); + expect(Helper::dateTime('2012-07-13'))->toBeFalse(); +}); + +test('time', function () { + expect(Helper::time('20:00:15', 'H:i:s'))->toBeTrue(); + expect(Helper::time('20:00:99'))->toBeFalse(); +}); diff --git a/tests/src/Rule/AbstractValidatorTest.php b/tests/src/Rule/AbstractValidatorTest.php index 1ce8368..4d84398 100755 --- a/tests/src/Rule/AbstractValidatorTest.php +++ b/tests/src/Rule/AbstractValidatorTest.php @@ -1,75 +1,61 @@ value = $value; - $this->success = (bool) $value && isset($this->context) && $this->context->getItemValue('key'); + $this->value = $value; + $this->success = (bool)$value && isset($this->context) && $this->context->getItemValue('key'); return $this->success; } } - -class AbstractRuleTest extends \PHPUnit\Framework\TestCase -{ - - protected function setUp(): void - { - $this->rule = new FakeRule(); - } - - function testErrorMessagePrototype() - { - // we always have an error message prototype - $this->assertTrue($this->rule->getErrorMessagePrototype() instanceof \Sirius\Validation\ErrorMessage); - $proto = new \Sirius\Validation\ErrorMessage('Not valid'); - $this->rule->setErrorMessagePrototype($proto); - $this->assertEquals('Not valid', (string) $this->rule->getErrorMessagePrototype()); - } - - function testMessageIsGeneratedCorrectly() - { - $this->rule->setOption('label', 'Accept'); - $this->rule->setMessageTemplate('Field "{label}" must be true, {value} was provided'); - $this->rule->validate('false'); - $this->assertEquals('Field "Accept" must be true, false was provided', (string) $this->rule->getMessage()); - } - - function testNoMessageWhenValidationPasses() - { - $this->rule->setContext(array( 'key' => true )); - $this->assertTrue($this->rule->validate(true)); - $this->assertNull($this->rule->getMessage()); - } - - function testContext() - { - $this->assertFalse($this->rule->validate(true)); - $this->rule->setContext(array( 'key' => true )); - $this->assertTrue($this->rule->validate(true)); - } - - function testErrorMessageTemplateIsUsed() - { - $this->rule->setMessageTemplate('Custom message'); - $this->assertEquals('Custom message', (string) $this->rule->getPotentialMessage()); - } - - function testErrorThrownOnInvalidContext() - { - $this->expectException('\InvalidArgumentException'); - $this->rule->setContext(new \stdClass()); - } - - function testGetOption() - { - $this->rule->setOption('label', 'Accept'); - $this->assertEquals('Accept', $this->rule->getOption('label')); - $this->assertNull($this->rule->getOption('notExist')); - } -} +beforeEach(function () { + $this->rule = new FakeRule(); +}); + +test('error message prototype', function () { + // we always have an error message prototype + expect($this->rule->getErrorMessagePrototype())->toBeInstanceOf(ErrorMessage::class); + $proto = new ErrorMessage('Not valid'); + $this->rule->setErrorMessagePrototype($proto); + expect((string) $this->rule->getErrorMessagePrototype())->toEqual('Not valid'); +}); + +test('message is generated correctly', function () { + $this->rule->setOption('label', 'Accept'); + $this->rule->setMessageTemplate('Field "{label}" must be true, {value} was provided'); + $this->rule->validate('false'); + expect((string) $this->rule->getMessage())->toEqual('Field "Accept" must be true, false was provided'); +}); + +test('no message when validation passes', function () { + $this->rule->setContext(array( 'key' => true )); + expect($this->rule->validate(true))->toBeTrue(); + expect($this->rule->getMessage())->toBeNull(); +}); + +test('context', function () { + expect($this->rule->validate(true))->toBeFalse(); + $this->rule->setContext(array( 'key' => true )); + expect($this->rule->validate(true))->toBeTrue(); +}); + +test('error message template is used', function () { + $this->rule->setMessageTemplate('Custom message'); + expect((string) $this->rule->getPotentialMessage())->toEqual('Custom message'); +}); + +test('error thrown on invalid context', function () { + $this->expectException('\InvalidArgumentException'); + $this->rule->setContext(new \stdClass()); +}); + +test('get option', function () { + $this->rule->setOption('label', 'Accept'); + expect($this->rule->getOption('label'))->toEqual('Accept'); + expect($this->rule->getOption('notExist'))->toBeNull(); +}); diff --git a/tests/src/Rule/ArrayMaxLengthTest.php b/tests/src/Rule/ArrayMaxLengthTest.php index bf7e967..12870c7 100755 --- a/tests/src/Rule/ArrayMaxLengthTest.php +++ b/tests/src/Rule/ArrayMaxLengthTest.php @@ -1,19 +1,12 @@ rule = new Rule(); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidationWithoutALimit() - { - $this->assertTrue($this->rule->validate(array())); - } -} +test('validation without a limit', function () { + expect($this->rule->validate(array()))->toBeTrue(); +}); diff --git a/tests/src/Rule/ArrayMinLengthTest.php b/tests/src/Rule/ArrayMinLengthTest.php index 9b3048e..3243a31 100755 --- a/tests/src/Rule/ArrayMinLengthTest.php +++ b/tests/src/Rule/ArrayMinLengthTest.php @@ -1,19 +1,12 @@ rule = new Rule(); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidationWithoutALimit() - { - $this->assertTrue($this->rule->validate(array())); - } -} +test('validation without a limit', function () { + expect($this->rule->validate(array()))->toBeTrue(); +}); diff --git a/tests/src/Rule/BetweenTest.php b/tests/src/Rule/BetweenTest.php index 47e38b4..d546a98 100644 --- a/tests/src/Rule/BetweenTest.php +++ b/tests/src/Rule/BetweenTest.php @@ -1,24 +1,16 @@ rule = new Rule(); - } - function testValidation() - { - $this->rule->setOption('min', 50); - $this->rule->setOption('max', 100); - $this->assertFalse($this->rule->validate(40)); - $this->assertFalse($this->rule->validate(110)); - $this->assertTrue($this->rule->validate(80)); - } +beforeEach(function () { + $this->rule = new Rule(); +}); -} +test('validation', function () { + $this->rule->setOption('min', 50); + $this->rule->setOption('max', 100); + expect($this->rule->validate(40))->toBeFalse(); + expect($this->rule->validate(110))->toBeFalse(); + expect($this->rule->validate(80))->toBeTrue(); +}); diff --git a/tests/src/Rule/CallbackTest.php b/tests/src/Rule/CallbackTest.php index 58af382..732b2d4 100644 --- a/tests/src/Rule/CallbackTest.php +++ b/tests/src/Rule/CallbackTest.php @@ -1,58 +1,47 @@ rule = new Rule(); - } - - function testValidationWithoutAValidCallback() - { - $this->rule->setOption(Rule::OPTION_CALLBACK, 'ssss'); - $this->assertTrue($this->rule->validate('abc')); - } - - function testGetUniqueIdForCallbacksAsStrings() - { - $this->rule->setOption(Rule::OPTION_CALLBACK, 'is_int'); - $this->assertTrue(strpos($this->rule->getUniqueId(), '|is_int') !== false); - - $this->rule->setOption(Rule::OPTION_CALLBACK, 'Class::method'); - $this->assertTrue(strpos($this->rule->getUniqueId(), '|Class::method') !== false); - } - - function testGetUniqueIdForCallbacksAsArrays() - { - $this->rule->setOption(Rule::OPTION_CALLBACK, array( 'Class', 'method' )); - $this->assertTrue(strpos($this->rule->getUniqueId(), '|Class::method') !== false); - - $this->rule->setOption(Rule::OPTION_CALLBACK, array( $this, 'setUp' )); - $this->assertTrue(strpos($this->rule->getUniqueId(), '->setUp') !== false); - } - - function testGetUniqueIdForCallbacksWithArguments() - { - $this->rule->setOption(Rule::OPTION_CALLBACK, 'is_int'); - $this->rule->setOption(Rule::OPTION_ARGUMENTS, array( 'b' => 2, 'a' => 1 )); - - // arguments should be sorted by key so test for that too - $this->assertTrue(strpos($this->rule->getUniqueId(), '|{"a":1,"b":2}') !== false); - } - - function testGetUniqueIdForClosures() - { - $this->rule->setOption( - Rule::OPTION_CALLBACK, - function ($value, $valueIdentifier) { - return true; - } - ); - $this->assertNotNull($this->rule->getUniqueId()); - } -} + +beforeEach(function () { + $this->rule = new Rule(); +}); + +test('validation without a valid callback', function () { + $this->rule->setOption(Rule::OPTION_CALLBACK, 'ssss'); + expect($this->rule->validate('abc'))->toBeTrue(); +}); + +test('get unique id for callbacks as strings', function () { + $this->rule->setOption(Rule::OPTION_CALLBACK, 'is_int'); + expect(strpos($this->rule->getUniqueId(), '|is_int') !== false)->toBeTrue(); + + $this->rule->setOption(Rule::OPTION_CALLBACK, 'Class::method'); + expect(strpos($this->rule->getUniqueId(), '|Class::method') !== false)->toBeTrue(); +}); + +test('get unique id for callbacks as arrays', function () { + $this->rule->setOption(Rule::OPTION_CALLBACK, array( 'Class', 'method' )); + expect(strpos($this->rule->getUniqueId(), '|Class::method') !== false)->toBeTrue(); + + $this->rule->setOption(Rule::OPTION_CALLBACK, array( $this, 'setUp' )); + expect(strpos($this->rule->getUniqueId(), '->setUp') !== false)->toBeTrue(); +}); + +test('get unique id for callbacks with arguments', function () { + $this->rule->setOption(Rule::OPTION_CALLBACK, 'is_int'); + $this->rule->setOption(Rule::OPTION_ARGUMENTS, array( 'b' => 2, 'a' => 1 )); + + // arguments should be sorted by key so test for that too + expect(strpos($this->rule->getUniqueId(), '|{"a":1,"b":2}') !== false)->toBeTrue(); +}); + +test('get unique id for closures', function () { + $this->rule->setOption( + Rule::OPTION_CALLBACK, + function ($value, $valueIdentifier) { + return true; + } + ); + expect($this->rule->getUniqueId())->not->toBeNull(); +}); diff --git a/tests/src/Rule/EmailTest.php b/tests/src/Rule/EmailTest.php index db3b686..2f8d88d 100644 --- a/tests/src/Rule/EmailTest.php +++ b/tests/src/Rule/EmailTest.php @@ -1,21 +1,13 @@ rule = new Rule(); - } - function testValidation() - { - $this->assertFalse($this->rule->validate('')); - $this->assertTrue($this->rule->validate('me@domain.com')); - } +beforeEach(function () { + $this->rule = new Rule(); +}); -} +test('validation', function () { + expect($this->rule->validate(''))->toBeFalse(); + expect($this->rule->validate('me@domain.com'))->toBeTrue(); +}); diff --git a/tests/src/Rule/EqualTest.php b/tests/src/Rule/EqualTest.php index 82fd389..1322299 100644 --- a/tests/src/Rule/EqualTest.php +++ b/tests/src/Rule/EqualTest.php @@ -1,28 +1,19 @@ rule = new Rule(); - } - function testValidationWithOptionSet() - { - $this->rule->setOption(Rule::OPTION_VALUE, '123'); - $this->assertTrue($this->rule->validate('123')); - $this->assertFalse($this->rule->validate('abc')); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidationWithoutOptionSet() - { - $this->assertTrue($this->rule->validate('abc')); - $this->assertTrue($this->rule->validate(null)); - } +test('validation with option set', function () { + $this->rule->setOption(Rule::OPTION_VALUE, '123'); + expect($this->rule->validate('123'))->toBeTrue(); + expect($this->rule->validate('abc'))->toBeFalse(); +}); -} +test('validation without option set', function () { + expect($this->rule->validate('abc'))->toBeTrue(); + expect($this->rule->validate(null))->toBeTrue(); +}); diff --git a/tests/src/Rule/File/ExtensionTest.php b/tests/src/Rule/File/ExtensionTest.php index 0b3eec7..8f3556a 100644 --- a/tests/src/Rule/File/ExtensionTest.php +++ b/tests/src/Rule/File/ExtensionTest.php @@ -1,43 +1,31 @@ validator = new Extension(); +}); - protected function setUp(): void - { - $this->validator = new Extension(); - } +test('existing files', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; + expect($this->validator->validate($file))->toBeTrue(); +}); - function testExistingFiles() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; - $this->assertTrue($this->validator->validate($file)); - } +test('missing files', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; + expect($this->validator->validate($file))->toBeFalse(); +}); - function testMissingFiles() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; - $this->assertFalse($this->validator->validate($file)); - } +test('set option as string', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, 'jpg, GIF'); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; + expect($this->validator->validate($file))->toBeTrue(); +}); - function testSetOptionAsString() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, 'jpg, GIF'); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; - $this->assertTrue($this->validator->validate($file)); - } - - function testPotentialMessage() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); - $this->validator->validate('no_file.jpg'); - $this->assertEquals( - 'The file does not have an acceptable extension (JPG, PNG)', - (string) $this->validator->getPotentialMessage() - ); - } -} +test('potential message', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); + $this->validator->validate('no_file.jpg'); + expect((string) $this->validator->getPotentialMessage())->toEqual('The file does not have an acceptable extension (JPG, PNG)'); +}); diff --git a/tests/src/Rule/File/ImageHeightTest.php b/tests/src/Rule/File/ImageHeightTest.php index 31ea2c6..d402859 100644 --- a/tests/src/Rule/File/ImageHeightTest.php +++ b/tests/src/Rule/File/ImageHeightTest.php @@ -1,32 +1,24 @@ validator = new ImageHeight(array( 'min' => 400 )); +}); - protected function setUp(): void - { - $this->validator = new ImageHeight(array( 'min' => 400 )); - } +test('missing files', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; + expect($this->validator->validate($file))->toBeFalse(); +}); - function testMissingFiles() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; - $this->assertFalse($this->validator->validate($file)); - } +test('file', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; + expect($this->validator->validate($file))->toBeTrue(); - function testFile() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; - $this->assertTrue($this->validator->validate($file)); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'square_image.gif'; + expect($this->validator->validate($file))->toBeFalse(); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'square_image.gif'; - $this->assertFalse($this->validator->validate($file)); - - // change minimum - $this->validator->setOption(ImageHeight::OPTION_MIN, 200); - $this->assertTrue($this->validator->validate($file)); - } - -} + // change minimum + $this->validator->setOption(ImageHeight::OPTION_MIN, 200); + expect($this->validator->validate($file))->toBeTrue(); +}); diff --git a/tests/src/Rule/File/ImageRatioTest.php b/tests/src/Rule/File/ImageRatioTest.php index db08e17..4e1da1a 100644 --- a/tests/src/Rule/File/ImageRatioTest.php +++ b/tests/src/Rule/File/ImageRatioTest.php @@ -1,63 +1,50 @@ validator = new ImageRatio(array( 'ratio' => 1 )); - } - - function testMissingFiles() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; - $this->assertFalse($this->validator->validate($file)); - } - - function testSquare() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'square_image.gif'; - $this->assertTrue($this->validator->validate($file)); - } - - function testAlmostSquare() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'almost_square_image.gif'; - $this->assertFalse($this->validator->validate($file)); - - // change the error margin - $this->validator->setOption(ImageRatio::OPTION_ERROR_MARGIN, 0.2); - $this->assertTrue($this->validator->validate($file)); - } - - function testRatioZero() - { - $this->validator->setOption(ImageRatio::OPTION_RATIO, 0); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'almost_square_image.gif'; - $this->assertTrue($this->validator->validate($file)); - } - - function testInvalidRatio() - { - $this->validator->setOption(ImageRatio::OPTION_RATIO, 'abc'); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'almost_square_image.gif'; - $this->assertTrue($this->validator->validate($file)); - } - - function testRatioAsString() - { - $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . '4_by_3_image.jpg'; - $this->assertTrue($this->validator->validate($file)); - } - - function testFileNotAnImage() - { - $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'corrupt_image.jpg'; - $this->assertFalse($this->validator->validate($file)); - } - -} +use \Sirius\Validation\Rule\File\ImageRatio; + +beforeEach(function () { + $this->validator = new ImageRatio(array( 'ratio' => 1 )); +}); + +test('missing files', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; + expect($this->validator->validate($file))->toBeFalse(); +}); + +test('square', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'square_image.gif'; + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('almost square', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'almost_square_image.gif'; + expect($this->validator->validate($file))->toBeFalse(); + + // change the error margin + $this->validator->setOption(ImageRatio::OPTION_ERROR_MARGIN, 0.2); + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('ratio zero', function () { + $this->validator->setOption(ImageRatio::OPTION_RATIO, 0); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'almost_square_image.gif'; + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('invalid ratio', function () { + $this->validator->setOption(ImageRatio::OPTION_RATIO, 'abc'); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'almost_square_image.gif'; + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('ratio as string', function () { + $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . '4_by_3_image.jpg'; + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('file not an image', function () { + $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'corrupt_image.jpg'; + expect($this->validator->validate($file))->toBeFalse(); +}); diff --git a/tests/src/Rule/File/ImageTest.php b/tests/src/Rule/File/ImageTest.php index 02d1817..c754496 100644 --- a/tests/src/Rule/File/ImageTest.php +++ b/tests/src/Rule/File/ImageTest.php @@ -1,49 +1,37 @@ validator = new Image(); - } - - function testMissingFiles() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; - $this->assertFalse($this->validator->validate($file)); - } - - function testRealImage() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; - $this->assertTrue($this->validator->validate($file)); - } - - function testFakeImage() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'fake_jpeg_file.jpg'; - $this->assertFalse($this->validator->validate($file)); - } - - function testExtensionsAsString() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, 'GIF, jpg'); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; - $this->assertTrue($this->validator->validate($file)); - } - - function testPotentialMessage() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); - $this->validator->validate('no_file.jpg'); - $this->assertEquals( - 'The file is not a valid image (only JPG, PNG are allowed)', - (string) $this->validator->getPotentialMessage() - ); - } -} +use \Sirius\Validation\Rule\File\Extension; +use \Sirius\Validation\Rule\File\Image; + +beforeEach(function () { + $this->validator = new Image(); +}); + +test('missing files', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; + expect($this->validator->validate($file))->toBeFalse(); +}); + +test('real image', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('fake image', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'fake_jpeg_file.jpg'; + expect($this->validator->validate($file))->toBeFalse(); +}); + +test('extensions as string', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, 'GIF, jpg'); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('potential message', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); + $this->validator->validate('no_file.jpg'); + expect((string) $this->validator->getPotentialMessage())->toEqual('The file is not a valid image (only JPG, PNG are allowed)'); +}); diff --git a/tests/src/Rule/File/ImageWidthTest.php b/tests/src/Rule/File/ImageWidthTest.php index 800af11..5c8fd11 100644 --- a/tests/src/Rule/File/ImageWidthTest.php +++ b/tests/src/Rule/File/ImageWidthTest.php @@ -1,32 +1,24 @@ validator = new ImageWidth(array( 'min' => 500 )); +}); - protected function setUp(): void - { - $this->validator = new ImageWidth(array( 'min' => 500 )); - } +test('missing files', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; + expect($this->validator->validate($file))->toBeFalse(); +}); - function testMissingFiles() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; - $this->assertFalse($this->validator->validate($file)); - } +test('file', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; + expect($this->validator->validate($file))->toBeTrue(); - function testFile() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; - $this->assertTrue($this->validator->validate($file)); + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'square_image.gif'; + expect($this->validator->validate($file))->toBeFalse(); - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'square_image.gif'; - $this->assertFalse($this->validator->validate($file)); - - // change minimum - $this->validator->setOption(ImageWidth::OPTION_MIN, 200); - $this->assertTrue($this->validator->validate($file)); - } - -} + // change minimum + $this->validator->setOption(ImageWidth::OPTION_MIN, 200); + expect($this->validator->validate($file))->toBeTrue(); +}); diff --git a/tests/src/Rule/File/SizeTest.php b/tests/src/Rule/File/SizeTest.php index 455efd1..810bdaf 100644 --- a/tests/src/Rule/File/SizeTest.php +++ b/tests/src/Rule/File/SizeTest.php @@ -1,39 +1,31 @@ validator = new Size(array( 'size' => '1M' )); - } - - function testMissingFiles() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; - $this->assertFalse($this->validator->validate($file)); - } - - function testFile() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; - $this->assertTrue($this->validator->validate($file)); - - // change size - $this->validator->setOption(Size::OPTION_SIZE, '10K'); - $this->assertFalse($this->validator->validate($file)); - } - - function testSizeAsNumber() - { - $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; - $this->validator->setOption(Size::OPTION_SIZE, 1000000000000); - $this->assertTrue($this->validator->validate($file)); - - // change size - $this->validator->setOption(Size::OPTION_SIZE, 10000); - $this->assertFalse($this->validator->validate($file)); - } -} +use \Sirius\Validation\Rule\File\Size; + +beforeEach(function () { + $this->validator = new Size(array( 'size' => '1M' )); +}); + +test('missing files', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'file_that_does_not_exist.jpg'; + expect($this->validator->validate($file))->toBeFalse(); +}); + +test('file', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; + expect($this->validator->validate($file))->toBeTrue(); + + // change size + $this->validator->setOption(Size::OPTION_SIZE, '10K'); + expect($this->validator->validate($file))->toBeFalse(); +}); + +test('size as number', function () { + $file = realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . 'real_jpeg_file.jpg'; + $this->validator->setOption(Size::OPTION_SIZE, 1000000000000); + expect($this->validator->validate($file))->toBeTrue(); + + // change size + $this->validator->setOption(Size::OPTION_SIZE, 10000); + expect($this->validator->validate($file))->toBeFalse(); +}); diff --git a/tests/src/Rule/GreaterThanTest.php b/tests/src/Rule/GreaterThanTest.php index ab8ed52..18a27ee 100755 --- a/tests/src/Rule/GreaterThanTest.php +++ b/tests/src/Rule/GreaterThanTest.php @@ -1,51 +1,39 @@ rule = new Rule(); - } - - function testDefaultOptions() - { - $this->assertNull($this->rule->getOption('min')); - $this->assertTrue($this->rule->getOption('inclusive')); - } - - function testExclusiveValidation() - { - $this->rule->setOption('inclusive', false); - $this->rule->setOption('min', 100); - $this->assertFalse($this->rule->validate(100)); - } - - function testValidationWithoutALimit() - { - $this->assertTrue($this->rule->validate(0)); - } - - function testConstructCsvFormatMinZeroAndInclusiveFalse() - { - $this->rule = new Rule('0,false'); - $this->assertSame('0', $this->rule->getOption('min')); - $this->assertSame(false, $this->rule->getOption('inclusive')); - } - - function testConstructWithMinValueZeroQueryStringFormat() - { - $this->rule = new Rule('min=0'); - $this->assertSame('0', $this->rule->getOption('min')); - } - - function testConstructWithMinValueZeroCsvFormat() - { - $this->rule = new Rule('0'); - $this->assertSame('0', $this->rule->getOption('min')); - } -} + +beforeEach(function () { + $this->rule = new Rule(); +}); + +test('default options', function () { + expect($this->rule->getOption('min'))->toBeNull(); + expect($this->rule->getOption('inclusive'))->toBeTrue(); +}); + +test('exclusive validation', function () { + $this->rule->setOption('inclusive', false); + $this->rule->setOption('min', 100); + expect($this->rule->validate(100))->toBeFalse(); +}); + +test('validation without a limit', function () { + expect($this->rule->validate(0))->toBeTrue(); +}); + +test('construct csv format min zero and inclusive false', function () { + $this->rule = new Rule('0,false'); + expect($this->rule->getOption('min'))->toBe('0'); + expect($this->rule->getOption('inclusive'))->toBe(false); +}); + +test('construct with min value zero query string format', function () { + $this->rule = new Rule('min=0'); + expect($this->rule->getOption('min'))->toBe('0'); +}); + +test('construct with min value zero csv format', function () { + $this->rule = new Rule('0'); + expect($this->rule->getOption('min'))->toBe('0'); +}); diff --git a/tests/src/Rule/InListTest.php b/tests/src/Rule/InListTest.php index 3202e47..f4aba1a 100755 --- a/tests/src/Rule/InListTest.php +++ b/tests/src/Rule/InListTest.php @@ -1,19 +1,12 @@ rule = new Rule(); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidationWithoutALIstOfAcceptableValues() - { - $this->assertTrue($this->rule->validate('abc')); - } -} +test('validation without a l ist of acceptable values', function () { + expect($this->rule->validate('abc'))->toBeTrue(); +}); diff --git a/tests/src/Rule/IntegerTest.php b/tests/src/Rule/IntegerTest.php index 78b5404..cb20588 100644 --- a/tests/src/Rule/IntegerTest.php +++ b/tests/src/Rule/IntegerTest.php @@ -1,21 +1,14 @@ rule = new Rule(); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidation() - { - $this->assertTrue($this->rule->validate('0')); - $this->assertTrue($this->rule->validate('10')); - $this->assertFalse($this->rule->validate('10.3')); - } -} +test('validation', function () { + expect($this->rule->validate('0'))->toBeTrue(); + expect($this->rule->validate('10'))->toBeTrue(); + expect($this->rule->validate('10.3'))->toBeFalse(); +}); diff --git a/tests/src/Rule/LessThanTest.php b/tests/src/Rule/LessThanTest.php index c61c8bc..7393bef 100755 --- a/tests/src/Rule/LessThanTest.php +++ b/tests/src/Rule/LessThanTest.php @@ -1,50 +1,39 @@ rule = new Rule(); - } - - function testExclusiveValidation() - { - $this->rule->setOption('inclusive', false); - $this->rule->setOption('max', 100); - $this->assertFalse($this->rule->validate(100)); - } - - function testValidationWithoutALimit() - { - $this->assertTrue($this->rule->validate(0)); - } - - function testOptionNormalizationForHttpQueryString() - { - $this->rule = new Rule('max=100&inclusive=false'); - $this->assertFalse($this->rule->validate(100)); - - $this->rule = new Rule('max=100&inclusive=true'); - $this->assertTrue($this->rule->validate(100)); - } - - function testOptionNormalizationForJsonString() - { - $this->rule = new Rule('{"max": 100, "inclusive": false}'); - $this->assertFalse($this->rule->validate(100)); - } - - function testOptionNormalizationForCsvString() - { - $this->rule = new Rule('100,false'); - $this->assertFalse($this->rule->validate(100)); - - $this->rule = new Rule('100,true'); - $this->assertTrue($this->rule->validate(100)); - } -} + +beforeEach(function () { + $this->rule = new Rule(); +}); + +test('exclusive validation', function () { + $this->rule->setOption('inclusive', false); + $this->rule->setOption('max', 100); + expect($this->rule->validate(100))->toBeFalse(); +}); + +test('validation without a limit', function () { + expect($this->rule->validate(0))->toBeTrue(); +}); + +test('option normalization for http query string', function () { + $this->rule = new Rule('max=100&inclusive=false'); + expect($this->rule->validate(100))->toBeFalse(); + + $this->rule = new Rule('max=100&inclusive=true'); + expect($this->rule->validate(100))->toBeTrue(); +}); + +test('option normalization for json string', function () { + $this->rule = new Rule('{"max": 100, "inclusive": false}'); + expect($this->rule->validate(100))->toBeFalse(); +}); + +test('option normalization for csv string', function () { + $this->rule = new Rule('100,false'); + expect($this->rule->validate(100))->toBeFalse(); + + $this->rule = new Rule('100,true'); + expect($this->rule->validate(100))->toBeTrue(); +}); diff --git a/tests/src/Rule/MatchTest.php b/tests/src/Rule/MatchTest.php index 07dde76..d545359 100644 --- a/tests/src/Rule/MatchTest.php +++ b/tests/src/Rule/MatchTest.php @@ -1,36 +1,27 @@ rule = new Rule(); - $this->rule->setContext( - new ArrayWrapper( - array( - 'password' => 'secret' - ) +beforeEach(function () { + $this->rule = new Rule(); + $this->rule->setContext( + new ArrayWrapper( + array( + 'password' => 'secret' ) - ); - } - - function testValidationWithItemPresent() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'password'); - $this->assertTrue($this->rule->validate('secret')); - $this->assertFalse($this->rule->validate('abc')); - } + ) + ); +}); - function testValidationWithoutItemPresent() - { - $this->assertTrue($this->rule->validate('abc')); - $this->assertTrue($this->rule->validate(null)); - } +test('validation with item present', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'password'); + expect($this->rule->validate('secret'))->toBeTrue(); + expect($this->rule->validate('abc'))->toBeFalse(); +}); -} +test('validation without item present', function () { + expect($this->rule->validate('abc'))->toBeTrue(); + expect($this->rule->validate(null))->toBeTrue(); +}); diff --git a/tests/src/Rule/NotEqualTest.php b/tests/src/Rule/NotEqualTest.php index 1a19a44..113b6f0 100644 --- a/tests/src/Rule/NotEqualTest.php +++ b/tests/src/Rule/NotEqualTest.php @@ -1,28 +1,19 @@ rule = new Rule(); - } - function testValidationWithOptionSet() - { - $this->rule->setOption(Rule::OPTION_VALUE, '123'); - $this->assertFalse($this->rule->validate('123')); - $this->assertTrue($this->rule->validate('abc')); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidationWithoutOptionSet() - { - $this->assertFalse($this->rule->validate('abc')); - $this->assertFalse($this->rule->validate(null)); - } +test('validation with option set', function () { + $this->rule->setOption(Rule::OPTION_VALUE, '123'); + expect($this->rule->validate('123'))->toBeFalse(); + expect($this->rule->validate('abc'))->toBeTrue(); +}); -} +test('validation without option set', function () { + expect($this->rule->validate('abc'))->toBeFalse(); + expect($this->rule->validate(null))->toBeFalse(); +}); diff --git a/tests/src/Rule/NotInListTest.php b/tests/src/Rule/NotInListTest.php index 8bd91b1..e9feeda 100755 --- a/tests/src/Rule/NotInListTest.php +++ b/tests/src/Rule/NotInListTest.php @@ -1,19 +1,12 @@ rule = new Rule(); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidationWithoutAListOfForbiddenValues() - { - $this->assertTrue($this->rule->validate('abc')); - } -} +test('validation without a list of forbidden values', function () { + expect($this->rule->validate('abc'))->toBeTrue(); +}); diff --git a/tests/src/Rule/NotMatchTest.php b/tests/src/Rule/NotMatchTest.php index 6395152..6b1ce49 100644 --- a/tests/src/Rule/NotMatchTest.php +++ b/tests/src/Rule/NotMatchTest.php @@ -1,36 +1,27 @@ rule = new Rule(); - $this->rule->setContext( - new ArrayWrapper( - array( - 'password' => 'secret' - ) +beforeEach(function () { + $this->rule = new Rule(); + $this->rule->setContext( + new ArrayWrapper( + array( + 'password' => 'secret' ) - ); - } - - function testValidationWithItemPresent() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'password'); - $this->assertFalse($this->rule->validate('secret')); - $this->assertTrue($this->rule->validate('abc')); - } + ) + ); +}); - function testValidationWithoutItemPresent() - { - $this->assertFalse($this->rule->validate('abc')); - $this->assertFalse($this->rule->validate(null)); - } +test('validation with item present', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'password'); + expect($this->rule->validate('secret'))->toBeFalse(); + expect($this->rule->validate('abc'))->toBeTrue(); +}); -} +test('validation without item present', function () { + expect($this->rule->validate('abc'))->toBeFalse(); + expect($this->rule->validate(null))->toBeFalse(); +}); diff --git a/tests/src/Rule/NumberTest.php b/tests/src/Rule/NumberTest.php index 019a998..8db90d3 100644 --- a/tests/src/Rule/NumberTest.php +++ b/tests/src/Rule/NumberTest.php @@ -1,21 +1,14 @@ rule = new Rule(); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidation() - { - $this->assertTrue($this->rule->validate('0')); - $this->assertTrue($this->rule->validate('0.3')); - $this->assertFalse($this->rule->validate('0,3')); - } -} +test('validation', function () { + expect($this->rule->validate('0'))->toBeTrue(); + expect($this->rule->validate('0.3'))->toBeTrue(); + expect($this->rule->validate('0,3'))->toBeFalse(); +}); diff --git a/tests/src/Rule/RegexTest.php b/tests/src/Rule/RegexTest.php index 2ef6ba7..6bb38a1 100755 --- a/tests/src/Rule/RegexTest.php +++ b/tests/src/Rule/RegexTest.php @@ -1,20 +1,13 @@ rule = new Rule(); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidationWithoutARegexPattern() - { - // pattern was not set, everything is valid - $this->assertTrue($this->rule->validate('abc')); - } -} +test('validation without a regex pattern', function () { + // pattern was not set, everything is valid + expect($this->rule->validate('abc'))->toBeTrue(); +}); diff --git a/tests/src/Rule/RequiredTest.php b/tests/src/Rule/RequiredTest.php index 2252f47..4bd9597 100644 --- a/tests/src/Rule/RequiredTest.php +++ b/tests/src/Rule/RequiredTest.php @@ -1,35 +1,21 @@ rule = new Rule(); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidationWithNull() - { - $this->assertFalse($this->rule->validate(null)); - } +test('validation with null', function () { + expect($this->rule->validate(null))->toBeFalse(); +}); - function testValidationWithEmptyString() - { - $this->assertFalse($this->rule->validate('')); - } +test('validation with empty string', function () { + expect($this->rule->validate(''))->toBeFalse(); +}); - function testValidationWithWhitespaceString() - { - $this->assertTrue($this->rule->validate(' ')); - } -} +test('validation with whitespace string', function () { + expect($this->rule->validate(' '))->toBeTrue(); +}); diff --git a/tests/src/Rule/RequiredWhenTest.php b/tests/src/Rule/RequiredWhenTest.php index 3530af3..d8d8ad6 100644 --- a/tests/src/Rule/RequiredWhenTest.php +++ b/tests/src/Rule/RequiredWhenTest.php @@ -1,93 +1,82 @@ rule = new Rule(); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testValidationWithItemValid() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'email'); - $this->rule->setOption(Rule::OPTION_RULE, 'Email'); - $this->rule->setContext( - new ArrayWrapper( - array( - 'email' => 'me@domain.com' - ) +test('validation with item valid', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'email'); + $this->rule->setOption(Rule::OPTION_RULE, 'Email'); + $this->rule->setContext( + new ArrayWrapper( + array( + 'email' => 'me@domain.com' ) - ); - $this->assertTrue($this->rule->validate('abc')); - $this->assertFalse($this->rule->validate(null)); - $this->assertFalse($this->rule->validate('')); - } + ) + ); + expect($this->rule->validate('abc'))->toBeTrue(); + expect($this->rule->validate(null))->toBeFalse(); + expect($this->rule->validate(''))->toBeFalse(); +}); - function testValidationWithItemNotValid() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'email'); - $this->rule->setOption(Rule::OPTION_RULE, 'Sirius\Validation\Rule\Email'); - $this->rule->setContext( - new ArrayWrapper( - array( - 'email' => 'not_a_valid_email' - ) +test('validation with item not valid', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'email'); + $this->rule->setOption(Rule::OPTION_RULE, 'Sirius\Validation\Rule\Email'); + $this->rule->setContext( + new ArrayWrapper( + array( + 'email' => 'not_a_valid_email' ) - ); - $this->assertTrue($this->rule->validate('abc')); - $this->assertTrue($this->rule->validate(null)); - $this->assertTrue($this->rule->validate('')); - } + ) + ); + expect($this->rule->validate('abc'))->toBeTrue(); + expect($this->rule->validate(null))->toBeTrue(); + expect($this->rule->validate(''))->toBeTrue(); +}); - function testValidationWithoutItem() - { - $this->rule->setOption(Rule::OPTION_RULE, 'Sirius\Validation\Rule\Email'); - $this->rule->setContext( - new ArrayWrapper( - array( - 'email' => 'not_a_valid_email' - ) +test('validation without item', function () { + $this->rule->setOption(Rule::OPTION_RULE, 'Sirius\Validation\Rule\Email'); + $this->rule->setContext( + new ArrayWrapper( + array( + 'email' => 'not_a_valid_email' ) - ); - $this->assertTrue($this->rule->validate('abc')); - $this->assertTrue($this->rule->validate(null)); - $this->assertTrue($this->rule->validate('')); - } + ) + ); + expect($this->rule->validate('abc'))->toBeTrue(); + expect($this->rule->validate(null))->toBeTrue(); + expect($this->rule->validate(''))->toBeTrue(); +}); - function testItemRuleSetAsRuleObject() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'email'); - $this->rule->setOption(Rule::OPTION_RULE, new \Sirius\Validation\Rule\Email); - $this->rule->setContext( - new ArrayWrapper( - array( - 'email' => 'me@domain.com' - ) +test('item rule set as rule object', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'email'); + $this->rule->setOption(Rule::OPTION_RULE, new \Sirius\Validation\Rule\Email); + $this->rule->setContext( + new ArrayWrapper( + array( + 'email' => 'me@domain.com' ) - ); - $this->assertTrue($this->rule->validate('abc')); - $this->assertFalse($this->rule->validate(null)); - $this->assertFalse($this->rule->validate('')); - } + ) + ); + expect($this->rule->validate('abc'))->toBeTrue(); + expect($this->rule->validate(null))->toBeFalse(); + expect($this->rule->validate(''))->toBeFalse(); +}); - function testExceptionThrownOnInvalidItemRule() - { - $this->expectException('\InvalidArgumentException'); - $this->rule->setOption(Rule::OPTION_ITEM, 'email'); - $this->rule->setOption(Rule::OPTION_RULE, new \stdClass()); - $this->rule->setContext( - new ArrayWrapper( - array( - 'email' => 'me@domain.com' - ) +test('exception thrown on invalid item rule', function () { + $this->expectException('\InvalidArgumentException'); + $this->rule->setOption(Rule::OPTION_ITEM, 'email'); + $this->rule->setOption(Rule::OPTION_RULE, new \stdClass()); + $this->rule->setContext( + new ArrayWrapper( + array( + 'email' => 'me@domain.com' ) - ); - $this->assertTrue($this->rule->validate('abc')); - } -} + ) + ); + expect($this->rule->validate('abc'))->toBeTrue(); +}); diff --git a/tests/src/Rule/RequiredWithTest.php b/tests/src/Rule/RequiredWithTest.php index f2f5877..9e01bb7 100644 --- a/tests/src/Rule/RequiredWithTest.php +++ b/tests/src/Rule/RequiredWithTest.php @@ -1,59 +1,44 @@ rule = new Rule(); - $this->rule->setContext( - new ArrayWrapper( - array( - 'item_1' => 'is_present' - ) +beforeEach(function () { + $this->rule = new Rule(); + $this->rule->setContext( + new ArrayWrapper( + array( + 'item_1' => 'is_present' ) - ); - } - - function testValidationWithItemPresent() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'item_1'); - $this->assertTrue($this->rule->validate('abc')); - $this->assertFalse($this->rule->validate(null)); - $this->assertFalse($this->rule->validate('')); - } - - function testValidationWithoutItemPresent() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'item_2'); - $this->assertTrue($this->rule->validate('abc')); - $this->assertTrue($this->rule->validate(null)); - } - - function testValidationWithDeepItems() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'lines[*][quantity]'); - $this->rule->setContext(new ArrayWrapper( - array( - 'lines' => array( - 0 => array( 'quantity' => 10, 'price' => 10 ), - 1 => array( 'quantity' => 20, 'price' => null ), - ) - )) - ); - $this->assertTrue($this->rule->validate(10, 'lines[0][price]')); - $this->assertFalse($this->rule->validate(null, 'lines[1][price]')); - $this->assertFalse($this->rule->validate('', 'lines[1][price]')); - } - -} + ) + ); +}); + +test('validation with item present', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'item_1'); + expect($this->rule->validate('abc'))->toBeTrue(); + expect($this->rule->validate(null))->toBeFalse(); + expect($this->rule->validate(''))->toBeFalse(); +}); + +test('validation without item present', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'item_2'); + expect($this->rule->validate('abc'))->toBeTrue(); + expect($this->rule->validate(null))->toBeTrue(); +}); + +test('validation with deep items', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'lines[*][quantity]'); + $this->rule->setContext(new ArrayWrapper( + array( + 'lines' => array( + 0 => array( 'quantity' => 10, 'price' => 10 ), + 1 => array( 'quantity' => 20, 'price' => null ), + ) + )) + ); + expect($this->rule->validate(10, 'lines[0][price]'))->toBeTrue(); + expect($this->rule->validate(null, 'lines[1][price]'))->toBeFalse(); + expect($this->rule->validate('', 'lines[1][price]'))->toBeFalse(); +}); diff --git a/tests/src/Rule/RequiredWithoutTest.php b/tests/src/Rule/RequiredWithoutTest.php index c8fdade..836484a 100644 --- a/tests/src/Rule/RequiredWithoutTest.php +++ b/tests/src/Rule/RequiredWithoutTest.php @@ -1,59 +1,45 @@ rule = new Rule(); - $this->rule->setContext( - new ArrayWrapper( - array( - 'item_1' => 'is_present' - ) +beforeEach(function () { + $this->rule = new Rule(); + $this->rule->setContext( + new ArrayWrapper( + array( + 'item_1' => 'is_present' ) - ); - } - - function testValidationWithoutItemPresent() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'item_2'); - $this->assertTrue($this->rule->validate('abc')); - $this->assertFalse($this->rule->validate(null)); - $this->assertFalse($this->rule->validate('')); - } - - function testValidationWithItemPresent() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'item_1'); - $this->assertTrue($this->rule->validate('abc')); - $this->assertTrue($this->rule->validate(null)); - $this->assertTrue($this->rule->validate('')); - } - - function testValidationWithDeepItems() - { - $this->rule->setOption(Rule::OPTION_ITEM, 'lines[*][quantity]'); - $this->rule->setContext(new ArrayWrapper( - array( - 'lines' => array( - 0 => array( 'quantity' => null, 'price' => null ), - 1 => array( 'quantity' => 20, 'price' => null ), - ) - )) - ); - $this->assertFalse($this->rule->validate(null, 'lines[0][price]')); - $this->assertTrue($this->rule->validate(null, 'lines[1][price]')); - $this->assertTrue($this->rule->validate('', 'lines[1][price]')); - } -} + ) + ); +}); + +test('validation without item present', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'item_2'); + expect($this->rule->validate('abc'))->toBeTrue(); + expect($this->rule->validate(null))->toBeFalse(); + expect($this->rule->validate(''))->toBeFalse(); +}); + +test('validation with item present', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'item_1'); + expect($this->rule->validate('abc'))->toBeTrue(); + expect($this->rule->validate(null))->toBeTrue(); + expect($this->rule->validate(''))->toBeTrue(); +}); + +test('validation with deep items', function () { + $this->rule->setOption(Rule::OPTION_ITEM, 'lines[*][quantity]'); + $this->rule->setContext(new ArrayWrapper( + array( + 'lines' => array( + 0 => array( 'quantity' => null, 'price' => null ), + 1 => array( 'quantity' => 20, 'price' => null ), + ) + )) + ); + expect($this->rule->validate(null, 'lines[0][price]'))->toBeFalse(); + expect($this->rule->validate(null, 'lines[1][price]'))->toBeTrue(); + expect($this->rule->validate('', 'lines[1][price]'))->toBeTrue(); +}); diff --git a/tests/src/Rule/Upload/ExtensionTest.php b/tests/src/Rule/Upload/ExtensionTest.php index 762d728..9c6f020 100644 --- a/tests/src/Rule/Upload/ExtensionTest.php +++ b/tests/src/Rule/Upload/ExtensionTest.php @@ -1,75 +1,62 @@ validator = new Extension(); - } - - function testExistingFiles() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - } - - function testNoUpload() - { - $file = array( - 'name' => 'not_required', - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => 'not_required', - 'error' => UPLOAD_ERR_NO_FILE - ); - $this->assertTrue($this->validator->validate($file)); - } - - function testMissingFiles() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); - $fileName = 'file_that_does_not_exist.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - } - - function testSetOptionAsString() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, 'jpg, GIF'); - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - } - - function testPotentialMessage() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); - $this->assertEquals( - 'The file does not have an acceptable extension (JPG, PNG)', - (string) $this->validator->getPotentialMessage() - ); - } -} +use \Sirius\Validation\Rule\Upload\Extension; + +beforeEach(function () { + $this->validator = new Extension(); +}); + +test('existing files', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('no upload', function () { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('missing files', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); + $fileName = 'file_that_does_not_exist.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); +}); + +test('set option as string', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, 'jpg, GIF'); + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('potential message', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); + expect((string) $this->validator->getPotentialMessage())->toEqual('The file does not have an acceptable extension (JPG, PNG)'); +}); diff --git a/tests/src/Rule/Upload/ImageHeightTest.php b/tests/src/Rule/Upload/ImageHeightTest.php index 54af80a..109e047 100644 --- a/tests/src/Rule/Upload/ImageHeightTest.php +++ b/tests/src/Rule/Upload/ImageHeightTest.php @@ -1,65 +1,56 @@ validator = new ImageHeight(array( 'min' => 400 )); - } - - function testMissingFiles() - { - $fileName = 'file_that_does_not_exist.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - } - - function testNoUpload() - { - $file = array( - 'name' => 'not_required', - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => 'not_required', - 'error' => UPLOAD_ERR_NO_FILE - ); - $this->assertTrue($this->validator->validate($file)); - } - - function testFile() - { - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - - $fileName = 'square_image.gif'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - - // change minimum - $this->validator->setOption(ImageHeight::OPTION_MIN, 200); - $this->assertTrue($this->validator->validate($file)); - } - -} +use \Sirius\Validation\Rule\Upload\ImageHeight; + +beforeEach(function () { + $this->validator = new ImageHeight(array( 'min' => 400 )); +}); + +test('missing files', function () { + $fileName = 'file_that_does_not_exist.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); +}); + +test('no upload', function () { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('file', function () { + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); + + $fileName = 'square_image.gif'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); + + // change minimum + $this->validator->setOption(ImageHeight::OPTION_MIN, 200); + expect($this->validator->validate($file))->toBeTrue(); +}); diff --git a/tests/src/Rule/Upload/ImageRatioTest.php b/tests/src/Rule/Upload/ImageRatioTest.php index bf7d273..d47f674 100644 --- a/tests/src/Rule/Upload/ImageRatioTest.php +++ b/tests/src/Rule/Upload/ImageRatioTest.php @@ -1,124 +1,110 @@ validator = new ImageRatio(array( 'ratio' => 1 )); +}); - protected function setUp(): void - { - $this->validator = new ImageRatio(array( 'ratio' => 1 )); - } +test('missing files', function () { + $fileName = 'file_that_does_not_exist.gif'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); +}); - function testMissingFiles() - { - $fileName = 'file_that_does_not_exist.gif'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - } +test('no upload', function () { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + expect($this->validator->validate($file))->toBeTrue(); +}); - function testNoUpload() - { - $file = array( - 'name' => 'not_required', - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => 'not_required', - 'error' => UPLOAD_ERR_NO_FILE - ); - $this->assertTrue($this->validator->validate($file)); - } +test('square', function () { + $fileName = 'square_image.gif'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); +}); - function testSquare() - { - $fileName = 'square_image.gif'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - } +test('almost square', function () { + $fileName = 'almost_square_image.gif'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); - function testAlmostSquare() - { - $fileName = 'almost_square_image.gif'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); + // change the error margin + $this->validator->setOption(ImageRatio::OPTION_ERROR_MARGIN, 0.2); + expect($this->validator->validate($file))->toBeTrue(); +}); - // change the error margin - $this->validator->setOption(ImageRatio::OPTION_ERROR_MARGIN, 0.2); - $this->assertTrue($this->validator->validate($file)); - } +test('ratio zero', function () { + $this->validator->setOption(ImageRatio::OPTION_RATIO, 0); + $fileName = 'almost_square_image.gif'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); +}); - function testRatioZero() - { - $this->validator->setOption(ImageRatio::OPTION_RATIO, 0); - $fileName = 'almost_square_image.gif'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - } +test('invalid ratio', function () { + $this->validator->setOption(ImageRatio::OPTION_RATIO, 'abc'); + $fileName = 'almost_square_image.gif'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); +}); - function testInvalidRatio() - { - $this->validator->setOption(ImageRatio::OPTION_RATIO, 'abc'); - $fileName = 'almost_square_image.gif'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - } +test('ratio as string', function () { + $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); + $fileName = '4_by_3_image.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); +}); - function testRatioAsString() - { - $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); - $fileName = '4_by_3_image.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - } - - function testFileNotAnImage() - { - $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); - $fileName = 'corrupt_image.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - } - -} +test('file not an image', function () { + $this->validator->setOption(ImageRatio::OPTION_RATIO, '4:3'); + $fileName = 'corrupt_image.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); +}); diff --git a/tests/src/Rule/Upload/ImageTest.php b/tests/src/Rule/Upload/ImageTest.php index 6758139..bf1b93f 100644 --- a/tests/src/Rule/Upload/ImageTest.php +++ b/tests/src/Rule/Upload/ImageTest.php @@ -1,88 +1,75 @@ validator = new Image(); +}); - protected function setUp(): void - { - $this->validator = new Image(); - } +test('missing files', function () { + $fileName = 'file_that_does_not_exist.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); +}); - function testMissingFiles() - { - $fileName = 'file_that_does_not_exist.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - } +test('no upload', function () { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + expect($this->validator->validate($file))->toBeTrue(); +}); - function testNoUpload() - { - $file = array( - 'name' => 'not_required', - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => 'not_required', - 'error' => UPLOAD_ERR_NO_FILE - ); - $this->assertTrue($this->validator->validate($file)); - } +test('real image', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); +}); - function testRealImage() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - } +test('fake image', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); + $fileName = 'fake_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); +}); - function testFakeImage() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg' )); - $fileName = 'fake_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - } +test('extensions as string', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, 'GIF, jpg'); + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); +}); - function testExtensionsAsString() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, 'GIF, jpg'); - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - } - - function testPotentialMessage() - { - $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); - $this->assertEquals( - 'The file is not a valid image (only JPG, PNG are allowed)', - (string) $this->validator->getPotentialMessage() - ); - } -} +test('potential message', function () { + $this->validator->setOption(Extension::OPTION_ALLOWED_EXTENSIONS, array( 'jpg', 'png' )); + expect((string) $this->validator->getPotentialMessage())->toEqual('The file is not a valid image (only JPG, PNG are allowed)'); +}); diff --git a/tests/src/Rule/Upload/ImageWidthTest.php b/tests/src/Rule/Upload/ImageWidthTest.php index 919575f..eaf7eb0 100644 --- a/tests/src/Rule/Upload/ImageWidthTest.php +++ b/tests/src/Rule/Upload/ImageWidthTest.php @@ -1,65 +1,56 @@ validator = new ImageWidth(array( 'min' => 500 )); - } - - function testMissingFiles() - { - $fileName = 'file_that_does_not_exist.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - } - - function testNoUpload() - { - $file = array( - 'name' => 'not_required', - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => 'not_required', - 'error' => UPLOAD_ERR_NO_FILE - ); - $this->assertTrue($this->validator->validate($file)); - } - - function testFile() - { - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - - $fileName = 'square_image.gif'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - - // change minimum - $this->validator->setOption(ImageWidth::OPTION_MIN, 200); - $this->assertTrue($this->validator->validate($file)); - } - -} +use \Sirius\Validation\Rule\Upload\ImageWidth; + +beforeEach(function () { + $this->validator = new ImageWidth(array( 'min' => 500 )); +}); + +test('missing files', function () { + $fileName = 'file_that_does_not_exist.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); +}); + +test('no upload', function () { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('file', function () { + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); + + $fileName = 'square_image.gif'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); + + // change minimum + $this->validator->setOption(ImageWidth::OPTION_MIN, 200); + expect($this->validator->validate($file))->toBeTrue(); +}); diff --git a/tests/src/Rule/Upload/RequiredTest.php b/tests/src/Rule/Upload/RequiredTest.php index 6f947b4..fc52395 100644 --- a/tests/src/Rule/Upload/RequiredTest.php +++ b/tests/src/Rule/Upload/RequiredTest.php @@ -1,83 +1,66 @@ validator = new Required(); +}); -class RequiredTest extends \PHPUnit\Framework\TestCase -{ +test('missing files', function () { + $fileName = 'file_that_does_not_exist.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); +}); - protected function setUp(): void - { - $this->validator = new Required(); - } +test('upload ok', function () { + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); +}); - function testMissingFiles() - { - $fileName = 'file_that_does_not_exist.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - } +test('upload not ok', function () { + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_PARTIAL + ); + expect($this->validator->validate($file))->toBeFalse(); +}); - function testUploadOk() - { - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - } +test('no upload', function () { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + expect($this->validator->validate($file))->toBeFalse(); +}); - function testUploadNotOk() - { - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_PARTIAL - ); - $this->assertFalse($this->validator->validate($file)); - } - - function testNoUpload() - { - $file = array( - 'name' => 'not_required', - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => 'not_required', - 'error' => UPLOAD_ERR_NO_FILE - ); - $this->assertFalse($this->validator->validate($file)); - } - - function testFile() - { - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - } -} +test('file', function () { + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); +}); diff --git a/tests/src/Rule/Upload/SizeTest.php b/tests/src/Rule/Upload/SizeTest.php index 98662fa..66f86f0 100644 --- a/tests/src/Rule/Upload/SizeTest.php +++ b/tests/src/Rule/Upload/SizeTest.php @@ -1,72 +1,63 @@ validator = new Size(array( 'size' => '1M' )); - } - - function testMissingFiles() - { - $fileName = 'file_that_does_not_exist.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertFalse($this->validator->validate($file)); - } - - function testNoUpload() - { - $file = array( - 'name' => 'not_required', - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => 'not_required', - 'error' => UPLOAD_ERR_NO_FILE - ); - $this->assertTrue($this->validator->validate($file)); - } - - function testFile() - { - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->assertTrue($this->validator->validate($file)); - - // change size - $this->validator->setOption(Size::OPTION_SIZE, '10K'); - $this->assertFalse($this->validator->validate($file)); - } - - function testSizeAsNumber() - { - $fileName = 'real_jpeg_file.jpg'; - $file = array( - 'name' => $fileName, - 'type' => 'not_required', - 'size' => 'not_required', - 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, - 'error' => UPLOAD_ERR_OK - ); - $this->validator->setOption(Size::OPTION_SIZE, 1000000000000); - $this->assertTrue($this->validator->validate($file)); - - // change size - $this->validator->setOption(Size::OPTION_SIZE, 10000); - $this->assertFalse($this->validator->validate($file)); - } -} +use \Sirius\Validation\Rule\Upload\Size; + +beforeEach(function () { + $this->validator = new Size(array( 'size' => '1M' )); +}); + + +test('missing files', function () { + $fileName = 'file_that_does_not_exist.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeFalse(); +}); + +test('no upload', function () { + $file = array( + 'name' => 'not_required', + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => 'not_required', + 'error' => UPLOAD_ERR_NO_FILE + ); + expect($this->validator->validate($file))->toBeTrue(); +}); + +test('file', function () { + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + expect($this->validator->validate($file))->toBeTrue(); + + // change size + $this->validator->setOption(Size::OPTION_SIZE, '10K'); + expect($this->validator->validate($file))->toBeFalse(); +}); + +test('size as number', function () { + $fileName = 'real_jpeg_file.jpg'; + $file = array( + 'name' => $fileName, + 'type' => 'not_required', + 'size' => 'not_required', + 'tmp_name' => realpath(__DIR__ . '/../../../fixitures/') . DIRECTORY_SEPARATOR . $fileName, + 'error' => UPLOAD_ERR_OK + ); + $this->validator->setOption(Size::OPTION_SIZE, 1000000000000); + expect($this->validator->validate($file))->toBeTrue(); + + // change size + $this->validator->setOption(Size::OPTION_SIZE, 10000); + expect($this->validator->validate($file))->toBeFalse(); +}); diff --git a/tests/src/Rule/UrlTest.php b/tests/src/Rule/UrlTest.php index 8b4065c..5b9a4af 100644 --- a/tests/src/Rule/UrlTest.php +++ b/tests/src/Rule/UrlTest.php @@ -1,25 +1,13 @@ rule = new Rule(); - } - function testValidation() - { - $this->assertFalse($this->rule->validate('')); - $this->assertTrue($this->rule->validate('http://www.google.com')); - } -} +beforeEach(function () { + $this->rule = new Rule(); +}); + +test('validation', function () { + expect($this->rule->validate(''))->toBeFalse(); + expect($this->rule->validate('http://www.google.com'))->toBeTrue(); +}); diff --git a/tests/src/Rule/WebsiteTest.php b/tests/src/Rule/WebsiteTest.php index 0d1bec2..9c0a970 100644 --- a/tests/src/Rule/WebsiteTest.php +++ b/tests/src/Rule/WebsiteTest.php @@ -1,19 +1,12 @@ rule = new Rule(); - } +beforeEach(function () { + $this->rule = new Rule(); +}); - function testNonHttpAddresses() - { - $this->assertTrue($this->rule->validate('//google.com')); - } -} +test('non http addresses', function () { + expect($this->rule->validate('//google.com'))->toBeTrue(); +}); diff --git a/tests/src/RuleCollectionTest.php b/tests/src/RuleCollectionTest.php index 46c1aef..8019c44 100644 --- a/tests/src/RuleCollectionTest.php +++ b/tests/src/RuleCollectionTest.php @@ -1,35 +1,31 @@ collection = new RuleCollection(); - } - - function testAddAndRemove() - { - $this->collection->attach(new Rule\Required); - $this->assertEquals(1, count($this->collection)); +beforeEach(function () { + $this->collection = new RuleCollection(); +}); - $this->collection->detach(new Rule\Required); - $this->assertEquals(0, count($this->collection)); - } +test('add and remove', function () { + $this->collection->attach(new Required()); + expect(count($this->collection))->toEqual(1); - function testIterator() - { - $this->collection->attach(new Rule\Email); - $this->collection->attach(new Rule\Required); + $this->collection->detach(new Required()); + expect(count($this->collection))->toEqual(0); +}); - $rules = array(); - foreach ($this->collection as $k => $rule) { - $rules[] = $rule; - } +test('iterator', function () { + $this->collection->attach(new Email); + $this->collection->attach(new Required); - // the required rule should be first - $this->assertTrue($rules[0] instanceof Rule\Required); - $this->assertTrue($rules[1] instanceof Rule\Email); + $rules = array(); + foreach ($this->collection as $k => $rule) { + $rules[] = $rule; } -} + + // the required rule should be first + expect($rules[0] instanceof Required)->toBeTrue(); + expect($rules[1] instanceof Email)->toBeTrue(); +}); diff --git a/tests/src/RuleFactoryTest.php b/tests/src/RuleFactoryTest.php index f6e54e9..2f4b03c 100644 --- a/tests/src/RuleFactoryTest.php +++ b/tests/src/RuleFactoryTest.php @@ -1,49 +1,40 @@ ruleFactory = new RuleFactory(); +}); - protected function setUp(): void - { - $this->ruleFactory = new RuleFactory(); - } +test('registration of validator classes', function () { + $this->ruleFactory->register('even', TestingCustomRule::class); - function testRegistrationOfValidatorClasses() - { - $this->ruleFactory->register('even', '\Sirius\Validation\TestingCustomRule'); + $validator = $this->ruleFactory->createRule('even'); + expect($validator instanceof TestingCustomRule)->toBeTrue(); + expect($validator->validate(3))->toBeTrue(); + expect($validator->validate(4))->toBeFalse(); + expect((string)$validator->getMessage())->toEqual('Value is not valid'); +}); - $validator = $this->ruleFactory->createRule('even'); - $this->assertTrue($validator instanceof TestingCustomRule); - $this->assertTrue($validator->validate(3)); - $this->assertFalse($validator->validate(4)); - $this->assertEquals('Value is not valid', (string) $validator->getMessage()); - } +test('custom error messages', function () { + $this->ruleFactory->register('even', TestingCustomRule::class, 'This should be even', + '{label} should be even'); - function testCustomErrorMessages() - { - $this->ruleFactory->register('even', '\Sirius\Validation\TestingCustomRule', 'This should be even', - '{label} should be even'); - - $validatorWithLabel = $this->ruleFactory->createRule('even', null, null, 'Number'); - $validatorWithLabel->validate(4); - $this->assertEquals('Number should be even', (string) $validatorWithLabel->getMessage()); - - $validator = $validator = $this->ruleFactory->createRule('even'); - $validator->validate(4); - $this->assertEquals('This should be even', (string) $validator->getMessage()); + $validatorWithLabel = $this->ruleFactory->createRule('even', null, null, 'Number'); + $validatorWithLabel->validate(4); + expect((string)$validatorWithLabel->getMessage())->toEqual('Number should be even'); - } -} + $validator = $this->ruleFactory->createRule('even'); + $validator->validate(4); + expect((string)$validator->getMessage())->toEqual('This should be even'); +}); diff --git a/tests/src/Util/ArrTest.php b/tests/src/Util/ArrTest.php index 472b608..5df11eb 100644 --- a/tests/src/Util/ArrTest.php +++ b/tests/src/Util/ArrTest.php @@ -1,139 +1,104 @@ data = array( - 'name' => 'John Doe', - 'addresses' => array( - 'billing' => array( - 'street' => '1st Ave' - ), - 'shipping' => array( - 'street' => '1st Boulevar' - ) +beforeEach(function () { + $this->data = array( + 'name' => 'John Doe', + 'addresses' => array( + 'billing' => array( + 'street' => '1st Ave' + ), + 'shipping' => array( + 'street' => '1st Boulevar' ) - ); - } - + ) + ); +}); - function testOfArrayGetByPath() - { - $this->assertEquals(Arr::getByPath($this->data, 'name'), $this->data['name']); - $this->assertEquals( - Arr::getByPath($this->data, 'addresses[shipping][street]'), - $this->data['addresses']['shipping']['street'] - ); - $this->assertEquals(Arr::getByPath($this->data, 'email'), null); - $this->assertEquals(Arr::getByPath($this->data, 'address[shipping][street]'), null); - } +use \Sirius\Validation\Util\Arr; - function testOfArrayGetByPathRoot() - { - $this->assertEquals($this->data, Arr::getByPath($this->data)); - } +test('array get by path', function () { + expect($this->data['name'])->toEqual(Arr::getByPath($this->data, 'name')); + expect($this->data['addresses']['shipping']['street'])->toEqual(Arr::getByPath($this->data, 'addresses[shipping][street]')); + expect(null)->toEqual(Arr::getByPath($this->data, 'email')); + expect(null)->toEqual(Arr::getByPath($this->data, 'address[shipping][street]')); +}); - function testOfArraySetByPath() - { - $this->data = Arr::setBySelector($this->data, 'email', 'my@domain.com'); - $this->assertEquals(Arr::getByPath($this->data, 'email'), 'my@domain.com'); +test('array get by path root', function () { + expect(Arr::getByPath($this->data))->toEqual($this->data); +}); - $this->data = Arr::setBySelector($this->data, 'newsletters[offers]', true); - $this->assertEquals(Arr::getByPath($this->data, 'newsletters'), array( 'offers' => true )); - $this->data = Arr::setBySelector($this->data, 'addresses[*][state]', 'California'); - $this->assertEquals(Arr::getByPath($this->data, 'addresses[shipping][state]'), 'California'); - $this->assertEquals(Arr::getByPath($this->data, 'addresses[billing][state]'), 'California'); - } +test('array set by path', function () { + $this->data = Arr::setBySelector($this->data, 'email', 'my@domain.com'); + expect('my@domain.com')->toEqual(Arr::getByPath($this->data, 'email')); - function testOfArraySetBySelectorDoesNotOverwriteTheExistingValues() - { - $this->data = Arr::setBySelector($this->data, 'name', 'Jane Fonda'); - $this->assertEquals(Arr::getByPath($this->data, 'name'), 'John Doe'); - } + $this->data = Arr::setBySelector($this->data, 'newsletters[offers]', true); + expect(array( 'offers' => true ))->toEqual(Arr::getByPath($this->data, 'newsletters')); + $this->data = Arr::setBySelector($this->data, 'addresses[*][state]', 'California'); + expect('California')->toEqual(Arr::getByPath($this->data, 'addresses[shipping][state]')); + expect('California')->toEqual(Arr::getByPath($this->data, 'addresses[billing][state]')); +}); - function testOfArraySetBySelectorEnsuresDataIsArray() - { - $this->data = Arr::setBySelector('string', 'name', 'Jane Fonda'); - $this->assertEquals(Arr::getByPath($this->data, 'name'), 'Jane Fonda'); - } +test('array set by selector does not overwrite the existing values', function () { + $this->data = Arr::setBySelector($this->data, 'name', 'Jane Fonda'); + expect('John Doe')->toEqual(Arr::getByPath($this->data, 'name')); +}); - function testOfArrayGetBySelectorDeepSearch() - { - $arr = array( - 'people' => array( - array( - 'name' => 'John', - 'address' => array( - 'city' => 'New York' - ) - ), - array( - 'name' => 'Marry', - 'address' => array( - 'state' => 'California' - ) - ), - ) - ); - $this->assertEquals( +test('array get by selector deep search', function () { + $arr = array( + 'people' => array( array( - 'people[0][address][city]' => 'New York', - 'people[1][address][city]' => null - ), - Arr::getBySelector($arr, 'people[*][address][city]') - ); - } - - function testOfArrayGetBySelectorUsingPath() - { - $arr = array( - 'recipients' => array( - array( 'name' => 'John' ), - array( 'name' => 'Marry', 'email' => 'marry@gmail.com' ) - ) - ); - $this->assertEquals( - array( - 'recipients[0][email]' => null + 'name' => 'John', + 'address' => array( + 'city' => 'New York' + ) ), - Arr::getBySelector($arr, 'recipients[0][email]') - ); - $this->assertEquals( array( - 'recipients[1][email]' => 'marry@gmail.com' + 'name' => 'Marry', + 'address' => array( + 'state' => 'California' + ) ), - Arr::getBySelector($arr, 'recipients[1][email]') - ); - } + ) + ); + expect(Arr::getBySelector($arr, 'people[*][address][city]'))->toEqual(array( + 'people[0][address][city]' => 'New York', + 'people[1][address][city]' => null + )); +}); - function testOfArrayGetBySelectorWithEndingSelector() - { - $arr = array( - 'lines' => array( - 'quantities' => array( 1, 2, 3 ) - ) - ); - $this->assertEquals( - array( - 'lines[quantities][0]' => 1, - 'lines[quantities][1]' => 2, - 'lines[quantities][2]' => 3 - ), - Arr::getBySelector($arr, 'lines[quantities][*]') - ); - } +test('array get by selector using path', function () { + $arr = array( + 'recipients' => array( + array( 'name' => 'John' ), + array( 'name' => 'Marry', 'email' => 'marry@gmail.com' ) + ) + ); + expect(Arr::getBySelector($arr, 'recipients[0][email]'))->toEqual(array( + 'recipients[0][email]' => null + )); + expect(Arr::getBySelector($arr, 'recipients[1][email]'))->toEqual(array( + 'recipients[1][email]' => 'marry@gmail.com' + )); +}); - function testOfArrayGetBySelectorWithWrongSelector() - { - $arr = array( - 'lines' => array( - 'quantities' => array( 1, 2, 3 ) - ) - ); - $this->assertEquals(array(), Arr::getBySelector($arr, 'recipients[*]')); - } -} +test('array get by selector with ending selector', function () { + $arr = array( + 'lines' => array( + 'quantities' => array( 1, 2, 3 ) + ) + ); + expect(Arr::getBySelector($arr, 'lines[quantities][*]'))->toEqual(array( + 'lines[quantities][0]' => 1, + 'lines[quantities][1]' => 2, + 'lines[quantities][2]' => 3 + )); +}); + +test('array get by selector with wrong selector', function () { + $arr = array( + 'lines' => array( + 'quantities' => array( 1, 2, 3 ) + ) + ); + expect(Arr::getBySelector($arr, 'recipients[*]'))->toEqual(array()); +}); diff --git a/tests/src/ValidatorTest.php b/tests/src/ValidatorTest.php index 818c344..3b98439 100755 --- a/tests/src/ValidatorTest.php +++ b/tests/src/ValidatorTest.php @@ -1,6 +1,8 @@ validator = new Validator(new RuleFactory, new ErrorMessage); +}); + +test('if messages can be set and cleared', function () { + expect(count($this->validator->getMessages()))->toEqual(0); + + // add empty message does nothing + $this->validator->addMessage('field_1'); + expect(count($this->validator->getMessages()))->toEqual(0); + + $this->validator->addMessage('field_1', 'Field is required'); + $this->validator->addMessage('field_2', 'Field should be an email'); + expect(count($this->validator->getMessages()))->toEqual(2); + + $this->validator->clearMessages('field_1'); + expect(count($this->validator->getMessages()))->toEqual(1); + $this->validator->clearMessages(); + expect(count($this->validator->getMessages()))->toEqual(0); +}); + +test('exception thrown when the data is not an array', function () { + $this->expectException('InvalidArgumentException'); + $this->validator->validate('string'); + $this->validator->validate(false); +}); + +test('if validate executes', function () { + $this->validator + ->add('field_1', 'Required', null) + ->add('field_2', 'Email', null, 'This field should be an email'); + + expect($this->validator->validate( + array( + 'field_1' => 'exists', + 'field_2' => 'not' + ) + ))->toBeFalse(); + + $this->validator->validate( + array( + 'field_1' => 'exists', + 'field_2' => 'me@domain.com' + ) + ); + + // execute the validation again without data + $this->validator->validate(); + expect(count($this->validator->getMessages()))->toEqual(0); +}); + +test('if missing items validate against the required rule', function () { + $this->validator->add('item', 'required', null, 'This field is required'); + $this->validator->add('items[subitem]', 'required', null, 'This field is required'); + $this->validator->setData(array()); + $this->validator->validate(); + expect(array('This field is required'))->toEqual($this->validator->getMessages('item')); + expect(array('This field is required'))->toEqual($this->validator->getMessages('items[subitem]')); +}); + +test('different data formats', function () { + $this->validator->add('email', 'email'); + + // test array objects + $data = new \ArrayObject(array(), \ArrayObject::ARRAY_AS_PROPS); + $data->email = 'not_an_email'; + + $this->validator->validate($data); + expect(count($this->validator->getMessages('email')))->toEqual(1); + + // test objects with a 'toArray' method + $data = new FakeObject(); + $data->email = 'not_an_email'; + $this->validator->validate($data); + expect(count($this->validator->getMessages('email')))->toEqual(1); +}); + +test('if exception is thrown on invalid rules', function () { + $this->expectException('\InvalidArgumentException'); + $this->validator->add('random_string'); +}); + +test('adding multiple rules at once', function () { + $this->validator->add( + array( + 'item' => array( + 'required', + array('minlength', 'min=4', '{label} should have at least {min} characters', 'Item') + ), + 'itema' => array('required', 'minLength(min=8)', 'required'), + 'itemb' => 'required' + ) + ); + $this->validator->validate( + array( + 'item' => 'ab', + 'itema' => 'abc' + ) + ); + expect($this->validator->getMessages('item'))->toEqual(array('Item should have at least 4 characters')); + expect($this->validator->getMessages('itema'))->toEqual(array('This input should have at least 8 characters')); + expect($this->validator->getMessages('itemb'))->toEqual(array('This field is required')); +}); + +test('adding validation rules via strings without label arg', function () { + $this->validator + // mixed rules in 1 string + ->add('item:Item', 'required | minLength({"min":4})') + // validator options as a QUERY string + ->add('itema:Item', 'minLength', 'min=8') + // validator without options and custom message + ->add('itemb:Item B', 'required') + // validator with defaults + ->add('itemc', 'email'); + $this->validator->validate(array('item' => 'ab', 'itema' => 'abc', 'itemc' => 'abc')); + expect(array((string)$this->validator->getMessages('item')[0]))->toEqual(array('Item should have at least 4 characters')); + expect($this->validator->getMessages('itema'))->toEqual(array('Item should have at least 8 characters')); + expect($this->validator->getMessages('itemb'))->toEqual(array('Item B is required')); + expect($this->validator->getMessages('itemc'))->toEqual(array('This input must be a valid email address')); +}); + +test('adding validation rules via strings', function () { + $this->validator + // mixed rules in 1 string + ->add('item', 'required | minLength({"min":4})({label} should have at least {min} characters)(Item)') + // validator options as a QUERY string + ->add('itema', 'minLength', 'min=8', '{label} should have at least {min} characters', 'Item') + // validator without options and custom message + ->add('itemb', 'required()(Item B is required)') + // validator with defaults + ->add('itemc', 'email'); + $this->validator->validate(array('item' => 'ab', 'itema' => 'abc', 'itemc' => 'abc')); + expect($this->validator->getMessages('item'))->toEqual(array('Item should have at least 4 characters')); + expect($this->validator->getMessages('itema'))->toEqual(array('Item should have at least 8 characters')); + expect($this->validator->getMessages('itemb'))->toEqual(array('Item B is required')); + expect($this->validator->getMessages('itemc'))->toEqual(array('This input must be a valid email address')); +}); + +test('exception on invalid validator options', function () { + $this->expectException('\InvalidArgumentException'); + $this->validator->add('item', 'required', new \stdClass()); +}); + +function fakeValidationMethod($value) { + return false; +} - protected function setUp(): void - { - $this->validator = new Validator(new RuleFactory, new ErrorMessage); - } - - function testIfMessagesCanBeSetAndCleared() - { - $this->assertEquals(0, count($this->validator->getMessages())); - - // add empty message does nothing - $this->validator->addMessage('field_1'); - $this->assertEquals(0, count($this->validator->getMessages())); - - $this->validator->addMessage('field_1', 'Field is required'); - $this->validator->addMessage('field_2', 'Field should be an email'); - $this->assertEquals(2, count($this->validator->getMessages())); - - $this->validator->clearMessages('field_1'); - $this->assertEquals(1, count($this->validator->getMessages())); - $this->validator->clearMessages(); - $this->assertEquals(0, count($this->validator->getMessages())); - } - - function testExceptionThrownWhenTheDataIsNotAnArray() - { - $this->expectException('InvalidArgumentException'); - $this->validator->validate('string'); - $this->validator->validate(false); - } - - function testIfValidateExecutes() - { - $this->validator - ->add('field_1', 'Required', null) - ->add('field_2', 'Email', null, 'This field should be an email'); - - $this->assertFalse( - $this->validator->validate( - array( - 'field_1' => 'exists', - 'field_2' => 'not' - ) - ) - ); - - $this->validator->validate( - array( - 'field_1' => 'exists', - 'field_2' => 'me@domain.com' - ) - ); - - // execute the validation again without data - $this->validator->validate(); - $this->assertEquals(0, count($this->validator->getMessages())); - - } - - function testIfMissingItemsValidateAgainstTheRequiredRule() - { - $this->validator->add('item', 'required', null, 'This field is required'); - $this->validator->add('items[subitem]', 'required', null, 'This field is required'); - $this->validator->setData(array()); - $this->validator->validate(); - $this->assertEquals($this->validator->getMessages('item'), array( 'This field is required' )); - $this->assertEquals($this->validator->getMessages('items[subitem]'), array( 'This field is required' )); - } - - function testDifferentDataFormats() - { - $this->validator->add('email', 'email'); - - // test array objects - $data = new \ArrayObject(array(), \ArrayObject::ARRAY_AS_PROPS); - $data->email = 'not_an_email'; - - $this->validator->validate($data); - $this->assertEquals(1, count($this->validator->getMessages('email'))); - - // test objects with a 'toArray' method - $data = new FakeObject(); - $data->email = 'not_an_email'; - $this->validator->validate($data); - $this->assertEquals(1, count($this->validator->getMessages('email'))); - } - - function testIfExceptionIsThrownOnInvalidRules() - { - $this->expectException('\InvalidArgumentException'); - $this->validator->add('random_string'); - } - - function testAddingMultipleRulesAtOnce() - { - $this->validator->add( - array( - 'item' => array( - 'required', - array( 'minlength', 'min=4', '{label} should have at least {min} characters', 'Item' ) - ), - 'itema' => array( 'required', 'minLength(min=8)', 'required' ), - 'itemb' => 'required' - ) - ); - $this->validator->validate( - array( - 'item' => 'ab', - 'itema' => 'abc' - ) - ); - $this->assertEquals(array( 'Item should have at least 4 characters' ), $this->validator->getMessages('item')); - $this->assertEquals( - array( 'This input should have at least 8 characters' ), - $this->validator->getMessages('itema') - ); - $this->assertEquals(array( 'This field is required' ), $this->validator->getMessages('itemb')); - } - - function testAddingValidationRulesViaStringsWithoutLabelArg() - { - $this->validator - // mixed rules in 1 string - ->add('item:Item', 'required | minLength({"min":4})') - // validator options as a QUERY string - ->add('itema:Item', 'minLength', 'min=8') - // validator without options and custom message - ->add('itemb:Item B', 'required') - // validator with defaults - ->add('itemc', 'email'); - $this->validator->validate(array( 'item' => 'ab', 'itema' => 'abc', 'itemc' => 'abc' )); - $this->assertEquals(array( 'Item should have at least 4 characters' ), - array( (string) $this->validator->getMessages('item')[0] )); - $this->assertEquals(array( 'Item should have at least 8 characters' ), $this->validator->getMessages('itema')); - $this->assertEquals(array( 'Item B is required' ), $this->validator->getMessages('itemb')); - $this->assertEquals(array( 'This input must be a valid email address' ), - $this->validator->getMessages('itemc')); - } - - function testAddingValidationRulesViaStrings() - { - $this->validator - // mixed rules in 1 string - ->add('item', 'required | minLength({"min":4})({label} should have at least {min} characters)(Item)') - // validator options as a QUERY string - ->add('itema', 'minLength', 'min=8', '{label} should have at least {min} characters', 'Item') - // validator without options and custom message - ->add('itemb', 'required()(Item B is required)') - // validator with defaults - ->add('itemc', 'email'); - $this->validator->validate(array( 'item' => 'ab', 'itema' => 'abc', 'itemc' => 'abc' )); - $this->assertEquals(array( 'Item should have at least 4 characters' ), $this->validator->getMessages('item')); - $this->assertEquals(array( 'Item should have at least 8 characters' ), $this->validator->getMessages('itema')); - $this->assertEquals(array( 'Item B is required' ), $this->validator->getMessages('itemb')); - $this->assertEquals(array( 'This input must be a valid email address' ), - $this->validator->getMessages('itemc')); - } - - function testExceptionOnInvalidValidatorOptions() - { - $this->expectException('\InvalidArgumentException'); - $this->validator->add('item', 'required', new \stdClass()); - } - - function fakeValidationMethod($value) - { - return false; - } - - static function fakeStaticValidationMethod($value, $return = false) - { - return $return; - } - - - function testCallbackValidators() - { - $this->validator->add('function', __NAMESPACE__ . '\fakeValidationFunction'); - $this->validator->add('method', array( $this, 'fakeValidationMethod' )); - $this->validator->add( - 'staticMethod', - array( __CLASS__, 'fakeStaticValidationMethod' ), - array( true ) - ); // this will return true - - $this->validator->validate( - array( - 'function' => true, - 'method' => true, - 'staticMethod' => true, - ) - ); - $this->assertEquals(2, count($this->validator->getMessages())); - } - - function testRemovingValidationRules() - { - $this->validator->add('item', 'required'); - $this->assertFalse($this->validator->validate(array())); - - $this->validator->remove('item', 'required'); - $this->assertTrue($this->validator->validate(array())); - } - - function testRemovingAllValidationRules() - { - $this->validator->remove('item', true); - $this->validator->add('item', 'required'); - $this->validator->add('item', 'email'); - $this->validator->setData(array()); - $this->assertFalse($this->validator->validate()); - - $this->validator->remove('item', true); - $rules = $this->validator->getRules(); - $this->assertEquals(count($rules['item']->getRules()), 0); - $this->assertTrue($this->validator->validate(array())); - } +function fakeStaticValidationMethod($value, $return = false) +{ + return $return; +} - function testMatchingRules() - { - $this->validator - ->add('items[*][key]', 'email', null, 'Key must be an email'); - $this->validator->validate( - array( - 'items' => array( - array( 'key' => 'sss' ), - array( 'key' => 'sss' ) - ) +test('callback validators', function () { + $this->validator->add('function', 'fakeValidationFunction'); + + // this will return true + $this->validator->validate( + array( + 'function' => true, + ) + ); + expect(count($this->validator->getMessages()))->toEqual(1); +}); + +test('removing validation rules', function () { + $this->validator->add('item', 'required'); + expect($this->validator->validate(array()))->toBeFalse(); + + $this->validator->remove('item', 'required'); + expect($this->validator->validate(array()))->toBeTrue(); +}); + +test('removing all validation rules', function () { + $this->validator->remove('item', true); + $this->validator->add('item', 'required'); + $this->validator->add('item', 'email'); + $this->validator->setData(array()); + expect($this->validator->validate())->toBeFalse(); + + $this->validator->remove('item', true); + $rules = $this->validator->getRules(); + expect(0)->toEqual(count($rules['item']->getRules())); + expect($this->validator->validate(array()))->toBeTrue(); +}); + +test('matching rules', function () { + $this->validator + ->add('items[*][key]', 'email', null, 'Key must be an email'); + $this->validator->validate( + array( + 'items' => array( + array('key' => 'sss'), + array('key' => 'sss') ) - ); - $this->assertEquals(array( 'Key must be an email' ), $this->validator->getMessages('items[0][key]')); - $this->assertEquals(array( 'Key must be an email' ), $this->validator->getMessages('items[1][key]')); - } - - function testIfParametersAreSentToValidationMethods() - { - $this->validator - ->add('a', 'email', array( 0, 1 ), 'This should be an email') - ->add('b', 'email', array( 0, 1, 2 ), 'This should be an email') - ->add('c', 'email', array( 0, 1, 2, 3 ), 'This should be an email'); - $this->validator->validate(array( 'a' => 'a', 'b' => 'b', 'c' => 'c' )); - $messages = $this->validator->getMessages(); - foreach (array( 'a', 'b', 'c' ) as $k) { - $this->assertEquals(1, count($messages[$k])); - } - } - - function testIfExceptionIsThrownForInvalidValidationMethods() - { - $this->expectException('\InvalidArgumentException'); - $this->validator->add('item', 'faker'); - $this->validator->validate(array( 'item' => true )); - } - - function testEmptyArrayValidation() - { - $this->validator->add(array( - 'a' => array( 'required' ), - 'b' => array( 'required' ) - )); - $this->validator->validate(array()); - $this->assertEquals(2, count($this->validator->getMessages())); - } - - function testValidationRequireConditional() - { - $this->validator->add(array( - 'a' => array( 'number', 'requiredWith(b)' ), - 'b' => array( 'number', 'requiredWith(a)' ) - )); - $this->assertTrue($this->validator->validate(array())); - } -} + ) + ); + expect($this->validator->getMessages('items[0][key]'))->toEqual(array('Key must be an email')); + expect($this->validator->getMessages('items[1][key]'))->toEqual(array('Key must be an email')); +}); + +test('if parameters are sent to validation methods', function () { + $this->validator + ->add('a', 'email', array(0, 1), 'This should be an email') + ->add('b', 'email', array(0, 1, 2), 'This should be an email') + ->add('c', 'email', array(0, 1, 2, 3), 'This should be an email'); + $this->validator->validate(array('a' => 'a', 'b' => 'b', 'c' => 'c')); + $messages = $this->validator->getMessages(); + foreach (array('a', 'b', 'c') as $k) { + expect(count($messages[$k]))->toEqual(1); + } +}); + +test('if exception is thrown for invalid validation methods', function () { + $this->expectException('\InvalidArgumentException'); + $this->validator->add('item', 'faker'); + $this->validator->validate(array('item' => true)); +}); + +test('empty array validation', function () { + $this->validator->add(array( + 'a' => array('required'), + 'b' => array('required') + )); + $this->validator->validate(array()); + expect(count($this->validator->getMessages()))->toEqual(2); +}); + +test('validation require conditional', function () { + $this->validator->add(array( + 'a' => array('number', 'requiredWith(b)'), + 'b' => array('number', 'requiredWith(a)') + )); + expect($this->validator->validate(array()))->toBeTrue(); +}); diff --git a/tests/src/ValueValidatorTest.php b/tests/src/ValueValidatorTest.php index caa119a..08aed6e 100644 --- a/tests/src/ValueValidatorTest.php +++ b/tests/src/ValueValidatorTest.php @@ -1,94 +1,80 @@ validator = new ValueValidator(); - } +beforeEach(function () { + $this->validator = new ValueValidator(); +}); - function testAddingValidationRulesRegularly() - { - $this->validator->add('required')->add('minlength', '{"min":4}', - '{label} should have at least {min} characters', 'Item'); - $this->validator->validate('ab'); - $this->assertEquals(array( - 'Item should have at least 4 characters' - ), $this->validator->getMessages()); - } +test('adding validation rules regularly', function () { + $this->validator->add('required')->add('minlength', '{"min":4}', + '{label} should have at least {min} characters', 'Item'); + $this->validator->validate('ab'); + expect($this->validator->getMessages())->toEqual(array( + 'Item should have at least 4 characters' + )); +}); - function testAddingValidationRulesViaStrings() - { - $this->validator->add('required | minlength({"min":4})({label} should have at least {min} characters)(Item)'); - $this->validator->validate('ab'); - $this->assertEquals(array( - 'Item should have at least 4 characters' - ), $this->validator->getMessages()); - } +test('adding validation rules via strings', function () { + $this->validator->add('required | minlength({"min":4})({label} should have at least {min} characters)(Item)'); + $this->validator->validate('ab'); + expect($this->validator->getMessages())->toEqual(array( + 'Item should have at least 4 characters' + )); +}); - function testRemovingValidationRules() - { - $this->validator->add('required'); - $this->assertFalse($this->validator->validate(null)); - $this->validator->remove('required'); - $this->assertTrue($this->validator->validate(null)); - } +test('removing validation rules', function () { + $this->validator->add('required'); + expect($this->validator->validate(null))->toBeFalse(); + $this->validator->remove('required'); + expect($this->validator->validate(null))->toBeTrue(); +}); - function testRemovingAllRules() - { - $this->validator->add('required')->add('minlength', '{"min":4}', - '{label} should have at least {min} characters', 'Item'); - $this->validator->validate('ab'); - $this->assertEquals(array( - 'Item should have at least 4 characters' - ), $this->validator->getMessages()); - $this->validator->remove(true); - $this->assertTrue($this->validator->validate(null)); - } +test('removing all rules', function () { + $this->validator->add('required')->add('minlength', '{"min":4}', + '{label} should have at least {min} characters', 'Item'); + $this->validator->validate('ab'); + expect($this->validator->getMessages())->toEqual(array( + 'Item should have at least 4 characters' + )); + $this->validator->remove(true); + expect($this->validator->validate(null))->toBeTrue(); +}); - function testNonRequiredRules() - { - $this->validator->add('email'); - $this->assertTrue($this->validator->validate(null)); - $this->assertTrue($this->validator->validate('')); - } +test('non required rules', function () { + $this->validator->add('email'); + expect($this->validator->validate(null))->toBeTrue(); + expect($this->validator->validate(''))->toBeTrue(); +}); - function testDefaultLabel() - { - $this->validator->setLabel('Item'); - $this->validator->add('required')->add('minlength', '{"min":4}', - '{label} should have at least {min} characters'); - $this->validator->validate('ab'); - $this->assertEquals(array( - 'Item should have at least 4 characters' - ), $this->validator->getMessages()); - } +test('default label', function () { + $this->validator->setLabel('Item'); + $this->validator->add('required')->add('minlength', '{"min":4}', + '{label} should have at least {min} characters'); + $this->validator->validate('ab'); + expect($this->validator->getMessages())->toEqual(array( + 'Item should have at least 4 characters' + )); +}); - function testParseRuleWithZeroValueInCsvFormat() - { - $this->validator->add('GreaterThan(0)'); - /** @var GreaterThan $rule */ - foreach ($this->validator->getRules() as $rule) { - break; - } +test('parse rule with zero value in csv format', function () { + $this->validator->add('GreaterThan(0)'); - $this->assertSame('0', $rule->getOption('min')); + /** @var GreaterThan $rule */ + foreach ($this->validator->getRules() as $rule) { + break; + } - $this->validator->validate(1); - $this->assertEmpty($this->validator->getMessages()); + expect($rule->getOption('min'))->toBe('0'); - $this->validator->validate(0); - $this->assertEmpty($this->validator->getMessages()); + $this->validator->validate(1); + expect($this->validator->getMessages())->toBeEmpty(); - $this->validator->validate(-1); - $this->assertNotEmpty($this->validator->getMessages()); - } -} + $this->validator->validate(0); + expect($this->validator->getMessages())->toBeEmpty(); + + $this->validator->validate(-1); + expect($this->validator->getMessages())->not->toBeEmpty(); +}); diff --git a/tools/php-cs-fixer/composer.json b/tools/php-cs-fixer/composer.json new file mode 100644 index 0000000..bc1aa7b --- /dev/null +++ b/tools/php-cs-fixer/composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "friendsofphp/php-cs-fixer": "^3.34" + } +} From 4704128b2b8e6fc781025e1594b337202478a197 Mon Sep 17 00:00:00 2001 From: adrianmiu Date: Sun, 19 Nov 2023 17:40:43 +0200 Subject: [PATCH 112/112] Improved documentation --- docs/custom_rule.md | 1 + docs/index.md | 25 +++++++++++++++++-------- docs/translate_messages.md | 16 +++------------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/docs/custom_rule.md b/docs/custom_rule.md index 968aab6..953707a 100644 --- a/docs/custom_rule.md +++ b/docs/custom_rule.md @@ -56,5 +56,6 @@ $validator->add('key', 'MyApp\Validation\Rule\ThisOrThat', [ ];); // or less verbose +$validator->add('key', 'MyApp\Validation\Rule\ThisOrThat(this=c&that=d)'); $validator->add('key', 'MyApp\Validation\Rule\ThisOrThat(c,d)'); ``` diff --git a/docs/index.md b/docs/index.md index 292b1ba..f15d166 100755 --- a/docs/index.md +++ b/docs/index.md @@ -24,20 +24,29 @@ $validation = new \Sirius\Validation\Validator; // let's validate an invoice form $validator->add(array( - 'date:Date' => 'required | date', - 'client_id:Client' => 'required | clientexists', // clientexists is an app-specific rule - 'notify_recipients[*]:Send invoice to' => 'email', // same rule for an array of items + // :Date specifies the label for the field. It will be used in the error messages + 'order_date:Date' => 'required | date', + // `clientexists` is an app-specific rule + 'client_id:Client' => 'required | clientexists', + // apply the same rule for an array of items + 'notify_recipients[*]:Send invoice to' => 'email', + // apply a rule to a specific item in the array 'shipping_address[line_1]:Address' => 'required' 'shipping_address[city]:City' => 'required' 'shipping_address[state]:State' => 'required' 'shipping_address[country]:Country' => 'required', 'lines[*]price:Price' => [ - 'requiredWith(item=lines[*]product_id', // the price is required only if a product was selected - 'MyApp\Validator\Rule\InvoiceItemPrice' // another app-specific rule, specified as a class + // the price is required only if a product was selected + 'requiredWith(item=lines[*]product_id)', + // another app-specific rule applied to the price, specified as a class + 'MyApp\Validator\Rule\InvoiceItemPrice' ];, 'lines[*]quantity:Quantity' => [ - 'requiredWith(item=lines[*]product_id', - ('invoice_item_quantity', 'The quantity is not valid']; // here we have a custom error message + // the price is required only if a product was selected + 'requiredWith(item=lines[*]product_id)', + // here we have a custom validation rule with no parameters AND a custom error message + 'quantity_in_stock()(The quantity is not valid)' + ; ) )); ``` @@ -56,7 +65,7 @@ This may seem counter-productive but remember that your forms' input fields may ``` 2. Because, If I am to do server side validation I can receive a JSON -```javascript +```json { "errors": { "recipients[0]": "Field must be a valid email", diff --git a/docs/translate_messages.md b/docs/translate_messages.md index 687725b..062bd47 100644 --- a/docs/translate_messages.md +++ b/docs/translate_messages.md @@ -4,11 +4,10 @@ title: Translating the error messages # Translating the error messages -There are a couple of ways to translate the error messages, each having it's pros and cons: +There are a couple of ways to translate the error messages, each having its pros and cons: 1. Postpone the translation until display 2. Use a translatable error message class -3. Use translated string for the message templates ### 1.Postpone the translation until display @@ -34,15 +33,6 @@ class TranslatableErrorMessage extends Sirius\Validation\ErrorMessage { } // later when constructing your validators -$validator = new Sirius\Validation\Validator(null, new TranslatableErrorMessage); -``` - -### 3.Use translated string for the message templates - -```php -// in the validator -$validator->add('title:' . __('Title'), 'maxlength', 'max=100', __('{label} must have less than {max} characters')); - -// or the rule factory -$ruleFactoryInstance->setErrorMessages('maxlength', __('This field must have less than {max} characters'), __('{label} must have less than {max} characters')); +$translator = new MyTranslator(); +$validator = new Sirius\Validation\Validator(null, new TranslatableErrorMessage($translator)); ```