Skip to content

Instantly share code, notes, and snippets.

@inoas
Created March 8, 2017 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inoas/516b5132cae28441d07a20dab15e48c7 to your computer and use it in GitHub Desktop.
Save inoas/516b5132cae28441d07a20dab15e48c7 to your computer and use it in GitHub Desktop.
CakePHP3 IsUniqueInContextRule
<?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