Debian Codegraph @

vendor/wikimedia/equivset/src/Equivset.php

raw
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 */
18
19 namespace Wikimedia\Equivset;
20
21 use ArrayIterator;
22 use IteratorAggregate;
23 use LogicException;
24
25 /**
26 * Default Equivset
27 */
28 class Equivset implements EquivsetInterface, IteratorAggregate {
29
30 /**
31 * @var array<string,string>
32 */
33 protected array $data;
34
35 protected string $dataPath;
36
37 /**
38 * @param array<string,string> $data Equivalent Set
39 * @param string $dataPath Path of the equivset array.
40 */
41 public function __construct( array $data = [], string $dataPath = '' ) {
42 $this->data = $data;
43 $this->dataPath = $dataPath ?: __DIR__ . '/../dist/equivset.php';
44 }
45
46 /** {@inheritdoc} */
47 public function all(): array {
48 if ( !$this->data ) {
49 $this->data = $this->load();
50 }
51
52 return $this->data;
53 }
54
55 /** {@inheritdoc} */
56 public function normalize( string $value ): string {
57 $data = $this->all();
58
59 return strtr( $value, $data );
60 }
61
62 /** {@inheritdoc} */
63 public function isEqual( string $str1, string $str2 ): bool {
64 return $this->normalize( $str1 ) === $this->normalize( $str2 );
65 }
66
67 /** {@inheritdoc} */
68 public function has( string $key ): bool {
69 $data = $this->all();
70
71 return array_key_exists( $key, $data );
72 }
73
74 /** {@inheritdoc} */
75 public function get( string $key ): string {
76 $data = $this->all();
77
78 if ( !array_key_exists( $key, $data ) ) {
79 throw new LogicException( 'Equivalent Character Not Found' );
80 }
81
82 return $data[$key];
83 }
84
85 /** {@inheritdoc} */
86 public function getIterator(): ArrayIterator {
87 return new ArrayIterator( $this->all() );
88 }
89
90 /**
91 * Get the equivset.
92 *
93 * @return array<string,string> An associative array of equivalent characters.
94 */
95 protected function load(): array {
96 // This will naturally throw if the file does not exist, is not readable,
97 // or can't be parsed.
98 return require $this->dataPath;
99 }
100 }