chubbyphp/chubbyphp-validation

2.1.0 2017-08-22 19:23 UTC

README

Build Status Total Downloads Latest Stable Version Scrutinizer Code Quality Code Coverage

Description

A simple validation.

Requirements

  • php: ~7.0
  • psr/log: ~1.0

Suggest

  • container-interop/container-interop: ~1.0
  • pimple/pimple: ~3.0

Installation

Through Composer as chubbyphp/chubbyphp-validation.

composer require chubbyphp/chubbyphp-validation "~2.1"

Usage

Validator

<?php

use Chubbyphp\Validation\Error\NestedErrorMessages;
use Chubbyphp\Validation\Registry\ObjectMappingRegistry;
use Chubbyphp\Validation\Validator;
use MyProject\Model\Model;
use MyProject\Repository\ModelRepository;
use MyProject\Validation\ModelMapping;

/** @var ModelRepository $modelRepository */
$modelRepository = ...;

$translate = function (string $key, array $arguments) { return $key; };

$validator = new Validator(new ObjectMappingRegistry([new ModelMapping($modelRepository)]));

$model = new Model();

// name is null
$errorMessages = new NestedErrorMessages($validator->validateObject($model), $translate);
$errorMessages->getMessages(); // ['name' => ['constraint.notnull.null']]

$model->setName('name');

// name is not null
$errorMessages = new NestedErrorMessages($validator->validateObject($model), $translate);
$errorMessages->getMessages(); // []

Mapping

<?php

namespace MyProject\Validation;

use Chubbyphp\Validation\Constraint\NotNullConstraint;
use Chubbyphp\Validation\Mapping\ObjectMappingInterface;
use Chubbyphp\Validation\Mapping\PropertyMapping;
use Chubbyphp\Validation\Mapping\PropertyMappingInterface;
use MyProject\Model\Model;
use MyProject\Repository\ModelRepository;
use MyProject\Validation\UniqueModelConstraint;

class ModelMapping implements ObjectMappingInterface
{
    /**
     * @var ModelRepository
     */
    private $modelRepository;

    /**
     * @param ModelRepository $modelRepository
     */
    public function __construct(ModelRepository $modelRepository)
    {
        $this->modelRepository = $modelRepository;
    }

    /**
     * @return string
     */
    public function getClass(): string
    {
        return Model::class;
    }

    /**
     * @return ConstraintInterface[]
     */
    public function getConstraints(): array
    {
        return [new UniqueModelConstraint($this->modelRepository, ['name'])];
    }

    /**
     * @return PropertyMappingInterface[]
     */
    public function getPropertyMappings(): array
    {
        return [
            new PropertyMapping('name', [new NotNullConstraint()]),
        ];
    }
}

Constraint

Error

Registry

Provider

Copyright

Dominik Zogg 2017