Skip to content

Commit

Permalink
Merge pull request #2 from tflori/error-object
Browse files Browse the repository at this point in the history
Error object (solves #1)
  • Loading branch information
tflori authored Nov 26, 2017
2 parents de12ce8 + 4cfb937 commit 2c9b54d
Show file tree
Hide file tree
Showing 21 changed files with 270 additions and 171 deletions.
12 changes: 7 additions & 5 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ permalink: /index.html
---
## {{ page.title }}

*Verja* is a very simple and stupid library to filter and validate input data. The name *Verja* comes from the Old
Norse language and means defender. The idea behind this name is that the library defends you from invalid input.
**Verja** is a very simple and stupid library to filter and validate input data. The name
[**Verja**](https://en.wiktionary.org/wiki/verja) (pronunciation **/ˈvɛrja/**
[IPA](https://en.wiktionary.org/wiki/Wiktionary:International_Phonetic_Alphabet)) comes from the Old Norse language and
means to defend. The idea behind this name is that the library defends you from invalid, missing and unwanted input.

The interface is very straight forward. `Verja\Gate` is the main object (you should **not reuse** this object). It
holds the data that should be validated, and the `Verja\Field`s. Each field has it's own filters and validators. When
you run `$container->validate()` each field gets filtered and validated.
The interface is very straight forward. `Verja\Gate` is the gate for your input data. It holds the data that should be
validated, and the `Verja\Field`s. Each field has it's own filters and validators. When you run `$container->validate()`
each field gets filtered and validated.

Here is a small pseudo code example to explain the simplicity of this library:

Expand Down
85 changes: 57 additions & 28 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,45 +163,74 @@ $gate->getData(); // throws "Invalid pw: value should be equal to contexts pw_co

### Show Errors

The `Validator` may contain an error in the following format after validating an invalid value:

```php?start_inline=true
return [
'key' => 'NOT_CONTAINS', // a key that can be used for translation
'value' => 'any string', // the value that got validated
'message' => 'value should contain "bar"', // OPTIONAL - a default error message (used for exceptions)
'parameters' => [ 'subString' => 'bar' ], // OPTIONAL - parameters used for validation
];
```
The `Validator` may contain an `Verja\Error` after validating an invalid value that you can retrieve with
`Validator::getError()`.

The `Field` contains an array of all errors occurred during `Field::validate()` and the `Gate` contains an array with
all arrays of errors from the fields. The method `Gate::getErrors()` may return something like this:

```php?start_inline=true
return [
'foo' => [
[
'key' => 'NOT_CONTAINS',
'value' => 'any string',
'message' => 'value should contain "bar"',
'parameters' => [ 'subString' => 'bar' ],
]
new \Verja\Error(
'NOT_CONTAINS',
'any string',
'value should contain "bar"',
[ 'subString' => 'bar' ]
)
],
'pw' => [
[
'key' => 'STRLEN_TOO_SHORT',
'value' => 'abc123',
'message' => 'value should be at least 8 characters long',
'parameters' => [ 'min' => 8, 'max' => 0 ],
],
[
'key' => 'NOT_EQUAL',
'value' => 'abc123',
'message' => 'value should be equal to contexts pw_conf',
'parameters' => [ 'opposite' => 'pw_conf', 'jsonEncode' => true ]
]
new \Verja\Error(
'STRLEN_TOO_SHORT',
'abc123',
'value should be at least 8 characters long',
[ 'min' => 8, 'max' => 0 ]
),
new \Verja\Error(
'NOT_EQUAL',
'abc123',
'value should be equal to contexts pw_conf',
[ 'opposite' => 'pw_conf', 'jsonEncode' => true ]
)
],
];
```

You can then serialize this data to this json:

```json
{
"foo": [
{
"key": "NOT_CONTAINS",
"message": "value should contain \"bar\"",
"parameters": {
"subString": "bar",
"value": "any string"
}
}
],
"pw": [
{
"key": "STRLEN_TOO_SHORT",
"message": "value should be at least 8 characters long",
"parameters": {
"min": 8,
"max": 0,
"value": "abc123"
}
},
{
"key": "NOT_EQUAL",
"message": "value should be equal to contexts pw_conf",
"parameters": {
"opposite": "pw_conf",
"jsonEncode": true,
"value": "abc123"
}
}
]
}
```

### Example
Expand Down
39 changes: 39 additions & 0 deletions src/Error.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace Verja;

class Error
{
/** @var string */
public $key;

/** @var string */
public $message;

/** @var array */
public $parameters;

/**
* Error constructor.
*
* @param string $key
* @param mixed $value
* @param string $message
* @param array $parameters
*/
public function __construct(string $key, $value, string $message = null, array $parameters = null)
{
$this->key = $key;

if ($message !== null) {
$this->message = $message;
} else {
$this->message = sprintf('%s %s', json_encode($value), $key);
}

if ($parameters !== null) {
$this->parameters = $parameters;
}
$this->parameters['value'] = $value;
}
}
27 changes: 0 additions & 27 deletions src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,31 +88,4 @@ public function getInverseError($value)
{
return null;
}

/**
* @param string $key
* @param mixed $value
* @param string|null $message
* @param array|null $parameters
* @return array
*/
public static function buildError(string $key, $value, string $message = null, array $parameters = null)
{
$error = [
'key' => $key,
'value' => $value,
];

if ($parameters !== null) {
$error['parameters'] = $parameters;
}

if ($message !== null) {
$error['message'] = $message;
} else {
$error['message'] = sprintf('%s %s', json_encode($value), $key);
}

return $error;
}
}
3 changes: 2 additions & 1 deletion src/Validator/Callback.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Verja\Validator;

use Verja\Error;
use Verja\Validator;

class Callback extends Validator
Expand All @@ -24,7 +25,7 @@ public function validate($value, array $context = []): bool
{
$result = call_user_func($this->callback, $value, $context);

if (is_array($result) && isset($result['key']) && isset($result['value']) && isset($result['message'])) {
if ($result instanceof Error) {
$this->error = $result;
return false;
}
Expand Down
5 changes: 3 additions & 2 deletions src/Validator/Contains.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Verja\Validator;

use Verja\Error;
use Verja\Validator;

class Contains extends Validator
Expand All @@ -23,7 +24,7 @@ public function __construct(string $subString)
public function validate($value, array $context = []): bool
{
if (strpos($value, $this->subString) === false) {
$this->error = $this->buildError(
$this->error = new Error(
'NOT_CONTAINS',
$value,
sprintf('value should contain "%s"', $this->subString),
Expand All @@ -38,7 +39,7 @@ public function validate($value, array $context = []): bool
/** {@inheritdoc} */
public function getInverseError($value)
{
return $this->buildError(
return new Error(
'CONTAINS',
$value,
sprintf('value should not contain "%s"', $this->subString),
Expand Down
5 changes: 3 additions & 2 deletions src/Validator/EmailAddress.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Verja\Validator;

use Verja\Error;
use Verja\Validator;

class EmailAddress extends Validator
Expand All @@ -13,7 +14,7 @@ class EmailAddress extends Validator
public function validate($value, array $context = []): bool
{
if (!preg_match('/^' . self::LOCAL_PART_PATTERN . '@' . self::DOMAIN_PART_PATTERN . '$/', $value)) {
$this->error = $this::buildError(
$this->error = new Error(
'NO_EMAIL_ADDRESS',
$value,
'value should be a valid email address',
Expand All @@ -28,7 +29,7 @@ public function validate($value, array $context = []): bool
/** {@inheritdoc} */
public function getInverseError($value)
{
return $this::buildError(
return new Error(
'EMAIL_ADDRESS',
$value,
'value should not be an email address',
Expand Down
5 changes: 3 additions & 2 deletions src/Validator/Equals.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Verja\Validator;

use Verja\Error;
use Verja\Validator;

class Equals extends Validator
Expand Down Expand Up @@ -43,7 +44,7 @@ public function validate($value, array $context = []): bool
}
}

$this->error = $this->buildError(
$this->error = new Error(
'NOT_EQUAL',
$value,
sprintf('value should be equal to contexts %s', $this->opposite),
Expand All @@ -55,7 +56,7 @@ public function validate($value, array $context = []): bool
/** {@inheritdoc} */
public function getInverseError($value)
{
return $this->buildError(
return new Error(
'EQUALS',
$value,
sprintf('value should not be equal to contexts %s', $this->opposite),
Expand Down
5 changes: 3 additions & 2 deletions src/Validator/NotEmpty.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Verja\Validator;

use Verja\Error;
use Verja\Validator;

class NotEmpty extends Validator
Expand All @@ -10,7 +11,7 @@ class NotEmpty extends Validator
public function validate($value, array $context = []): bool
{
if (empty($value)) {
$this->error = $this->buildError(
$this->error = new Error(
'IS_EMPTY',
$value,
'value should not be empty'
Expand All @@ -24,7 +25,7 @@ public function validate($value, array $context = []): bool
/** {@inheritdoc} */
public function getInverseError($value)
{
return $this->buildError(
return new Error(
'IS_NOT_EMPTY',
$value,
'value should be empty'
Expand Down
5 changes: 3 additions & 2 deletions src/Validator/PregMatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Verja\Validator;

use Verja\Error;
use Verja\Validator;

class PregMatch extends Validator
Expand All @@ -26,7 +27,7 @@ public function validate($value, array $context = []): bool
return true;
}

$this->error = $this->buildError(
$this->error = new Error(
'NO_MATCH',
$value,
sprintf('value should match "%s"', $this->pattern),
Expand All @@ -38,7 +39,7 @@ public function validate($value, array $context = []): bool
/** {@inheritdoc} */
public function getInverseError($value)
{
return $this->buildError(
return new Error(
'MATCHES',
$value,
sprintf('value should not match "%s"', $this->pattern),
Expand Down
5 changes: 3 additions & 2 deletions src/Validator/StrLen.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Verja\Validator;

use Verja\Error;
use Verja\Validator;

class StrLen extends Validator
Expand Down Expand Up @@ -30,15 +31,15 @@ public function validate($value, array $context = []): bool
{
$strLen = strlen($value);
if ($strLen < $this->min) {
$this->error = $this->buildError(
$this->error = new Error(
'STRLEN_TOO_SHORT',
$value,
sprintf('value should be at least %d characters long', $this->min),
[ 'min' => $this->min, 'max' => $this->max ]
);
return false;
} elseif ($this->max > 0 && $strLen > $this->max) {
$this->error = $this->buildError(
$this->error = new Error(
'STRLEN_TOO_LONG',
$value,
sprintf('value should be maximal %d characters long', $this->max),
Expand Down
Loading

0 comments on commit 2c9b54d

Please sign in to comment.