|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace MaksimM\CompositePrimaryKeys\Http\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
7
|
|
|
use MaksimM\CompositePrimaryKeys\Exceptions\WrongKeyException; |
|
8
|
|
|
|
|
9
|
|
|
trait NormalizedKeysParser |
|
10
|
|
|
{ |
|
11
|
|
|
protected $magicKeyDelimiter = '___'; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Get key-value array from normalized key. |
|
15
|
|
|
* |
|
16
|
|
|
* @param $normalizedKey |
|
17
|
|
|
* |
|
18
|
|
|
* @throws WrongKeyException |
|
19
|
|
|
* |
|
20
|
|
|
* @return array |
|
21
|
|
|
*/ |
|
22
|
|
|
public function parseNormalizedKey($normalizedKey) |
|
23
|
|
|
{ |
|
24
|
|
|
$parsedKeys = explode($this->magicKeyDelimiter, $normalizedKey); |
|
25
|
|
|
$keys = $this instanceof Model ? $this->getRawKeyName() : $this->key; |
|
26
|
|
|
foreach ($keys as $index => $key) { |
|
27
|
|
|
$keys[$key] = in_array($key, $this->getBinaryColumns()) ? $this->recoverBinaryKey($key, $parsedKeys[$index]) : $parsedKeys[$index]; |
|
|
|
|
|
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
return $keys; |
|
|
|
|
|
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Get normalized key. |
|
35
|
|
|
* |
|
36
|
|
|
* @return string |
|
37
|
|
|
*/ |
|
38
|
|
|
private function getNormalizedKeyName() |
|
39
|
|
|
{ |
|
40
|
|
|
return implode($this->magicKeyDelimiter, array_merge($this->getRawKeyName())); |
|
|
|
|
|
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Get normalized key. |
|
45
|
|
|
* |
|
46
|
|
|
* @return string |
|
47
|
|
|
*/ |
|
48
|
|
|
private function getNormalizedKey() |
|
49
|
|
|
{ |
|
50
|
|
|
$rawKeys = $this->getRawKey(); |
|
|
|
|
|
|
51
|
|
|
|
|
52
|
|
|
//do not normalize single key because we couldn't detect its type |
|
53
|
|
|
if (count($rawKeys) > 1) { |
|
54
|
|
|
foreach ($rawKeys as $key => $value) { |
|
55
|
|
|
if (in_array($key, $this->getBinaryColumns()) && !$this->hexBinaryColumns()) { |
|
|
|
|
|
|
56
|
|
|
$rawKeys[$key] = strtoupper(bin2hex($value)); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
return implode($this->magicKeyDelimiter, $rawKeys); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @param $key |
|
66
|
|
|
* @param $hexValue |
|
67
|
|
|
* |
|
68
|
|
|
* @throws WrongKeyException |
|
69
|
|
|
* |
|
70
|
|
|
* @return bool|string |
|
71
|
|
|
*/ |
|
72
|
|
|
public function recoverBinaryKey($key, $hexValue) |
|
73
|
|
|
{ |
|
74
|
|
|
try { |
|
75
|
|
|
return hex2bin($hexValue); |
|
76
|
|
|
} catch (Exception $exception) { |
|
77
|
|
|
throw new WrongKeyException("$key has invalid hex value"); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|