1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakephp.org CakePHP(tm) Project
12: * @since 3.2.9
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\ORM\Rule;
16:
17: use Cake\Datasource\EntityInterface;
18: use Cake\Validation\Validation;
19: use Countable;
20:
21: /**
22: * Validates the count of associated records.
23: */
24: class ValidCount
25: {
26: /**
27: * The field to check
28: *
29: * @var string
30: */
31: protected $_field;
32:
33: /**
34: * Constructor.
35: *
36: * @param string $field The field to check the count on.
37: */
38: public function __construct($field)
39: {
40: $this->_field = $field;
41: }
42:
43: /**
44: * Performs the count check
45: *
46: * @param \Cake\Datasource\EntityInterface $entity The entity from where to extract the fields.
47: * @param array $options Options passed to the check.
48: * @return bool True if successful, else false.
49: */
50: public function __invoke(EntityInterface $entity, array $options)
51: {
52: $value = $entity->{$this->_field};
53: if (!is_array($value) && !$value instanceof Countable) {
54: return false;
55: }
56:
57: return Validation::comparison(count($value), $options['operator'], $options['count']);
58: }
59: }
60: