<?php

namespace Comitium5\DesignerBundle\Resolver\Widget;

use Comitium5\DesignerBundle\Entity\Widget;
use Comitium5\DesignerBundle\Validator\EntityValidator;
use Comitium5\DesignerBundle\Validator\EntityValidatorConstraintInterface;
use Comitium5\DesignerBundle\ValueObjects\Common\ErrorObject;

/**
 * Class WidgetValidationResolver
 *
 * Joan Pont <joan.pont@bab-soft.com>
 * @package Comitium5\DesignerBundle\Resolver\Widget
 */
class WidgetValidationResolver
{
    /**
     * @var EntityValidator
     */
    private $entityValidator;

    /**
     * PageValidationResolver constructor.
     *
     * @param EntityValidator $entityValidator
     */
    public function __construct(EntityValidator $entityValidator)
    {
        $this->entityValidator = $entityValidator;
    }

    /**
     * @param Widget|null $widget
     * @param EntityValidatorConstraintInterface[] $constraints
     *
     * @return ErrorObject
     */
    public function __invoke(?Widget $widget, array $constraints = []): ErrorObject
    {
        if (empty($widget)) {
            return new ErrorObject(
                404,
                "common.errors.widget.widget_not_found",
                false
            );
        }

        $result = $this->entityValidator->validate($widget, $constraints);

        return new ErrorObject(
            422,
            $result->getErrorMessage(),
            $result->isValidResult()
        );
    }
}