Skip to content

Instantly share code, notes, and snippets.

@stibiumz
Last active August 29, 2015 14:19
Show Gist options
  • Save stibiumz/7d92ed9ebb33ff67d656 to your computer and use it in GitHub Desktop.
Save stibiumz/7d92ed9ebb33ff67d656 to your computer and use it in GitHub Desktop.
<?php
use Phalcon\Db\RawValue,
Phalcon\Mvc\Model\Message,
Phalcon\Mvc\Model\Relation;
abstract class Model extends \Phalcon\Mvc\Model {
/**
* @see https://github.com/phalcon/cphalcon/issues/2039
*/
protected function _checkForeignKeysRestrict() {
$manager = $this->_modelsManager;
$belongsTo = $manager->getBelongsTo($this);
if (! empty ($belongsTo)) {
$nullFields = array_flip(array_diff(
$this->getModelsMetaData()->getAttributes($this),
$this->getModelsMetaData()->getNotNullAttributes($this)
));
$isNotNullFk = function ($field, $value) use ($nullFields) {
if (isset ($nullFields[$field]) && (
$value === NULL ||
($value instanceof RawValue && strtolower($value) === 'null'))) {
return FALSE;
}
return TRUE;
};
foreach ($belongsTo as $relation) {
$foreignKey = $relation->getForeignKey();
$action = $foreignKey !== FALSE;
if ($action && is_array($foreignKey) && isset ($foreignKey['action'])) {
$action = $foreignKey['action'] === Relation::ACTION_RESTRICT;
}
if ($action) {
$conditions = [];
$bindParams = [];
$fields = $relation->getFields();
$referencedFields = $relation->getReferencedFields();
if (is_array($fields)) {
foreach ($fields as $position => $field) {
if ($isNotNullFk($field, $this->{$field})) {
$conditions[] = '[' . $referencedFields[$position] . '] = ?' . $position;
$bindParams[] = $this->{$field};
}
}
}
else if ($isNotNullFk($fields, $this->{$fields})) {
$conditions[] = '[' . $referencedFields . '] = ?0';
$bindParams[] = $this->{$fields};
}
if (isset ($foreignKey['conditions'])) {
$conditions[] = $foreignKey['conditions'];
}
if ($conditions === []) {
continue;
}
if (! $manager->load($relation->getReferencedModel())->count([join(' AND ', $conditions), 'bind' => $bindParams])) {
if (! isset ($foreignKey['message'])) {
if (is_array($fields)) {
$message = 'Value of fields "' . join(', ', $fields) . '" does not exist on referenced table';
}
else {
$message = 'Value of field "' . $fields . '" does not exist on referenced table';
}
}
else {
$message = $foreignKey['message'];
}
$this->appendMessage(new Message($message, $fields, 'ConstraintViolation'));
if (ini_get('phalcon.orm.events')) {
$this->fireEvent('onValidationFails');
$this->_cancelOperation();
}
return FALSE;
}
}
}
}
return TRUE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment