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.0.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\View\Helper;
16:
17: use Cake\Utility\Text;
18:
19: /**
20: * A trait that provides id generating methods to be
21: * used in various widget classes.
22: */
23: trait IdGeneratorTrait
24: {
25: /**
26: * Prefix for id attribute.
27: *
28: * @var string|null
29: */
30: protected $_idPrefix;
31:
32: /**
33: * A list of id suffixes used in the current rendering.
34: *
35: * @var string[]
36: */
37: protected $_idSuffixes = [];
38:
39: /**
40: * Clear the stored ID suffixes.
41: *
42: * @return void
43: */
44: protected function _clearIds()
45: {
46: $this->_idSuffixes = [];
47: }
48:
49: /**
50: * Generate an ID attribute for an element.
51: *
52: * Ensures that id's for a given set of fields are unique.
53: *
54: * @param string $name The ID attribute name.
55: * @param string $val The ID attribute value.
56: * @return string Generated id.
57: */
58: protected function _id($name, $val)
59: {
60: $name = $this->_domId($name);
61: $suffix = $this->_idSuffix($val);
62:
63: return trim($name . '-' . $suffix, '-');
64: }
65:
66: /**
67: * Generate an ID suffix.
68: *
69: * Ensures that id's for a given set of fields are unique.
70: *
71: * @param string $val The ID attribute value.
72: * @return string Generated id suffix.
73: */
74: protected function _idSuffix($val)
75: {
76: $idSuffix = mb_strtolower(str_replace(['/', '@', '<', '>', ' ', '"', '\''], '-', $val));
77: $count = 1;
78: $check = $idSuffix;
79: while (in_array($check, $this->_idSuffixes)) {
80: $check = $idSuffix . $count++;
81: }
82: $this->_idSuffixes[] = $check;
83:
84: return $check;
85: }
86:
87: /**
88: * Generate an ID suitable for use in an ID attribute.
89: *
90: * @param string $value The value to convert into an ID.
91: * @return string The generated id.
92: */
93: protected function _domId($value)
94: {
95: $domId = mb_strtolower(Text::slug($value, '-'));
96: if ($this->_idPrefix) {
97: $domId = $this->_idPrefix . '-' . $domId;
98: }
99:
100: return $domId;
101: }
102: }
103: