|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* Copyright 2016 Johannes M. Schmitt <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
|
9
|
|
|
* you may not use this file except in compliance with the License. |
|
10
|
|
|
* You may obtain a copy of the License at |
|
11
|
|
|
* |
|
12
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
|
13
|
|
|
* |
|
14
|
|
|
* Unless required by applicable law or agreed to in writing, software |
|
15
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
|
16
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
17
|
|
|
* See the License for the specific language governing permissions and |
|
18
|
|
|
* limitations under the License. |
|
19
|
|
|
*/ |
|
20
|
|
|
|
|
21
|
|
|
namespace JMS\Serializer\Ordering; |
|
22
|
|
|
|
|
23
|
|
|
final class CustomPropertyOrderingStrategy implements PropertyOrderingInterface |
|
24
|
|
|
{ |
|
25
|
|
|
/** @var int[] property => weight */ |
|
26
|
|
|
private $ordering; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @param int[] $ordering property => weight |
|
30
|
|
|
*/ |
|
31
|
34 |
|
public function __construct(array $ordering) |
|
32
|
|
|
{ |
|
33
|
34 |
|
$this->ordering = $ordering; |
|
34
|
34 |
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* {@inheritdoc} |
|
38
|
|
|
*/ |
|
39
|
34 |
|
public function order(array $properties) : array |
|
40
|
|
|
{ |
|
41
|
34 |
|
$currentSorting = $properties ? array_combine(array_keys($properties), range(1, \count($properties))) : []; |
|
42
|
|
|
|
|
43
|
|
|
uksort($properties, function ($a, $b) use ($currentSorting) { |
|
44
|
34 |
|
$existsA = isset($this->ordering[$a]); |
|
45
|
34 |
|
$existsB = isset($this->ordering[$b]); |
|
46
|
|
|
|
|
47
|
34 |
|
if (!$existsA && !$existsB) { |
|
48
|
4 |
|
return $currentSorting[$a] - $currentSorting[$b]; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
33 |
|
if (!$existsA) { |
|
52
|
4 |
|
return 1; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
29 |
|
if (!$existsB) { |
|
56
|
1 |
|
return -1; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
28 |
|
return $this->ordering[$a] < $this->ordering[$b] ? -1 : 1; |
|
60
|
34 |
|
}); |
|
61
|
|
|
|
|
62
|
34 |
|
return $properties; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|