Created
March 8, 2017 15:10
-
-
Save inoas/516b5132cae28441d07a20dab15e48c7 to your computer and use it in GitHub Desktop.
CakePHP3 IsUniqueInContextRule
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Model\Rule; | |
use Cake\Datasource\EntityInterface; | |
use Cake\ORM\TableRegistry; | |
/** | |
* Checks if a list of fields from an entity are unique in the table given a context where they can be duplicates | |
*/ | |
class IsUniqueInContext | |
{ | |
/** | |
* The list of fields to check | |
* | |
* @var array | |
*/ | |
protected $_fields; | |
/** | |
* The options to use. | |
* | |
* @var array | |
*/ | |
protected $_options; | |
/** | |
* Constructor. | |
* | |
* ### Options | |
* | |
* - `context` Set context list of fields in which duplications are okay. | |
* | |
* @param array $fields The list of fields to check uniqueness for | |
* @param array $options The additional options for this rule. | |
*/ | |
public function __construct(array $fields, array $options = []) | |
{ | |
$this->_fields = $fields; | |
$this->_options = $options + ['context' => []]; | |
$this->_options['context'] = (array)$this->_options['context']; | |
} | |
public function __invoke(EntityInterface $entity, array $options) | |
{ | |
$table = $options['repository']; | |
$query = $table->find(); | |
foreach ($this->_fields as $field) { | |
$query = $query->where([$field => $entity->get($field)]); | |
} | |
foreach ($this->_options['context'] as $contextField) { | |
$query = $query->where(['NOT' => [$contextField => $entity->get($contextField)]]); | |
} | |
$wouldBeUnique = $query->count() === 0; | |
return $wouldBeUnique; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment