<?php
namespace Moto\Validator; class Unique extends AbstractValidator { const ERROR_NOT_UNIQUE = 'notUnique'; const BROKEN_SCHEMA = 'brokenSchema'; protected $messageTemplates = array( self::ERROR_NOT_UNIQUE => "Column '%key%' is not unique", self::BROKEN_SCHEMA => 'Broken request schema', ); protected $messageVariables = array( 'key' => '_key' ); protected $_key; protected $_defaultOptions = array( 'key' => 'id' ); public function isValid($list, array $context = array()) { $this->setValue($list); $this->_key = $this->getOption('key'); if (!is_array($list)) { $this->error(self::BROKEN_SCHEMA); return false; } if (empty($list)) { return true; } $arrayOfKeys = array(); foreach($list as $item) { if (!is_array($list) || !array_key_exists($this->_key, $item)) { $this->error(self::BROKEN_SCHEMA); return false; } $arrayOfKeys[] = $item[$this->_key]; } $arrayUnique = array_unique($arrayOfKeys); $isValid = count($arrayUnique) == count($arrayOfKeys); if (!$isValid) { $this->error(self::ERROR_NOT_UNIQUE); } return $isValid; } }