Skip to content

Validation of Domain Entities in Magento

Igor Miniailo edited this page Aug 18, 2017 · 14 revisions

Table of Contents

Always valid entities

It’s a common question, “Where do I put validation?” Simple answer: put it where it’s needed.

But it’s not just a question of “where”, but of “when”, “what” and “why”. If we treat our entities as data holders, we might think to put all of our validation there, in the form of reactive validation, where the entity is allowed to be put into an “invalid” state.

Validation depends completely on the context of the operation you’re trying to perform. Life becomes much more complicated if we start having “IsValid” properties on our entities.

In domain-driven design (DDD) there is a consideration of the always valid entity (entities which are always in a valid state). There is no need to allow the entity to enter an invalid state. From the DDD perspective, validation rules can be viewed as invariants (the logical assertions that are held to always be true ).

If you let your entities become invalid, you’ve most likely lost the context of what operation was being performed on the entity in the first place. An entity may change state for a wide variety of reasons for a wide variety of operations, so certain attributes may be valid in one operation and invalid in the next.

Thinking operationally

Instead of thinking of changing state on an entity, we need to move up to a higher level of command/query separation, where we perform and execute commands on one or many entities. Instead of answering the question, “is this object valid”, try and answer the question, “Can this operation be performed?”. Because our Service Contracts (command objects) know answers to all of the “Who, what, why” questions, they are in the best position to perform contextual validation based on the operation the user is trying to execute.

Validation Types

There are two major types of validation:

  • Task-based where you don’t need to map validation errors to UI elements (happens in Magento Service Contract Commands).
  • CRUD-y where you do need to do that (happens in Magento Repositories).

Validation in Magento MSI

Based on the above it's decided to follow the practice of having always valid entities in the system. And make the Service Contract Command Services being responsible for Domain Entities validity. If the Entity is being created in a code of business logic, a creational pattern (Factory/Builder) which is used for entity instantiation should take a responsibility of preparation and validation of entity before the creation.

For the sake of convenience, we've introduced two classes to the Framework (not merged into Mainline yet).

Validation Result - to provide an ability return more than one error which happened in the scope of Entity validation process. And isValid() method which helps to decide whether validation passed successfully.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Framework\Validation;

/**
 * @api
 */
class ValidationResult
{
    /**
     * @var array
     */
    private $errors = [];

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

    /**
     * @return bool
     */
    public function isValid()
    {
        return empty($this->errors);
    }

    /**
     * @return array
     */
    public function getErrors()
    {
        return $this->errors;
    }
}

Custom Exception Type which could be thrown out of Service Contracts, providing an ability to return more than one error message to client. For example, could be useful sending Form Data when more than 1 field not passing validation checks.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Framework\Validation;

use Magento\Framework\Exception\AbstractAggregateException;

/**
 * Add possibility to set several messages to exception
 *
 * @api
 */
class ValidationException extends AbstractAggregateException
{
    /**
     * @param array $errors
     * @param \Exception $cause
     * @param int $code
     */
    public function __construct(array $errors = [], \Exception $cause = null, $code = 0)
    {
        foreach ($errors as $error) {
            $this->addError($error);
        }
        parent::__construct($this->phrase, $cause, $code);
    }
}

Service Contract and Validation

Our Service Contracts start to throw ValidationException as a part of contract

namespace Magento\InventoryApi\Api;

/**
 * @api
 */
interface SourceRepositoryInterface
{
    /**
     * Save Source data
     *
     * @param \Magento\InventoryApi\Api\Data\SourceInterface $source
     * @return int
     * @throws \Magento\Framework\Validation\ValidationException
     * @throws \Magento\Framework\Exception\CouldNotSaveException
     */
    public function save(SourceInterface $source);

Implementation of Save Command looks like

    /**
     * @param SourceValidatorInterface $sourceValidator
     * @param SourceResourceModel $sourceResource
     * @param LoggerInterface $logger
     */
    public function __construct(
        SourceValidatorInterface $sourceValidator,
        SourceResourceModel $sourceResource,
        LoggerInterface $logger
    ) {
        $this->sourceValidator = $sourceValidator;
        $this->sourceResource = $sourceResource;
        $this->logger = $logger;
    }

    /**
     * @inheritdoc
     */
    public function execute(SourceInterface $source)
    {
        $validationResult = $this->sourceValidator->validate($source);

        if (!$validationResult->isValid()) {
            throw new ValidationException($validationResult->getErrors());
        }

        try {
            $this->sourceResource->save($source);
            return $source->getSourceId();
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());
            throw new CouldNotSaveException(__('Could not save Source'), $e);
        }
    }

There are several things you can pay attention to:

SourceValidatorInterface looks like:

/**
 * Extension point for base validation
 *
 * @api
 */
interface SourceValidatorInterface
{
    /**
     * @param SourceInterface $source
     * @return ValidationResult
     */
    public function validate(SourceInterface $source);
}

Implementation of SourceValidationInterface which looks like a Composite Object provided through the DI preference

class ValidatorChain implements SourceValidatorInterface
{
    /**
     * @var ValidationResultFactory
     */
    private $validationResultFactory;

    /**
     * @var SourceValidatorInterface[]
     */
    private $validators;

    /**
     * @param ValidationResultFactory $validationResultFactory
     * @param SourceValidatorInterface[] $validators
     * @throws LocalizedException
     */
    public function __construct(
        ValidationResultFactory $validationResultFactory,
        array $validators = []
    ) {
        $this->validationResultFactory = $validationResultFactory;

        foreach ($validators as $validator) {
            if (!$validator instanceof SourceValidatorInterface) {
                throw new LocalizedException(
                    __('Source Validator must implement SourceValidatorInterface.')
                );
            }
        }
        $this->validators = $validators;
    }

    /**
     * @inheritdoc
     */
    public function validate(SourceInterface $source)
    {
        $errors = [];
        foreach ($this->validators as $validator) {
            $validationResult = $validator->validate($source);

            if (!$validationResult->isValid()) {
                $errors = array_merge($errors, $validationResult->getErrors());
            }
        }
        return $this->validationResultFactory->create(['errors' => $errors]);
    }
}

This composite object is extensible through DI.xml via adding custom validators to the array $validators = [] constructor parameter. This customization looks like:

   <preference for="Magento\Inventory\Model\Source\Validator\SourceValidatorInterface" type="Magento\Inventory\Model\Source\Validator\ValidatorChain"/>
    <type name="Magento\Inventory\Model\Source\Validator\ValidatorChain">
        <arguments>
            <argument name="validators" xsi:type="array">
                <item name="name" xsi:type="object">Magento\Inventory\Model\Source\Validator\NameValidator</item>
                <item name="postcode" xsi:type="object">Magento\Inventory\Model\Source\Validator\PostcodeValidator</item>
                <item name="country" xsi:type="object">Magento\Inventory\Model\Source\Validator\CountryValidator</item>
                <item name="carrier_links" xsi:type="object">Magento\Inventory\Model\Source\Validator\CarrierLinks</item>
            </argument>
        </arguments>
    </type>

There are 4 custom validators added for Source Entity. Each of this validator should implement SourceValidatorInterface.

Example of CarrierLinkValidator for Sources:

/**
 * Check that carrier links is valid
 */
class CarrierLinks implements SourceValidatorInterface
{
    /**
     * @var ValidationResultFactory
     */
    private $validationResultFactory;

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

    /**
     * @inheritdoc
     */
    public function validate(SourceInterface $source)
    {
        $value = $source->getCarrierLinks();

        $errors = [];
        if (null !== $value) {
            if (!is_array($value)) {
                $errors[] = __('"%field" must be list of SourceCarrierLinkInterface.', [
                    'field' => SourceInterface::CARRIER_LINKS,
                ]);
            } else if (count($value) && $source->isUseDefaultCarrierConfig()) {
                $errors[] = __('You can\'t configure "%field" because you have chosen Global Shipping configuration.', [
                    'field' => SourceInterface::CARRIER_LINKS,
                ]);
            }
        }
        return $this->validationResultFactory->create(['errors' => $errors]);
    }
}

MSI Documentation:

  1. Technical Vision. Catalog Inventory
  2. Installation Guide
  3. List of Inventory APIs and their legacy analogs
  4. MSI Roadmap
  5. Known Issues in Order Lifecycle
  6. MSI User Guide
  7. DevDocs Documentation
  8. User Stories
  9. User Scenarios:
  10. Technical Designs:
  11. Admin UI
  12. MFTF Extension Tests
  13. Weekly MSI Demos
  14. Tutorials
Clone this wiki locally