Skip to content

Instantly share code, notes, and snippets.

@Albert221
Last active November 6, 2016 14:15
Show Gist options
  • Save Albert221/add06cbc7d3162b99bd676daf0ca1e39 to your computer and use it in GitHub Desktop.
Save Albert221/add06cbc7d3162b99bd676daf0ca1e39 to your computer and use it in GitHub Desktop.
Validator concept
<?php
namespace App\Controller;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
class DogController extends BaseController
{
// (...)
public function store(Request $request, Response $response)
{
$this->validator->addField('phone', $request->getParsedBody()['phone']);
$this->validator->addRule('phone', new Validation\Required())
->setMessage('Numer telefonu jest wymagany');
$this->validator->addRule('phone', new Validation\Regex('/^(?:[0+]48)?(\d{9})$/'))
->setMessage('Numer telefonu jest nieprawidłowy');
$this->validator->addField('coordinates', $request->getParsedBody()['coordinates']);
$this->validator->addRule('coordinates', new Validation\Required())
->setMessage('Koordynaty są wymagane');
$this->validator->addRule('coordinates', new Validation\Regex('/^(-?(([0-9]|[0-9][0-9]|1[0-7][0-0])(\.\d*)?|180)),\s(-?(([0-9]|[0-8][0-9])(\.\d*)|90))$/')
->setMessage('Koordynaty są nieprawidłowe');
if ($this->validator->getErrorsCount() > 0) {
$errors = $this->validator->getErrors();
// [
// 'phone' => [
// 'Numer telefonu jest nieprawidłowy'
// ], 'coordinates' => [
// 'Koordynaty są wymagane',
// 'Koordynaty są nieprawidłowe'
// ]
// ]
$this->flash->set('errors', $errors);
return $response->withStatus(302)->withHeader('Location', $this->pathFor('dog.add'));
}
// (...)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment