ArrayMethods   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A filter_array() 0 10 3
A get_stage() 0 9 2
A create_sort_statement_from_id_array() 0 14 2
1
<?php
2
3
namespace Sunnysideup\OrmExtras;
4
5
use SilverStripe\Core\ClassInfo;
6
use SilverStripe\ORM\DataObject;
7
use SilverStripe\Versioned\Versioned;
8
9
class ArrayMethods
10
{
11
    /**
12
     * return an array of ids that can be ued for ORM filters...
13
     *
14
     * @param mixed $array - hopefully an array
15
     */
16
    public static function filter_array($array): array
17
    {
18
        if (! is_array($array)) {
19
            $array = [];
20
        }
21
        if (0 === count($array)) {
22
            $array = [0 => 0];
23
        }
24
25
        return array_values(array_unique($array));
26
    }
27
28
    /**
29
     * creates a sort string from a list of ID arrays...
30
     *
31
     * @param array $ids - list of product IDs
32
     */
33
    public static function create_sort_statement_from_id_array(array $ids, ?string $className = ''): string
34
    {
35
        $ids = ArrayMethods::filter_array($ids);
36
        $ifStatement = 'CASE ';
37
        $count = 0;
38
        $stage = self::get_stage();
39
        $dataClasses = ClassInfo::dataClassesFor($className);
40
        $table = DataObject::getSchema()->tableName(array_shift($dataClasses));
41
        foreach ($ids as $id) {
42
            $ifStatement .= ' WHEN "' . $table . $stage . "\".\"ID\" = {$id} THEN {$count}";
43
            ++$count;
44
        }
45
46
        return $ifStatement . ' END';
47
    }
48
49
    /**
50
     * Returns a versioned record stage table suffix (i.e "" or "_Live").
51
     *
52
     * @return string
53
     */
54
    protected static function get_stage()
55
    {
56
        $stage = '';
57
58
        if ('Live' === Versioned::get_stage()) {
59
            $stage = '_Live';
60
        }
61
62
        return $stage;
63
    }
64
}
65