1+ <?php
2+ /*
3+ * This file is part of Fusonic-linq.
4+ * https://github.com/fusonic/fusonic-linq
5+ *
6+ * (c) Fusonic GmbH
7+ *
8+ * For the full copyright and license information, please view the LICENSE
9+ * file that was distributed with this source code.
10+ */
11+
12+ namespace Fusonic \Linq \Helper ;
13+
14+
15+ class Set
16+ {
17+ private $ objects = array ();
18+
19+ /**
20+ * If the value is not in the set, it will be added and true is returned. otherwise false is returned.
21+ * @return bool
22+ */
23+ public function add ($ value )
24+ {
25+ return !$ this ->find ($ value , true );
26+ }
27+
28+ /**
29+ * If the value is in the set, it will be removed and true is returned. otherwise false is returned.
30+ * @param $value
31+ * @return bool
32+ */
33+ public function remove ($ value )
34+ {
35+ $ hash = self ::hash ($ value );
36+ if (array_key_exists ($ hash , $ this ->objects )) {
37+ unset($ this ->objects [$ hash ]);
38+ return true ;
39+ }
40+ return false ;
41+ }
42+
43+ /**
44+ * Returns true if the value exist in the set. Otherwise false.
45+ * @return bool
46+ */
47+ public function contains ($ value )
48+ {
49+ $ hash = self ::hash ($ value );
50+ return array_key_exists ($ hash , $ this ->objects );
51+ }
52+
53+ // Finds the given value and returns true if it was found. Otherwise return false.
54+ private function find ($ value , $ add = false )
55+ {
56+ $ hash = self ::hash ($ value );
57+ if (array_key_exists ($ hash , $ this ->objects )) {
58+ return true ;
59+ }
60+ else if ($ add ) {
61+ $ this ->objects [$ hash ] = $ value ;
62+ }
63+ return false ;
64+ }
65+
66+ private static function hash ($ value )
67+ {
68+ if (is_object ($ value )) {
69+ return spl_object_hash ($ value );
70+ } elseif (is_scalar ($ value )) {
71+ return "s_ $ value " ;
72+ } elseif (is_array ($ value )) {
73+ return 'a_ ' . md5 (json_encode ($ value ));
74+ } else if ($ value === null ) {
75+ return null ;
76+ }
77+ else throw new \InvalidArgumentException ("Value type is not supported. " );
78+ }
79+ }
0 commit comments