1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sludio\HelperBundle\Position\Service; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\Util\ClassUtils; |
6
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
7
|
|
|
|
8
|
|
|
class PositionHandler |
9
|
|
|
{ |
10
|
|
|
protected $positionField; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @var EntityManagerInterface |
14
|
|
|
*/ |
15
|
|
|
protected $entityManager; |
16
|
|
|
|
17
|
|
|
public function __construct(EntityManagerInterface $entityManager) |
18
|
|
|
{ |
19
|
|
|
$this->entityManager = $entityManager; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function getLastPosition($entity) |
23
|
|
|
{ |
24
|
|
|
$query = $this->entityManager->createQuery(sprintf('SELECT MAX(m.%s) FROM %s m', $positionFiles = $this->getPositionFieldByEntity($entity), $entity)); |
25
|
|
|
$result = $query->getResult(); |
26
|
|
|
|
27
|
|
|
if (array_key_exists(0, $result)) { |
28
|
|
|
return intval($result[0][1]); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
return 0; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param mixed $positionField |
36
|
|
|
*/ |
37
|
|
|
public function setPositionField($positionField) |
38
|
|
|
{ |
39
|
|
|
$this->positionField = $positionField; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param $entity |
44
|
|
|
* |
45
|
|
|
* @return string |
46
|
|
|
*/ |
47
|
|
|
public function getPositionFieldByEntity($entity) |
48
|
|
|
{ |
49
|
|
|
if (is_object($entity)) { |
50
|
|
|
$entity = ClassUtils::getClass($entity); |
51
|
|
|
} |
52
|
|
|
if (isset($this->positionField['entities'][$entity])) { |
53
|
|
|
return $this->positionField['entities'][$entity]; |
54
|
|
|
} else { |
55
|
|
|
return $this->positionField['default']; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function sludioUp($actual) |
60
|
|
|
{ |
61
|
|
|
if ($actual > 0) { |
62
|
|
|
return $actual - 1; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
private function sludioDown($actual, $last) |
67
|
|
|
{ |
68
|
|
|
if ($actual < $last) { |
69
|
|
|
return $actual + 1; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
private function sludioTop($actual) |
74
|
|
|
{ |
75
|
|
|
if ($actual > 0) { |
76
|
|
|
return 0; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
private function sludioBottom($actual, $last) |
81
|
|
|
{ |
82
|
|
|
if ($actual < $last) { |
83
|
|
|
return $last; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* @param $object |
89
|
|
|
* @param $position |
90
|
|
|
* @param $lastPosition |
91
|
|
|
* |
92
|
|
|
* @return int |
93
|
|
|
*/ |
94
|
|
|
public function getPosition($object, $position, $lastPosition) |
95
|
|
|
{ |
96
|
|
|
$getter = sprintf('get%s', ucfirst($this->getPositionFieldByEntity($object))); |
97
|
|
|
$result = $this->{'sludio'.ucfirst($position)}($object->{$getter}(), $lastPosition); |
98
|
|
|
|
99
|
|
|
return $result === null ? 0 : $result; |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|