1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the CMS Kernel package. |
5
|
|
|
* |
6
|
|
|
* Copyright (c) 2016-present LIN3S <[email protected]> |
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 LIN3S\CMSKernel\Application\DataTransformer\Menu; |
13
|
|
|
|
14
|
|
|
use LIN3S\CMSKernel\Application\DataTransformer\Translation\TranslationDTODataTransformer; |
15
|
|
|
use LIN3S\CMSKernel\Domain\Model\Menu\MenuTranslation; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @author Beñat Espiña <[email protected]> |
19
|
|
|
*/ |
20
|
|
|
class MenuTranslationDTODataTransformer extends TranslationDTODataTransformer |
21
|
|
|
{ |
22
|
|
|
private $menuItemDataTransformer; |
23
|
|
|
|
24
|
|
|
public function __construct(MenuItemDataTransformer $menuItemDataTransformer) |
25
|
|
|
{ |
26
|
|
|
$this->menuItemDataTransformer = $menuItemDataTransformer; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
protected function translationClass() |
30
|
|
|
{ |
31
|
|
|
return MenuTranslation::class; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
protected function serialize() |
35
|
|
|
{ |
36
|
|
|
return [ |
37
|
|
|
'name' => $this->translation->name()->name(), |
38
|
|
|
'tree' => $this->tree($this->translation->tree()), |
39
|
|
|
]; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
private function tree($items) |
43
|
|
|
{ |
44
|
|
|
$tree = []; |
45
|
|
|
|
46
|
|
|
// Create an associative array with each key being the ID of the item |
47
|
|
|
foreach ($items as &$item) { |
48
|
|
|
$this->menuItemDataTransformer->write($item); |
49
|
|
|
$item = $this->menuItemDataTransformer->read(); |
50
|
|
|
|
51
|
|
|
$tree[$item['id']] = &$item; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
// Loop over the array and add each child to their parent |
55
|
|
|
foreach ($tree as &$item) { |
56
|
|
|
if (!isset($item['parent_id'])) { |
57
|
|
|
continue; |
58
|
|
|
} |
59
|
|
|
$tree[$item['parent_id']]['children'][] = &$item; |
60
|
|
|
usort($tree[$item['parent_id']]['children'], [$this, 'sortByOrder']); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
// Loop over the array again and remove any items that don't have a parent of 0; |
64
|
|
|
foreach ($tree as $key => &$item) { |
65
|
|
|
if (!isset($item['parent_id'])) { |
66
|
|
|
continue; |
67
|
|
|
} |
68
|
|
|
unset($tree[$key]); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
// Sanitize the first level items |
72
|
|
|
$result = []; |
73
|
|
|
foreach ($tree as &$item) { |
74
|
|
|
$result[] = &$item['children'][0]; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
usort($result, [$this, 'sortByOrder']); |
78
|
|
|
|
79
|
|
|
return $result; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
private function sortByOrder($item1, $item2) |
83
|
|
|
{ |
84
|
|
|
if ($item1['order'] === $item2['order']) { |
85
|
|
|
return 0; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
return ($item1['order'] > $item2['order']) ? 1 : -1; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|