Validate uniqueness.

@param \Railken\Lem\Contracts\EntityContract $entity
@param Bag                                   $parameters

@return Collection
514078
public function validateUniqueness($entity, $parameters)
    {
        $errors = new Collection();

        foreach ($this->getManager()->getUnique() as $name => $attributes) {
            // Check if attribute exists...

            $q = $this->getManager()->getRepository()->getQuery();

            $where = collect();
            foreach ($attributes as $attribute) {
                $attribute = explode(':', $attribute);

                $col = count($attribute) > 1 ? $attribute[1] : $attribute[0];
                $attribute = $attribute[0];

                $value = $parameters->get($attribute, $entity->$attribute);

                if ($value) {
                    $where[$col] = is_object($value) && $value instanceof EntityContract ? $value->id : $value;
                }
            }

            if ($entity->exists) {
                $q->where('id', '!=', $entity->id);
            }

            if ($where->count() > 0 && $q->where($where->toArray())->count() > 0) {
                $exception = $this->getManager()->getException(Tokens::NOT_UNIQUE);

                $errors->push(new $exception($where));
            }
        }

        return $errors;
    }
902990
private function parseUniqueRule($field, array $parameters, $type)
    {
        // If we have a unique rule, make sure it's built correctly
        if ($type != 'unique') return $parameters;

        // The first item may be null, remove it if that's the case
        $parameters = array_filter($parameters);

        // Determine primary key
        $primaryKey = (isset($this->primaryKey)) ? $this->primaryKey : 'id';

        // Construct unique rule correctly
        $rule = [
            array_get($parameters, 0, $this->getTable()),
            array_get($parameters, 1, $field),
            array_get($parameters, 2, $this->{$primaryKey}),
            array_get($parameters, 3, $primaryKey)
        ];

        // Merge in any other parameters we have
        return $this->mergeArrayFromIndex($rule, $parameters, 4);
    }
1205864
public function serialize(EntityContract $entity, Collection $select = null)
    {
        $bag = parent::serialize($entity, $select);

        $bag->set('files', $entity->files->map(function ($file) {
            return [
                'url' => $file->media->first()->getFullUrl(),
            ];
        }));

        return $bag;
    }
1100160
protected function cartItemsCheck($entity)
    {
        return function ($item) use ($entity) {
            return $item->modelType == get_class($entity) &&
                $item->modelId == $entity->{$entity->getKeyName()}
            ;
        };
    }
1032669
public function updateOrCreate($criteria, $parameters = null)
    {
        if ($criteria instanceof Bag) {
            $criteria = $criteria->toArray();
        }

        if ($parameters === null) {
            $parameters = $criteria;
        }

        $parameters = $this->castParameters($parameters);
        $entity = $this->getRepository()->findOneBy($criteria);

        return $entity !== null ? $this->update($entity, $parameters) : $this->create($parameters->merge($criteria));
    }
1073193
public List<String> validateUniques(Identifiable<?> entity) {
        return newArrayList(concat( //
                validateCompositeUniqueConstraints(entity), //
                validateSimpleUniqueConstraints(entity) //
        ));
    }
204008
protected function prepareUniqueRule($parameters, $field)
    {
        // If the table name isn't set, infer it.
        if (empty($parameters[0])) {
            $parameters[0] = $this->getModel()->getTable();
        }

        // If the connection name isn't set but exists, infer it.
        if ((strpos($parameters[0], '.') === false) && (($connectionName = $this->getModel()->getConnectionName()) !== null)) {
            $parameters[0] = $connectionName.'.'.$parameters[0];
        }

        // If the field name isn't get, infer it.
        if (! isset($parameters[1])) {
            $parameters[1] = $field;
        }

        if ($this->exists) {
            // If the identifier isn't set, infer it.
            if (! isset($parameters[2]) || strtolower($parameters[2]) === 'null') {
                $parameters[2] = $this->getModel()->getKey();
            }

            // If the primary key isn't set, infer it.
            if (! isset($parameters[3])) {
                $parameters[3] = $this->getModel()->getKeyName();
            }

            // If the additional where clause isn't set, infer it.
            // Example: unique:users,email,123,id,username,NULL
            foreach ($parameters as $key => $parameter) {
                if (strtolower((string) $parameter) === 'null') {
                    // Maintain NULL as string in case the model returns a null value
                    $value = $this->getModel()->{$parameters[$key - 1]};
                    $parameters[$key] = is_null($value) ? 'NULL' : $value;
                }
            }
        }

        return 'unique:' . implode(',', $parameters);
    }
533465
public function valid(EntityContract $entity, $value)
    {
        return v::length($this->getMinLength(), $this->getMaxLength())->validate($value);
    }
1327788
private static function unique($model, $field)
    {
        if ($row = $model::find($field, $model->{$field}) and $row->{$model::primaryKey()} != $model->{$model::primaryKey()}) {
            return 'errors.validations.already_in_use';
        }
    }
549004
public function validate($entity, $context = null) : bool
    {
        if (!$entity instanceof AuditEvent) {
            throw new \LogicException('The Entity to validate must be an instance of \Fei\Service\Audit\Entity\AuditEvent');
        }

        return parent::validate($entity, $context);
    }
828995
public function authorizeAction(string $action, EntityContract $entity, Bag $parameters)
    {
        $errors = new Collection();

        $permission = $this->getPermission($action);

        if (!$this->getManager()->getAgent()->can($permission)) {
            $errors->push($this->newException(Tokens::NOT_AUTHORIZED, $permission));
        }

        return $errors;
    }
1067311
public function valid(EntityContract $entity, $value)
    {
        $validator = Validation::createValidator();

        $violations = $validator->validate($value, [
            new Url(),
        ]);

        return $violations->count() === 0;
    }
886073
protected function validateEntity($entity)
    {
        $errors = Validation::createValidatorBuilder()
            ->enableAnnotationMapping()
            ->getValidator()
            ->validate($entity);

        if ($errors->count() > 0) {
            throw RestException::createFromConstraintViolationList($errors);
        }

        return $entity;
    }
1184212
public function validate($entity, Constraint $constraint)
    {
        if (!$entity instanceof RoutableSubjectInterface) {
            throw new \InvalidArgumentException(sprintf('Expected instance of %s', RoutableSubjectInterface::class));
        }
        
        $route  = $entity->getRoute();
        $slug   = $entity->getSlug();
        $locale = $entity->getLocale();
        $result = $this->repository->findOneBy(['path' => $slug, 'locale' => $locale]);
        
        // route is unique always if no result was found
        if (null === $result) {
            return;
        }
        
        // skip validation if there is exact match
        if ($route instanceof Route && $result->getIdentifier()->getId() === $route->getIdentifier()->getId()) {
            return;
        }
        
        if ($this->context instanceof ExecutionContextInterface) {
            $this->context
                ->buildViolation($constraint->message)
                ->setParameter('{{ type }}', $this->formatValue($result->getType()))
                ->setParameter('{{ url }}', $this->generatePath($result))
                ->atPath('slug')
                ->setInvalidValue($slug)
                ->addViolation();
        }
    }
763407
public function duplicate(Entity $entity = null)
    {
        $entity = $this->getEntityIfEmpty($entity);

        $data = $this->toArray();
        if (isset($data['id'])) {
            unset($data['id']);
        }

        foreach ($data as $key => &$val) {
            if ($key && array_key_exists($key . '_x', $data) && array_key_exists($key . '_y', $data)) {
                $val = [
                    $data[$key . '_x'],
                    $data[$key . '_y'],
                ];
            }
        }

        $record = new static($data);
        $record->save($entity);

        return $record;
    }
968935
public function validator($entity, $data)
    {
        return ValidationManager::validator(self::getInstance()->getEntityStructure($entity), $data);
    }
333884
public function bindEntity($entity, $fields = null, $validatable = true)
    {
        if ($this->submitted) {
            throw new BadMethodCallException("Entities cannot be assigned after FormHandler::handleRequest has been called");
        }

        $this->entities[] = array('entity' => $entity, 'fields' => $fields, 'validatable' => $validatable);

        if ($entity instanceof EntityInterface) {
            $entityData = $entity->getFormData(array_keys($this->fields), $fields);
        } else {
            $entityData = $this->entityProcessor->getFromEntity($entity, array_keys($this->fields), $fields);
        }

        $entityData = $this->transformToFormData($entityData);

        $this->data = array_replace_recursive($this->data, $entityData);
    }