1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the Cubiche package. |
5
|
|
|
* |
6
|
|
|
* Copyright (c) Cubiche |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
namespace Cubiche\Core\Hashable; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Default Hash Coder class. |
15
|
|
|
* |
16
|
|
|
* @author Karel Osorio Ramírez <[email protected]> |
17
|
|
|
*/ |
18
|
|
|
class HashCoder implements HashCoderInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var HashCoderInterface |
22
|
|
|
*/ |
23
|
|
|
private static $default = null; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @return \Cubiche\Core\Hashable\HashCoderInterface |
27
|
|
|
*/ |
28
|
|
|
public static function defaultHashCoder() |
29
|
|
|
{ |
30
|
|
|
if (self::$default === null) { |
31
|
|
|
self::$default = new self(); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return self::$default; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param HashCoderInterface $hashCoder |
39
|
|
|
* @param HashCoderInterface $default |
40
|
|
|
* |
41
|
|
|
* @return \Cubiche\Core\Hashable\HashCoderInterface |
42
|
|
|
*/ |
43
|
|
|
public static function ensure(HashCoderInterface $hashCoder = null, HashCoderInterface $default = null) |
44
|
|
|
{ |
45
|
|
|
return $hashCoder !== null || $default !== null ? |
46
|
|
|
($hashCoder !== null ? $hashCoder : $default) : self::defaultHashCoder(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param mixed $value |
51
|
|
|
* |
52
|
|
|
* @return string |
53
|
|
|
*/ |
54
|
|
|
public static function defaultHashCode($value) |
55
|
|
|
{ |
56
|
|
|
if (\is_object($value)) { |
57
|
|
|
return \spl_object_hash($value); |
58
|
|
|
} elseif (\is_scalar($value) || \is_resource($value)) { |
59
|
|
|
return (string) $value; |
60
|
|
|
} elseif (\is_array($value)) { |
61
|
|
|
return \md5(\serialize($value)); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return '0'; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* {@inheritdoc} |
69
|
|
|
*/ |
70
|
|
|
public function hashCode($value) |
71
|
|
|
{ |
72
|
|
|
if ($value instanceof HashableInterface) { |
73
|
|
|
return $value->hashCode(); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return self::defaultHashCode($value); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|