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: /**
28: * The field to check
29: *
30: * @var string
31: */
32: protected $_field;
33:
34: /**
35: * Constructor.
36: *
37: * @param string $field The field to check the count on.
38: */
39: public function __construct($field)
40: {
41: $this->_field = $field;
42: }
43:
44: /**
45: * Performs the count check
46: *
47: * @param \Cake\Datasource\EntityInterface $entity The entity from where to extract the fields.
48: * @param array $options Options passed to the check.
49: * @return bool True if successful, else false.
50: */
51: public function __invoke(EntityInterface $entity, array $options)
52: {
53: $value = $entity->{$this->_field};
54: if (!is_array($value) && !$value instanceof Countable) {
55: return false;
56: }
57:
58: return Validation::comparison(count($value), $options['operator'], $options['count']);
59: }
60: }
61: