Triggers before/after validate events.

@param \Cake\Datasource\EntityInterface $entity The entity being validated
@return bool True if save operation should continue, false otherwise
177492
protected function _validation(EntityInterface $entity)
    {
        $validator = new Validator();
        $hasErrors = false;

        foreach ($this->_attributesForEntity($entity) as $attr) {
            $field = $this->_prepareMockField($entity, $attr);
            $result = $field->validate($validator);

            if ($result === false) {
                $this->attachEntityFields($entity);

                return false;
            }

            $errors = $validator->errors($entity->toArray(), $entity->isNew());
            $entity->errors($errors);

            if (!empty($errors)) {
                $hasErrors = true;
                if ($entity->has('_fields')) {
                    $entityErrors = $entity->errors();
                    foreach ($entity->get('_fields') as $field) {
                        $postData = $entity->get($field->name);
                        if (!empty($entityErrors[$field->name])) {
                            $field->set('value', $postData);
                            $field->metadata->set('errors', (array)$entityErrors[$field->name]);
                        }
                    }
                }
            }
        }

        return !$hasErrors;
    }
4784
public function validate($entity)
    {
        //reset the error message
        $context = $this->getCommandContext();
        $context->entity = $entity;
        if ($entity->isValidatable()) {
            $entity->resetErrors();
        }
        $result = $this->getCommandChain()->run('on.validate', $context);

        return $result !== false;
    }
95061
public function updateEavCache(EntityInterface $entity)
    {
        if (!$this->config('cacheMap')) {
            return false;
        }

        $attrsById = [];
        foreach ($this->_toolbox->attributes() as $attr) {
            $attrsById[$attr['id']] = $attr;
        }

        if (empty($attrsById)) {
            return true; // nothing to cache
        }

        $query = TableRegistry::get('Eav.EavValues')
            ->find('all')
            ->where([
                'EavValues.eav_attribute_id IN' => array_keys($attrsById),
                'EavValues.entity_id' => $this->_toolbox->getEntityId($entity),
            ])
            ->toArray();

        $values = [];
        foreach ($query as $v) {
            $type = $attrsById[$v->get('eav_attribute_id')]->get('type');
            $name = $attrsById[$v->get('eav_attribute_id')]->get('name');
            $values[$name] = $this->_toolbox->marshal($v->get("value_{$type}"), $type);
        }

        $toUpdate = [];
        foreach ((array)$this->config('cacheMap') as $column => $fields) {
            $cache = [];
            if (in_array('*', $fields)) {
                $cache = $values;
            } else {
                foreach ($fields as $field) {
                    if (isset($values[$field])) {
                        $cache[$field] = $values[$field];
                    }
                }
            }

            $toUpdate[$column] = (string)serialize(new CachedColumn($cache));
        }

        if (!empty($toUpdate)) {
            $conditions = []; // scope to entity's PK (composed PK supported)
            $keys = $this->_table->primaryKey();
            $keys = !is_array($keys) ? [$keys] : $keys;
            foreach ($keys as $key) {
                // TO-DO: check key exists in entity's visible properties list.
                // Throw an error otherwise as PK MUST be correctly calculated.
                $conditions[$key] = $entity->get($key);
            }

            if (empty($conditions)) {
                return false;
            }

            return (bool)$this->_table->updateAll($toUpdate, $conditions);
        }

        return true;
    }
573607
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) {
		$this->processItems($entity, 'input');
	}
1212077
public function isEqualTo(EntityInterface $entity)
    {
        if ($entity->getType() !== $this->getType()) {
            return false;
        }

        if ($this->getType()->getAttributes()->getSize() !== $this->value_holder_map->getSize()) {
            return false;
        }

        foreach ($this->getType()->getAttributes()->getKeys() as $attribute_name) {
            $value_holder = $this->value_holder_map->getItem($attribute_name);
            if (!$value_holder->sameValueAs($entity->getValue($attribute_name))) {
                return false;
            }
        }

        return true;
    }
286809
public function validate(EntityInterface $entity)
    {
        if (!$entity instanceof Attribution) {
            throw new Exception(
                sprintf('The Entity to validate must be an instance of %s', Attribution::class)
            );
        }

        $this->validateSource($entity->getSource());
        $this->validateTarget($entity->getTarget());
        $this->validateRole($entity->getRole());
        $errors = $this->getErrors();

        return empty($errors);
    }
306712
protected function removeEntity(EntityInterface $entity)
    {
        Orm::getRepository($this->getEntityClassName())
            ->getIdentityMap()
            ->remove($entity);
    }
172363
protected function triggerDelete(
        EntityInterface $entity, $action = Delete::ACTION_BEFORE_DELETE
    ) {
        $event = new Delete($entity);
        $event->setAction($action);
        return Orm::getEmitter($this->getEntityClassName())
            ->emit($event);
    }
632851
public function delete(EntityInterface $entity)
    {
        $this->entity = $entity;
        $primaryKey = $this->getDescriptor()->getPrimaryKey()->getName();
        $table = $this->getDescriptor()->getTableName();
        $sql = Sql::createSql($this->getAdapter());

        $this->triggerBeforeDelete($entity);

        $this->setUpdateCriteria(
            $sql->delete($table),
            $primaryKey,
            $table
        )->execute();

        $this->triggerAfterDelete($entity);
        $this->removeEntity($entity);
        return $this;
    }
468581
public function beforeSave(Event $event, EntityInterface $entity, \ArrayObject $options): void
    {
        if (!$entity->isNew() && $entity->dirty()) {
            $saveHash = Security::hash(md5(uniqid()));
            if (empty($entity->save_hash)) {
                $entity->save_hash = $saveHash;
                $entity->dirty('save_hash', false);
            }

            $this->_dirtyFields[$entity->id] = $this->_extractDirtyFields($entity);
            $this->_applySaveHash($entity, $saveHash);
        }
    }
943935
public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options)
    {
        if (!$this->config('status')) {
            return true;
        }

        // as we don't know entity's ID on beforeSave, we must delay values storage;
        // all this occurs inside a transaction so we are safe
        if (!empty($this->_cache['createValues'])) {
            foreach ($this->_cache['createValues'] as $valueEntity) {
                $valueEntity->set('entity_id', $this->_toolbox->getEntityId($entity));
                $valueEntity->unsetProperty('id');
                TableRegistry::get('Eav.EavValues')->save($valueEntity);
            }
            $this->_cache['createValues'] = [];
        }

        foreach ($this->_attributesForEntity($entity) as $attr) {
            $field = $this->_prepareMockField($entity, $attr);
            $field->afterSave();
        }

        if ($this->config('cacheMap')) {
            $this->updateEavCache($entity);
        }

        return true;
    }
813201
public function validate(EntityInterface $record) {
        $fields = $this->getOption('fields');
        $sql = '1';
        $params = array();
        //Don't check the current object, so add a not on the primary keys
        $primaryKeys = $record->getModelsMetaData()->getPrimaryKeyAttributes($record);
        $columnMap = $record->getModelsMetaData()->getColumnMap($record);
        //Check to see if all of the values are still null
        $someValuesNotNull = false;
        foreach($primaryKeys as $i => $primaryKey) {
            $field = $columnMap[$primaryKey]; //Get shortened version
            $value = $record->readAttribute($field);
            if(!is_null($value)) {
                $someValuesNotNull = true;
            }
        }
        if($someValuesNotNull) {
            $sql .= ' AND NOT (';
            foreach($primaryKeys as $i => $primaryKey) {
                $field = $columnMap[$primaryKey]; //Get shortened version
                $value = $record->readAttribute($field);
                if($i != 0) {
                    $sql .= ' AND';
                }
                $paramKey = sizeOf($params);
                $sql .= ' ' . $field . '=?' . $paramKey;
                $params[] = $value;
            }
            $sql .= ')';
        }
        //Add each field
        foreach($fields as $field) {
            $paramKey = sizeOf($params);
            $value = $record->readAttribute($field);
            $sql .= ' AND ' . $field . '=?' . $paramKey;
            $params[] = $value;
        }
        /** @var ResultSet $resultSet */
        $resultSet = $record->find(
            [
                'conditions' => $sql,
                'bind' => $params,
                'limit' => 1
            ]
        );
        //If one is found, give an
        if($resultSet->count() == 0) {
            return true;
        } else {
            $this->appendMessage($this->getOption('message'));
            return false;
        }

    }
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);
    }
26294
public function validate(EntityInterface $entity)
    {
        if (!$entity instanceof User) {
            throw new Exception(
                sprintf('The Entity to validate must be an instance of %s', User::class)
            );
        }

        $this->validateUserName($entity->getUserName());
        $this->validateFirstName($entity->getFirstName());
        $this->validateLastName($entity->getLastName());
        $this->validateEmail($entity->getEmail());
        $this->validateCreatedAt($entity->getCreatedAt());
        $this->validatePassword($entity->getPassword());
        $this->validateStatus($entity->getStatus());
        $this->validateRegisterToken($entity->getStatus());
        $this->validateAvatarUrl($entity->getAvatarUrl());
        $this->validateAvatarUrl($entity->getMiniAvatarUrl());
        $this->validateLanguage($entity->getLanguage());
        $errors = $this->getErrors();

        return empty($errors);
    }
831544
public function save(SaveEntityInterface $entity)
    {
        $entity = $this->persist($entity);
        $this->flush();

        return $entity;
    }
397983
public function insert(EntityInterface $entity)
	{
		$sql = <<<EOT
INSERT INTO `$this->tableName` (`Name`, `Description`, `Created`) 
VALUES ( :name , :description , :created )
EOT;

		$stmt = $this->pdo->prepare($sql);
		$stmt->bindParam(':name', $entity->getName(), \PDO::PARAM_STR);
		$stmt->bindParam(':description', $entity->getDescription(), \PDO::PARAM_STR);
		$stmt->bindParam(':created', $entity->getCreatedRfc3339(), \PDO::PARAM_STR);
		$res = $stmt->execute();

		if ($res === false || $stmt->rowCount() !== 1) {
			return false;
		}

		$entity->setProjectId($this->pdo->lastInsertId());

		return $entity;
	}
579214
protected function _beforeLogin(EntityInterface $entity, array $options) {
		$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->getData(), ['validate' => false]);

		$event = $this->dispatchEvent('User.beforeLogin', [
			'options' => $options,
			'entity' => $entity
		]);

		if ($event->isStopped()) {
			return $event->result;
		}

		return $this->_getAuthObject()->identify();
	}