Conditions | 5 |
Paths | 6 |
Total Lines | 54 |
Code Lines | 32 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
32 | public function reorder($elementToBeAfterID = 0) |
||
33 | { |
||
34 | $element = $this->element; |
||
35 | $parentId = $element->ParentID; |
||
|
|||
36 | $currentPosition = (int) $element->Sort; |
||
37 | $sortAfterPosition = 0; |
||
38 | |||
39 | if ($elementToBeAfterID) { |
||
40 | /** @var BaseElement $afterBlock */ |
||
41 | $afterElement = BaseElement::get()->byID($elementToBeAfterID); |
||
42 | |||
43 | if (!$afterElement) { |
||
44 | throw new InvalidArgumentException(sprintf( |
||
45 | '%s#%s not found', |
||
46 | BaseElement::class, |
||
47 | $elementToBeAfterID |
||
48 | )); |
||
49 | } |
||
50 | |||
51 | if ($afterElement->ParentID !== $parentId) { |
||
52 | throw new InvalidArgumentException( |
||
53 | 'Trying to sort element to be placed after an element from a different elemental area' |
||
54 | ); |
||
55 | } |
||
56 | |||
57 | $sortAfterPosition = (int) $afterElement->Sort; |
||
58 | } |
||
59 | |||
60 | // We are updating records with SQL queries to avoid the ORM triggering the creation of new versions |
||
61 | // for each element that is affected by this reordering. |
||
62 | $tableName = Convert::raw2sql(DataObject::getSchema()->tableName(BaseElement::class)); |
||
63 | |||
64 | if ($sortAfterPosition < $currentPosition) { |
||
65 | $operator = '+'; |
||
66 | $filter = "\"$tableName\".\"Sort\" > $sortAfterPosition AND \"$tableName\".\"Sort\" < $currentPosition"; |
||
67 | $newBlockPosition = $sortAfterPosition + 1; |
||
68 | } else { |
||
69 | $operator = '-'; |
||
70 | $filter = "\"$tableName\".\"Sort\" <= $sortAfterPosition AND \"$tableName\".\"Sort\" > $currentPosition"; |
||
71 | $newBlockPosition = $sortAfterPosition; |
||
72 | } |
||
73 | |||
74 | $query = SQLUpdate::create() |
||
75 | ->setTable("\"$tableName\"") |
||
76 | ->assignSQL('"Sort"', "\"$tableName\".\"Sort\" $operator 1") |
||
77 | ->addWhere([$filter, "\"$tableName\".\"ParentID\"" => $parentId]); |
||
78 | |||
79 | $query->execute(); |
||
80 | |||
81 | // Now use the ORM to write a new version of the record that we are directly reordering |
||
82 | $element->Sort = $newBlockPosition; |
||
83 | $element->write(); |
||
84 | |||
85 | return $element; |
||
86 | } |
||
88 |