DocumentSorter   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 44
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A sortDocumentsByField() 0 9 3
A fieldCompare() 0 15 4
1
<?php
2
/**
3
 * Created by jensk on 23-4-2018.
4
 */
5
6
namespace CloudControl\Cms\util;
7
8
9
use CloudControl\Cms\storage\entities\Document;
10
11
class DocumentSorter
12
{
13
    protected static $orderByField;
14
    protected static $order = 'ASC';
15
16
    /**
17
     * Sorts an array of Document instances
18
     * @param array $documents
19
     * @param string $field
20
     * @param string $order
21
     * @return array
22
     */
23
    public static function sortDocumentsByField($documents, $field, $order = 'ASC')
24
    {
25
        self::$orderByField = $field;
26
        self::$order = strtoupper($order) === 'ASC' ? 'ASC' : 'DESC';
27
        usort($documents, '\CloudControl\Cms\util\DocumentSorter::fieldCompare');
28
        if ($order === 'DESC') {
29
            return array_reverse($documents);
30
        }
31
        return $documents;
32
    }
33
34
    /**
35
     * Compares two documents
36
     * @param Document $a
37
     * @param Document $b
38
     * @return int
39
     */
40
    protected static function fieldCompare(Document $a, Document $b) {
41
        $field = self::$orderByField;
42
        if (property_exists('\CloudControl\Cms\storage\entities\Document', $field)) {
43
            return strcasecmp($a->{$field}, $b->{$field});
44
        }
45
46
        if (!isset($a->fields->{$field}[0])) {
47
            return -3;
48
        }
49
50
        if (!isset($b->fields->{$field}[0])) {
51
            return 3;
52
        }
53
54
        return strcasecmp($a->fields->{$field}[0], $b->fields->{$field}[0]);
55
    }
56
}