Completed
Push — master ( c2f76d...03586b )
by Freek
11:35
created

IsSorted   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 50
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A setHighestOrderNumber() 0 6 1
A getHighestOrderNumber() 0 4 1
A scopeOrdered() 0 4 1
A setNewOrder() 0 11 2
A determineOrderColumnName() 0 4 1
A shouldSortWhenCreating() 0 4 1
1
<?php
2
3
namespace Spatie\MediaLibrary\Models\Concerns;
4
5
use Illuminate\Database\Eloquent\Builder;
6
7
trait IsSorted
8
{
9
    public function setHighestOrderNumber()
10
    {
11
        $orderColumnName = $this->determineOrderColumnName();
12
13
        $this->$orderColumnName = $this->getHighestOrderNumber() + 1;
14
    }
15
16
    public function getHighestOrderNumber(): int
17
    {
18
        return (int) static::max($this->determineOrderColumnName());
19
    }
20
21
    public function scopeOrdered(Builder $query): Builder
22
    {
23
        return $query->orderBy($this->determineOrderColumnName());
0 ignored issues
show
Bug introduced by
The method orderBy() does not exist on Illuminate\Database\Eloquent\Builder. Did you maybe mean enforceOrderBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
24
    }
25
26
    /**
27
     * This function reorders the records: the record with the first id in the array
28
     * will get order 1, the record with the second it will get order 2, ...
29
     *
30
     * A starting order number can be optionally supplied (defaults to 1).
31
     *
32
     * @param array $ids
33
     * @param int   $startOrder
34
     */
35
    public static function setNewOrder(array $ids, int $startOrder = 1)
36
    {
37
        foreach ($ids as $id) {
38
            $model = static::find($id);
39
40
            $orderColumnName = $model->determineOrderColumnName();
41
42
            $model->$orderColumnName = $startOrder++;
43
            $model->save();
44
        }
45
    }
46
47
    protected function determineOrderColumnName(): string
48
    {
49
        return $this->sortable['order_column_name'] ?? 'order_column';
50
    }
51
52
    public function shouldSortWhenCreating(): bool
53
    {
54
        return $this->sortable['sort_when_creating'] ?? true;
55
    }
56
}
57