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: /**
27: * Prefix for id attribute.
28: *
29: * @var string|null
30: */
31: protected $_idPrefix;
32:
33: /**
34: * A list of id suffixes used in the current rendering.
35: *
36: * @var array
37: */
38: protected $_idSuffixes = [];
39:
40: /**
41: * Clear the stored ID suffixes.
42: *
43: * @return void
44: */
45: protected function _clearIds()
46: {
47: $this->_idSuffixes = [];
48: }
49:
50: /**
51: * Generate an ID attribute for an element.
52: *
53: * Ensures that id's for a given set of fields are unique.
54: *
55: * @param string $name The ID attribute name.
56: * @param string $val The ID attribute value.
57: * @return string Generated id.
58: */
59: protected function _id($name, $val)
60: {
61: $name = $this->_domId($name);
62:
63: $idSuffix = mb_strtolower(str_replace(['/', '@', '<', '>', ' ', '"', '\''], '-', $val));
64: $count = 1;
65: $check = $idSuffix;
66: while (in_array($check, $this->_idSuffixes)) {
67: $check = $idSuffix . $count++;
68: }
69: $this->_idSuffixes[] = $check;
70:
71: return trim($name . '-' . $check, '-');
72: }
73:
74: /**
75: * Generate an ID suitable for use in an ID attribute.
76: *
77: * @param string $value The value to convert into an ID.
78: * @return string The generated id.
79: */
80: protected function _domId($value)
81: {
82: $domId = mb_strtolower(Text::slug($value, '-'));
83: if ($this->_idPrefix) {
84: $domId = $this->_idPrefix . '-' . $domId;
85: }
86:
87: return $domId;
88: }
89: }
90: