Page MenuHomePhabricator

No OneTemporary

diff --git a/tests/validation/parser/ParserTest.php b/tests/validation/parser/ParserTest.php
index 2812b6d..705795a 100644
--- a/tests/validation/parser/ParserTest.php
+++ b/tests/validation/parser/ParserTest.php
@@ -1,53 +1,53 @@
<?php namespace tests\spitfire\validation\parser;
/*
* The MIT License
*
* Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
use PHPUnit\Framework\TestCase;
-use spitfire\validation\parser\logicparser\LogicProcessor;
+use spitfire\validation\parser\LogicProcessor;
use spitfire\validation\parser\preprocessor\Preprocessor;
class ParserTest extends TestCase
{
public function testParseLiteral() {
$string = 'GET#input(string length[10,24] not["detail"]) OR POST#other(positive number) AND POST#something(required) AND GET#another(required email)';
$pp = new Preprocessor();
$result = $pp->prepare($string)->tokenize();
$or = new LogicProcessor('OR');
$or->run($result);
$and = new LogicProcessor('AND');
$and->run($result);
$made = $result->make();
- $this->assertEquals(true, $made->test(['GET' => ['inputa' => 'test', 'another' => 'test@test.com'], 'POST' => ['other' => 34, 'something' => '123']]));
+ $this->assertEquals(true, $made->setValue(['GET' => ['input' => 'test', 'another' => 'test@test.com'], 'POST' => ['other' => 34, 'something' => '123']])->isOk());
}
}
\ No newline at end of file
diff --git a/validation/ValidatorGroup.php b/validation/ValidatorGroup.php
new file mode 100644
index 0000000..f0d17d6
--- /dev/null
+++ b/validation/ValidatorGroup.php
@@ -0,0 +1,59 @@
+<?php namespace spitfire\validation;
+
+/**
+ *
+ *
+ * @author César de la Cal <cesar@magic3w.com>
+ */
+class ValidatorGroup implements ValidatorInterface
+{
+
+ const TYPE_AND = 'AND';
+ const TYPE_OR = 'OR';
+
+ private $validators;
+
+ private $type;
+
+ public function __construct($validators, $type = self::TYPE_AND) {
+ $this->validators = $validators;
+ $this->type = $type;
+ }
+
+ public function getMessages() {
+ $messages = [];
+
+ foreach ($this->validators as $validator) {
+ $messages = array_merge($messages, $validator->getMessages());
+ }
+
+ return $messages;
+ }
+
+ public function isOk(): bool {
+ $ok = $this->type === 'AND'? true : false;
+
+ foreach ($this->validators as $validator) {
+ if ($this->type === 'AND') { $ok = $ok && $validator->isOk(); }
+ else { $ok = $ok || $validator->isOK(); }
+ }
+
+ return $ok;
+ }
+
+ public function validate() {
+ if (!$this->isOk()) {
+ throw new ValidationException('Validation failure', 0, $this->getMessages());
+ }
+ }
+
+ public function setValue($value) {
+
+ foreach ($this->validators as $validator) {
+ $validator->setValue($value);
+ }
+
+ return $this;
+ }
+
+}
diff --git a/validation/ValidatorInterface.php b/validation/ValidatorInterface.php
index 6871235..7c19bdb 100644
--- a/validation/ValidatorInterface.php
+++ b/validation/ValidatorInterface.php
@@ -1,50 +1,43 @@
<?php namespace spitfire\validation;
/**
* The validator interface is the interface that every element should implement
* to indicate that it's content can be verified for correctness. Every validator
* should allow to make itself more restrictive during runtime to ensure that
* higher security restrictions can be applied under some conditions.
*
* @author César de la Cal <cesar@magic3w.com>
*/
interface ValidatorInterface
{
/**
* Checks whether the content is correct and throws a validation exception in
* case it is not. This makes this method easily overridable to be able to
* generate more diverse error messages when using the method.
*
* For example, if your application applies a special behavior when data has
* been submitted rather than unsubmitted, your application can throw and catch
* each type of error making the code easier to read.
*/
function validate();
/**
* Checks the content. Returns true or false depending on the data being
* received being correct or not. The test should cascade automatically into
* child values.
*
- * @return boolean True if the data is valid
+ * @return bool True if the data is valid
*/
function isOk();
/**
* Returns the list of errors generated when validating the content. For this
* method it's up to the method's implementation to decide whether the method
* should be recursive and cascade into child values collecting all errors or
* just the ones originated by the content itself.
*
* @return ValidationError[] List of errors
*/
function getMessages();
- /**
- * Allows the application using this to apply additional restrictions to the
- * base ones (optional) to restrict the possibilities of the data being valid
- * further.
- */
- function addRule(ValidationRule$rule);
-
}
diff --git a/validation/parser/Component.php b/validation/parser/Component.php
deleted file mode 100644
index b74a004..0000000
--- a/validation/parser/Component.php
+++ /dev/null
@@ -1,37 +0,0 @@
-<?php namespace spitfire\validation\parser;
-
-/*
- * The MIT License
- *
- * Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-abstract class Component
-{
-
- /**
- * Make a tester for this unit.
- *
- * @todo Change the return type to a ValidationRule
- */
- abstract public function make();
-
-}
diff --git a/validation/parser/postprocessor/FunctionPostProcessor.php b/validation/parser/ExpressionValidator.php
similarity index 70%
rename from validation/parser/postprocessor/FunctionPostProcessor.php
rename to validation/parser/ExpressionValidator.php
index f9b60af..2605fc9 100644
--- a/validation/parser/postprocessor/FunctionPostProcessor.php
+++ b/validation/parser/ExpressionValidator.php
@@ -1,57 +1,52 @@
-<?php namespace spitfire\validation\parser\postprocessor;
+<?php namespace spitfire\validation\parser;
/*
* The MIT License
*
* Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
-class FunctionPostProcessor
+class ExpressionValidator extends \spitfire\validation\Validator
{
- private $src = '_GET';
+ private $src = 'GET';
private $parameter;
- private $options;
-
- public function __construct($parameter, $options) {
+ public function __construct($parameter) {
$p = explode('#', $parameter);
if (isset($p[1])) { list($this->src, $this->parameter) = $p; }
else { $this->parameter = $p[0]; }
- $this->options = $options;
}
- public function test($data) {
- if (!isset($data[$this->src]) || !isset($data[$this->src][$this->parameter])) { return false; }
-
- $raw = $data[$this->src][$this->parameter];
- $ok = true;
-
- foreach ($this->options as $option) {
- //TODO: Rules can return true or null on success
- $ok = $ok && $option->test($raw) === false;
+ public function setValue($value) {
+ if (!isset($value[$this->src]) || !isset($value[$this->src][$this->parameter])) {
+ parent::setValue(null);
+ return false;
+ }
+ else {
+ parent::setValue($value[$this->src][$this->parameter]);
+ return true;
}
-
- return $ok;
}
+
}
diff --git a/validation/parser/GroupComponent.php b/validation/parser/GroupComponent.php
index f373d75..acb27e8 100644
--- a/validation/parser/GroupComponent.php
+++ b/validation/parser/GroupComponent.php
@@ -1,131 +1,92 @@
<?php namespace spitfire\validation\parser;
-use spitfire\validation\parser\postprocessor\AndPostProcessor;
-use spitfire\validation\parser\postprocessor\FunctionPostProcessor;
-use spitfire\validation\parser\postprocessor\OrPostProcessor;
-use spitfire\validation\rules\EmptyValidationRule;
-use spitfire\validation\rules\FilterValidationRule;
-use spitfire\validation\rules\PositiveNumberValidationRule;
+use spitfire\validation\parser\ExpressionValidator;
+use spitfire\validation\ValidatorGroup;
/*
* The MIT License
*
* Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
-class GroupComponent extends Component
+class GroupComponent
{
const TYPE_AND = 'AND';
const TYPE_OR = 'OR';
private $items;
private $type;
public function __construct($items, $type = null) {
$this->items = $items;
$this->type = $type;
}
public function tokenize() {
$set = [];
foreach ($this->items as $e) {
if ($e instanceof GroupComponent) { $e->tokenize(); $set[] = $e; }
elseif (is_string($e)) { $set = array_merge($set, array_map(function ($e) { return new Token($e); }, array_filter(explode(' ', $e)))); }
else { $set[] = $e; }
}
$this->items = $set;
return $this;
}
public function getItems() {
return $this->items;
}
public function setItems($items) {
$this->items = $items;
return $this;
}
public function push($item) {
$this->items[] = $item;
}
public function make() {
$items = array_values($this->items);
- $_ret = [];
- if ($this->type !== null) {
- $items = $this->getItems();
- foreach ($items as &$item) { $item = $item->make(); }
- return $this->type === self::TYPE_AND? new AndPostProcessor($items) : new OrPostProcessor($items);
- }
-
- if (count($items) === 1) {
- return $items[0]->make();
- }
- elseif (count($items) === 2 && $items[0] instanceof Token && $items[1] instanceof GroupComponent) {
- $options = $items[1]->make();
- if (!is_array($options)) { $options = [$this->findRule($options, [])]; }
- return new FunctionPostProcessor($items[0]->getContent(), $options);
+ if (count($items) === 2 && $items[0] instanceof Token && $items[1] instanceof GroupComponent) {
+ $params = Parameters::_make($items[1]->getItems());
+ $fn = new ExpressionValidator($items[0]->getContent());
+
+ foreach ($params as $p) { $fn->addRule($p); }
+ return $fn;
}
else {
- //The group represents parameters
- for($i = 0; $i < count($items); $i++) {
-
- $rule = $items[$i];
-
- if (isset($items[$i + 1]) && $items[$i+1] instanceof Options) {
- $options = $items[$i+1];
- $i++;
- }
- else {
- $options = [];
- }
-
- $_ret[] = $this->findRule($rule, $options);
- }
-
- return array_filter($_ret);
- }
- }
-
- public function findRule($name, $options) {
-
- switch($name) {
- case 'email' : return new FilterValidationRule(FILTER_VALIDATE_EMAIL, 'Invalid email provided');
- case 'url' : return new FilterValidationRule(FILTER_VALIDATE_URL, 'Invalid URL provided');
- case 'required': return new EmptyValidationRule('Field may not be empty');
- case 'positive': return new PositiveNumberValidationRule('Positive number required');
+ foreach ($items as &$item) { $item = $item->make(); }
+ return new ValidatorGroup($items, $this->type? : self::TYPE_AND);
}
-
- return null;
}
public function __toString() {
return sprintf('group(%s)', implode(',', $this->items));
}
}
diff --git a/validation/parser/LiteralComponent.php b/validation/parser/LiteralComponent.php
deleted file mode 100644
index b12e315..0000000
--- a/validation/parser/LiteralComponent.php
+++ /dev/null
@@ -1,49 +0,0 @@
-<?php namespace spitfire\validation\parser;
-
-use spitfire\exceptions\PrivateException;
-
-/*
- * The MIT License
- *
- * Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-class LiteralComponent extends Component
-{
- private $content = '';
-
- public function __construct($content) {
- $this->content = reset($content);
- }
-
- public function getContent() {
- return $this->content;
- }
-
- public function make() {
- return $this->content;
- }
-
- public function __toString() {
- return sprintf('<%s>', $this->content);
- }
-
-}
\ No newline at end of file
diff --git a/validation/parser/logicparser/LogicProcessor.php b/validation/parser/LogicProcessor.php
similarity index 98%
rename from validation/parser/logicparser/LogicProcessor.php
rename to validation/parser/LogicProcessor.php
index 7439a92..356d9d6 100644
--- a/validation/parser/logicparser/LogicProcessor.php
+++ b/validation/parser/LogicProcessor.php
@@ -1,112 +1,112 @@
-<?php namespace spitfire\validation\parser\logicparser;
+<?php namespace spitfire\validation\parser;
use spitfire\validation\parser\GroupComponent;
use spitfire\validation\parser\Token;
/*
* The MIT License
*
* Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Parsing Spitfire's validation language is not a simple feat. While simple, the
* language has some caveats that cause it to be rather hard to interpret.
*
* At this stage, the statement the user provided has been broken up into several
* layers (groups, and options - depending on whether they were delimited by
* parenthesis or brackets) and contain a series of tokens.
*
* The logic processor will walk the groups looking for suitable tokens (at this
* point it's just AND and OR) and break the group up if it contains a token,
* wrapping the pieces up in several sub-groups.
*
* @author César de la Cal Bretschneider <cesar@magic3w.com>
*/
class LogicProcessor
{
private $type;
public function __construct($type) {
$this->type = $type;
}
/**
* This method checks if the appropriate token exists within the group. While
* this usually amounts to double checking the group in an unnecessary fashion,
* it usually prevents the group from instancing several objects and discarding
* them if they were unneeded.
*
* @param GroupComponent $component
* @return boolean
*/
public function exists(GroupComponent$component) {
foreach ($component->getItems() as $item) {
if ($item instanceof Token && $item->getContent() == $this->type) {
return true;
}
}
return false;
}
/**
* This is the main method of a logic processor. These components are in
* charge of replacing logical operator tokens (AND and OR) with components
* that represent them appropriately.
*
* @param GroupComponent $component
*/
public function run(GroupComponent$component) {
if (!$this->exists($component)) {
foreach ($component->getItems() as $item) {
if ($item instanceof GroupComponent) {
$this->run($item);
}
}
return;
}
$items = $component->getItems();
$copy = new GroupComponent([], $this->type);
$child = new GroupComponent([]);
$copy->push($child);
foreach ($items as $item) {
if ($item instanceof Token && $item->getContent() == $this->type) {
$child = new GroupComponent([]);
$copy->push($child);
}
elseif ($item instanceof GroupComponent) {
$this->run($item);
$child->push($item);
}
else {
$child->push($item);
}
}
$component->setItems([$copy]);
}
}
\ No newline at end of file
diff --git a/validation/parser/Options.php b/validation/parser/Options.php
index bef04b0..6e932ba 100644
--- a/validation/parser/Options.php
+++ b/validation/parser/Options.php
@@ -1,40 +1,47 @@
<?php namespace spitfire\validation\parser;
/*
* The MIT License
*
* Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
class Options
{
private $items = [];
public function __construct($items) {
- $this->items = array_filter($items);
+ $this->items = collect($items)
+ ->each(function ($e) { return $e instanceof Token? $e->getContent() : preg_split('/\,|\s/', $e); })
+ ->flatten()
+ ->filter();
+ }
+
+ public function getItems() {
+ return $this->items->toArray();
}
public function __toString() {
return sprintf('[%s]', implode(',', $this->items));
}
}
diff --git a/validation/parser/Parameters.php b/validation/parser/Parameters.php
new file mode 100644
index 0000000..f9851eb
--- /dev/null
+++ b/validation/parser/Parameters.php
@@ -0,0 +1,93 @@
+<?php namespace spitfire\validation\parser;
+
+use spitfire\exceptions\PrivateException;
+use spitfire\validation\rules\EmptyValidationRule;
+use spitfire\validation\rules\FilterValidationRule;
+use spitfire\validation\rules\LengthValidationRule;
+use spitfire\validation\rules\NotValidationRule;
+use spitfire\validation\rules\PositiveNumberValidationRule;
+use spitfire\validation\rules\TypeNumberValidationRule;
+use spitfire\validation\rules\TypeStringValidationRule;
+
+/*
+ * The MIT License
+ *
+ * Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+abstract class Parameters
+{
+
+ public static function string() {
+ return new TypeStringValidationRule('Accepts only strings');
+ }
+
+ public static function email() {
+ return new FilterValidationRule(FILTER_VALIDATE_EMAIL, 'Invalid email provided');
+ }
+
+ public static function length($min, $max = null) {
+ return new LengthValidationRule($min, $max, sprintf('Field length must be between %s and %s characters', $min, $max));
+ }
+
+ public static function not($value) {
+ return new NotValidationRule($value, sprintf('Value "%s" is not allowed', $value));
+ }
+
+ public static function positive() {
+ return new PositiveNumberValidationRule('Value must be a positive number');
+ }
+
+ public static function number() {
+ return new TypeNumberValidationRule('Value must be a number');
+ }
+
+ public static function required() {
+ return new EmptyValidationRule('Value is required. Cannot be empty');
+ }
+
+ public static function _make($from) {
+
+ for($i = 0; $i < count($from); $i++) {
+
+ $rule = $from[$i]->getContent();
+
+ if (isset($from[$i + 1]) && $from[$i+1] instanceof Options) {
+ $options = $from[$i+1];
+ $i++;
+ }
+ else {
+ $options = null;
+ }
+
+ if ($rule === '_make') {
+ throw new PrivateException('Invalid validator', 1805171523);
+ }
+
+ if (!is_callable([self::class, $rule])) { throw new PrivateException('Invalid rule: ' . $rule, 1805171527); }
+
+ $_ret[] = call_user_func_array([self::class, $rule], $options? $options->getItems() : []);
+ }
+
+ return array_filter($_ret);
+ }
+
+}
\ No newline at end of file
diff --git a/validation/parser/Token.php b/validation/parser/Token.php
index 8548a35..f7e8fa2 100644
--- a/validation/parser/Token.php
+++ b/validation/parser/Token.php
@@ -1,53 +1,44 @@
<?php namespace spitfire\validation\parser;
/*
* The MIT License
*
* Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
class Token
{
private $content;
public function __construct($content) {
- $this->content = trim($content);
+ $this->content = is_array($content)? reset($content) : trim($content);
}
public function getContent() {
return $this->content;
}
- /**
- *
- * @todo Remove
- * @return type
- */
- public function make() {
- return $this->content;
- }
-
public function __toString() {
return sprintf('token<%s>', $this->content);
}
}
diff --git a/validation/parser/postprocessor/AndPostProcessor.php b/validation/parser/postprocessor/AndPostProcessor.php
deleted file mode 100644
index 9b156de..0000000
--- a/validation/parser/postprocessor/AndPostProcessor.php
+++ /dev/null
@@ -1,44 +0,0 @@
-<?php namespace spitfire\validation\parser\postprocessor;
-
-/*
- * The MIT License
- *
- * Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-class AndPostProcessor
-{
- private $items;
-
- public function __construct($items) {
- $this->items = $items;
- }
-
- public function test($data) {
- $_ret = true;
-
- foreach ($this->items as $item) {
- $_ret = $_ret && $item->test($data);
- }
-
- return $_ret;
- }
-}
diff --git a/validation/parser/postprocessor/OrPostProcessor.php b/validation/parser/postprocessor/OrPostProcessor.php
deleted file mode 100644
index 3b1d4f3..0000000
--- a/validation/parser/postprocessor/OrPostProcessor.php
+++ /dev/null
@@ -1,44 +0,0 @@
-<?php namespace spitfire\validation\parser\postprocessor;
-
-/*
- * The MIT License
- *
- * Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-class OrPostProcessor
-{
- private $items;
-
- public function __construct($items) {
- $this->items = $items;
- }
-
- public function test($data) {
- $_ret = false;
-
- foreach ($this->items as $item) {
- $_ret = $_ret || $item->test($data);
- }
-
- return $_ret;
- }
-}
diff --git a/validation/parser/preprocessor/Preprocessor.php b/validation/parser/preprocessor/Preprocessor.php
index 234c3c7..5515a3f 100644
--- a/validation/parser/preprocessor/Preprocessor.php
+++ b/validation/parser/preprocessor/Preprocessor.php
@@ -1,84 +1,84 @@
<?php namespace spitfire\validation\parser\preprocessor;
/*
* The MIT License
*
* Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
class Preprocessor
{
private $modules;
public function __construct() {
$this->modules = [
- new Module('"', '"', true, function($e) { return new \spitfire\validation\parser\LiteralComponent($e); }), //Literals
+ new Module('"', '"', true, function($e) { return new \spitfire\validation\parser\Token($e); }), //Literals
new Module('(', ')', false, function($e) { return new \spitfire\validation\parser\GroupComponent($e); }), //Parenthesis
new Module('[', ']', false, function($e) { return new \spitfire\validation\parser\Options($e); }) //Brackets
];
}
public function prepare($str) {
$current = '';
$result = new Result(null, null);
for($i = 0; $i < strlen($str); $i++) {
if ($result->getModule() && $result->getModule()->isEscaped() && $str[$i - 1] === '\\') {
$current.= $str[$i];
continue;
}
elseif ($result->getModule() && $result->getModule()->isEscaped() && $str[$i] === '\\') {
continue;
}
elseif ($result->getModule() && $str[$i] === $result->getModule()->getClose() && ($result->getModule()->getOpen() !== $result->getModule()->getClose() || $result->getParent())) {
$result->append($current);
$result->getParent()->append($result->end());
$current = '';
$result = $result->getParent();
continue;
}
foreach($this->modules as $module) {
if ($str[$i] === $module->getOpen()) {
$result->append($current);
$current = '';
$result = new Result($module, $result);
/*
* I hate this structure, and I hope I don't have to use it ever
* again. But here it just makes so much more sense than introducing
* an extra variable that it pains me.
*/
continue 2;
}
}
$current.= $str[$i];
}
return new \spitfire\validation\parser\GroupComponent($result->getElements());
}
}
diff --git a/validation/rules/AcceptsRules.php b/validation/rules/AcceptsRules.php
index 5307099..5fb63e1 100644
--- a/validation/rules/AcceptsRules.php
+++ b/validation/rules/AcceptsRules.php
@@ -1,151 +1,160 @@
<?php namespace spitfire\validation\rules;
+use spitfire\validation\ValidationRule;
+use spitfire\validation\Validator;
+
/*
* The MIT License
*
* Copyright 2018 César de la Cal Bretschneider <cesar@magic3w.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
trait AcceptsRules
{
- abstract public function addRule(\spitfire\validation\ValidationRule$rule);
+
+ /**
+ * Allows the application using this to apply additional restrictions to the
+ * base ones (optional) to restrict the possibilities of the data being valid
+ * further.
+ */
+ abstract public function addRule(ValidationRule$rule);
/**
* Marks this as required, therefore, forcing the content of this validator
* to be non-empty
*
* @param string $message
* @param string $extended
* @return $this
*/
public function required($message, $extended) {
$this->addRule(new EmptyValidationRule($message, $extended));
return $this;
}
/**
* Adds minimum length validation to this object. It will cause an error if
* the data tested is not long enough, this is meant for strings, and will
* probably cause faulty behavior when testing agains other stuff.
*
* @param int $length
* @param string $msg
* @param string $longmsg
- * @return \spitfire\validation\Validator
+ * @return Validator
*/
public function minLength($length, $msg, $longmsg = '') {
$this->addRule(new MinLengthValidationRule($length, $msg, $longmsg));
return $this;
}
/**
* Adds maximum length validation to this object. It will cause an error if
* the data tested is longer than expected, this is meant for strings, and will
* probably cause faulty behavior when testing agains other stuff.
*
* @param int $length
* @param string $msg
* @param string $longmsg
- * @return \spitfire\validation\Validator
+ * @return Validator
*/
public function maxLength($length, $msg, $longmsg = '') {
$this->addRule(new MaxLengthValidationRule($length, $msg, $longmsg));
return $this;
}
/**
* Validates a content as email. This evaluates the string value of what it
* receives and may cause unexpected behavior.
*
* @param string $msg
* @param string $longmsg
- * @return \spitfire\validation\Validator
+ * @return Validator
*/
public function asEmail($msg, $longmsg = '') {
$this->addRule(new FilterValidationRule(FILTER_VALIDATE_EMAIL, $msg, $longmsg));
return $this;
}
/**
* Validates a content as a URL. This evaluates the string value of what it
* receives and may cause unexpected behavior.
*
* @param string $msg
* @param string $longmsg
- * @return \spitfire\validation\Validator
+ * @return Validator
*/
public function asURL($msg, $longmsg = '') {
$this->addRule(new FilterValidationRule(FILTER_VALIDATE_URL, $msg, $longmsg));
return $this;
}
/**
*
* @param int $filter An ID from the FILTER_* constants
* @param string $message
* @param string $extended
- * @return \spitfire\validation\Validator
+ * @return Validator
*/
public function filter($filter, $message, $extended = '') {
$this->addRule(new FilterValidationRule($filter, $message, $extended));
return $this;
}
/**
* Matches the content against a regular expression. If the content matches
* the regular expression validation will be considered successful.
*
* @param string $regex
* @param string $message
* @param string $extended
* @return $this
*/
public function match($regex, $message, $extended = '') {
$this->addRule(new RegexValidationRule($regex, $message, $extended));
return $this;
}
/**
* Checks whether the content of this validator contains a positive integer.
*
* @param string $message
* @param string $extended
* @return $this
*/
public function positive($message, $extended) {
$this->addRule(new PositiveNumberValidationRule($message, $extended));
return $this;
}
/**
* Creates a validation group. This allows to create more complicated rules
* that merge the results of several smaller rules.
*
* @return ValidationRuleGroup
*/
public function group() {
$this->addRule($v = new ValidationRuleGroup($this));
return $v;
}
}
diff --git a/validation/rules/EmptyValidationRule.php b/validation/rules/BaseRule.php
similarity index 63%
copy from validation/rules/EmptyValidationRule.php
copy to validation/rules/BaseRule.php
index dee2df8..946562c 100644
--- a/validation/rules/EmptyValidationRule.php
+++ b/validation/rules/BaseRule.php
@@ -1,47 +1,51 @@
<?php namespace spitfire\validation\rules;
-/**
- * Validates a value is not empty. This allows the system to make sure that a
- * required field has not been field with useless data.
- *
- * @author César de la Cal <cesar@magic3w.com>
- */
-class EmptyValidationRule implements \spitfire\validation\ValidationRule
+
+abstract class BaseRule implements \spitfire\validation\ValidationRule
{
/**
* A message the validation error generated by this object should carry to give
* the end user information about the reason his input was rejected.
+ *
* @var string
*/
private $message;
/**
* Additional information given to the user in case the validation did not
* succeed. This message can hold additional infos on how to solve the error.
+ *
* @var string
*/
private $extendedMessage;
+ /**
+ *
+ * @todo Document
+ * @param string $message
+ * @param string $extendedMessage
+ */
public function __construct($message, $extendedMessage = '') {
$this->message = $message;
$this->extendedMessage = $extendedMessage;
}
+ public function getMessage() {
+ return $this->message;
+ }
+
+ public function getExtendedMessage() {
+ return $this->extendedMessage;
+ }
+
/**
* Tests a value with this validation rule. Returns the errors detected for
* this element or boolean false on no errors.
*
- * @assert ('ok') == false
* @param mixed $value
- * @param mixed $source
* @return \spitfire\validation\ValidationError|boolean
*/
- public function test($value) {
- if (empty($value)) {
- return new ValidationError($this->message, $this->extendedMessage);
- }
- return false;
- }
-
+ abstract public function test($value);
+
}
\ No newline at end of file
diff --git a/validation/rules/EmptyValidationRule.php b/validation/rules/EmptyValidationRule.php
index dee2df8..b28eb94 100644
--- a/validation/rules/EmptyValidationRule.php
+++ b/validation/rules/EmptyValidationRule.php
@@ -1,47 +1,50 @@
<?php namespace spitfire\validation\rules;
+use spitfire\validation\ValidationError;
+use spitfire\validation\ValidationRule;
+
/**
* Validates a value is not empty. This allows the system to make sure that a
* required field has not been field with useless data.
*
* @author César de la Cal <cesar@magic3w.com>
*/
-class EmptyValidationRule implements \spitfire\validation\ValidationRule
+class EmptyValidationRule implements ValidationRule
{
/**
* A message the validation error generated by this object should carry to give
* the end user information about the reason his input was rejected.
* @var string
*/
private $message;
/**
* Additional information given to the user in case the validation did not
* succeed. This message can hold additional infos on how to solve the error.
* @var string
*/
private $extendedMessage;
public function __construct($message, $extendedMessage = '') {
$this->message = $message;
$this->extendedMessage = $extendedMessage;
}
/**
* Tests a value with this validation rule. Returns the errors detected for
* this element or boolean false on no errors.
*
* @assert ('ok') == false
* @param mixed $value
* @param mixed $source
- * @return \spitfire\validation\ValidationError|boolean
+ * @return ValidationError|boolean
*/
public function test($value) {
if (empty($value)) {
return new ValidationError($this->message, $this->extendedMessage);
}
return false;
}
}
\ No newline at end of file
diff --git a/validation/rules/FilterValidationRule.php b/validation/rules/FilterValidationRule.php
index 336f9a6..055e64d 100644
--- a/validation/rules/FilterValidationRule.php
+++ b/validation/rules/FilterValidationRule.php
@@ -1,63 +1,66 @@
<?php namespace spitfire\validation\rules;
+use spitfire\validation\ValidationError;
+use spitfire\validation\ValidationRule;
+
/**
* A filter based validation rule allows you to use premade PHP filters to validate
* your content. Please note that a filter that sanitizes may cause unwanted
* behavior or unexpected ones.
*
* @author César de la Cal <cesar@magic3w.com>
* @last-revision 2013-11-12
*/
-class FilterValidationRule implements \spitfire\validation\ValidationRule
+class FilterValidationRule implements ValidationRule
{
/**
* The filter being applied. This is one of the <code>FILTER_VALIDATION_*</code> constants
* defined in PHP's core, you can use any of those to place here.
* @var int
*/
private $filter;
/**
* A message the validation error generated by this object should carry to give
* the end user information about the reason his input was rejected.
* @var string
*/
private $message;
/**
* Additional information given to the user in case the validation did not
* succeed. This message can hold additional infos on how to solve the error.
* @var string
*/
private $extendedMessage;
/**
* Creates a new validation rule that relies on PHP's filters. You need to pass
* one of the VALIDATION_FILTER_* constants to it so it works. Many of this
* functions provide useful tools for quick validation of common tasks.
*
* @param int $filter One of the VALIDATION_FILTER_* constants
* @param string $message The message returned when an error is found
* @param string $extendedMessage Additional error information
*/
public function __construct($filter, $message, $extendedMessage = '') {
$this->filter = $filter;
$this->message = $message;
$this->extendedMessage = $extendedMessage;
}
/**
* Tests a value with this validation rule. Returns the errors detected for
* this element or boolean false on no errors.
*
* @param mixed $value The value tested.
- * @return \spitfire\validation\ValidationError|boolean A validation error or boolean on success
+ * @return ValidationError|boolean A validation error or boolean on success
*/
public function test($value) {
if (!filter_var($value, $this->filter)) {
return new ValidationError($this->message, $this->extendedMessage);
}
return false;
}
}
\ No newline at end of file
diff --git a/validation/rules/LengthValidationRule.php b/validation/rules/LengthValidationRule.php
new file mode 100644
index 0000000..1adb633
--- /dev/null
+++ b/validation/rules/LengthValidationRule.php
@@ -0,0 +1,67 @@
+<?php namespace spitfire\validation\rules;
+
+use spitfire\validation\ValidationError;
+
+/**
+ * Validates that the length of a content is smaller than the indicated minimum
+ * length. This validates only data as strings which may cause unexpected
+ * behavior if you try to test the length of an array.
+ *
+ * @author César de la Cal <cesar@magic3w.com>
+ */
+class LengthValidationRule extends BaseRule
+{
+ /**
+ * The minimum length a string passed to this element must have for the test
+ * to be passed successfully.
+ *
+ * @var int
+ */
+ private $min;
+
+ /**
+ * The maximum length a string passed to this element can have for the test
+ * to be passed successfully.
+ *
+ * @var int
+ */
+ private $max;
+
+ /**
+ * Creates a maximum length validation rule. This will provide a way to test
+ * whether a string is longer than allowed before using or storing it.
+ *
+ * @param int $min
+ * @param int $max
+ * @param string $message
+ * @param string $extendedMessage
+ */
+ public function __construct($min, $max, $message, $extendedMessage = '') {
+ $this->max = $max;
+ $this->min = $min;
+
+ parent::__construct($message, $extendedMessage);
+ }
+
+
+ /**
+ * Tests a value with this validation rule. Returns the errors detected for
+ * this element or boolean false on no errors.
+ *
+ * @param mixed $value
+ * @return ValidationError|boolean
+ */
+ public function test($value) {
+ if (function_exists('mb_strlen')) {
+ return ($this->max && mb_strlen($value) > $this->max) || mb_strlen($value) < $this->min?
+ new ValidationError($this->getMessage(), $this->getExtendedMessage()) :
+ false;
+ }
+ elseif (($this->max && strlen($value) > $this->max) || strlen($value) < $this->min) {
+ return new ValidationError($this->getMessage(), $this->getExtendedMessage());
+ }
+
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/validation/rules/NotValidationRule.php b/validation/rules/NotValidationRule.php
new file mode 100644
index 0000000..1da5c72
--- /dev/null
+++ b/validation/rules/NotValidationRule.php
@@ -0,0 +1,50 @@
+<?php namespace spitfire\validation\rules;
+
+use spitfire\validation\ValidationError;
+
+/**
+ * Validates that the length of a content is smaller than the indicated minimum
+ * length. This validates only data as strings which may cause unexpected
+ * behavior if you try to test the length of an array.
+ *
+ * @author César de la Cal <cesar@magic3w.com>
+ */
+class NotValidationRule extends BaseRule
+{
+ /**
+ *
+ * @var mixed
+ */
+ private $value;
+
+ /**
+ * Creates a maximum length validation rule. This will provide a way to test
+ * whether a string is longer than allowed before using or storing it.
+ *
+ * @param mixed $value
+ * @param string $message
+ * @param string $extendedMessage
+ */
+ public function __construct($value, $message, $extendedMessage = '') {
+ $this->value = $value;
+
+ parent::__construct($message, $extendedMessage);
+ }
+
+
+ /**
+ * Tests a value with this validation rule. Returns the errors detected for
+ * this element or boolean false on no errors.
+ *
+ * @param mixed $value
+ * @return ValidationError|boolean
+ */
+ public function test($value) {
+ if ($value === $this->value) {
+ return new ValidationError($this->getMessage(), $this->getExtendedMessage());
+ }
+
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/validation/rules/TypeNumberValidationRule.php b/validation/rules/TypeNumberValidationRule.php
new file mode 100644
index 0000000..a3b1b05
--- /dev/null
+++ b/validation/rules/TypeNumberValidationRule.php
@@ -0,0 +1,23 @@
+<?php namespace spitfire\validation\rules;
+
+use spitfire\validation\ValidationError;
+
+
+class TypeNumberValidationRule extends BaseRule
+{
+
+ /**
+ * Tests a value with this validation rule. Returns the errors detected for
+ * this element or boolean false on no errors.
+ *
+ * @param mixed $value
+ * @return ValidationError|boolean
+ */
+ public function test($value) {
+ if (!is_numeric($value)) {
+ return new ValidationError($this->getMessage(), $this->getExtendedMessage());
+ }
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/validation/rules/EmptyValidationRule.php b/validation/rules/TypeStringValidationRule.php
similarity index 70%
copy from validation/rules/EmptyValidationRule.php
copy to validation/rules/TypeStringValidationRule.php
index dee2df8..31247b9 100644
--- a/validation/rules/EmptyValidationRule.php
+++ b/validation/rules/TypeStringValidationRule.php
@@ -1,47 +1,46 @@
<?php namespace spitfire\validation\rules;
-/**
- * Validates a value is not empty. This allows the system to make sure that a
- * required field has not been field with useless data.
- *
- * @author César de la Cal <cesar@magic3w.com>
- */
-class EmptyValidationRule implements \spitfire\validation\ValidationRule
+use spitfire\validation\ValidationError;
+use spitfire\validation\ValidationRule;
+
+
+class TypeStringValidationRule implements ValidationRule
{
/**
* A message the validation error generated by this object should carry to give
* the end user information about the reason his input was rejected.
+ *
* @var string
*/
private $message;
/**
* Additional information given to the user in case the validation did not
* succeed. This message can hold additional infos on how to solve the error.
+ *
* @var string
*/
private $extendedMessage;
public function __construct($message, $extendedMessage = '') {
$this->message = $message;
$this->extendedMessage = $extendedMessage;
}
/**
* Tests a value with this validation rule. Returns the errors detected for
* this element or boolean false on no errors.
*
- * @assert ('ok') == false
* @param mixed $value
* @param mixed $source
- * @return \spitfire\validation\ValidationError|boolean
+ * @return ValidationError|boolean
*/
public function test($value) {
- if (empty($value)) {
+ if (!is_string($value)) {
return new ValidationError($this->message, $this->extendedMessage);
}
return false;
}
-
+
}
\ No newline at end of file

File Metadata

Mime Type
text/x-diff
Expires
Apr 13 2021, 9:04 AM (9 w, 11 h ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1787
Default Alt Text
(52 KB)

Event Timeline