Completed
Push — master ( cc8038...edef00 )
by Bartko
01:27
created

ArrayDataSource::sortData()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 3
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace StefanoTreeTest\DbTester;
6
7
class ArrayDataSource
8
{
9
    private $dataSource;
10
11
    /**
12
     * array(
13
     *      tableName => (
14
     *          array(
15
     *              columnName => value, anotherColumnName => value
16
     *          ),
17
     *          another row
18
     *      ),
19
     *      another table
20
     * ).
21
     *
22
     * @param array $dataSource
23
     */
24
    public function __construct(array $dataSource)
25
    {
26
        $this->dataSource = $dataSource;
27
    }
28
29
    public function getTableNames(): array
30
    {
31
        $tables = array();
32
        foreach ($this->dataSource as $tableName => $_) {
33
            $tables[] = $tableName;
34
        }
35
36
        return $tables;
37
    }
38
39
    public function getTableData(string $tableName, bool $sort = false)
40
    {
41
        if (array_key_exists($tableName, $this->dataSource)) {
42
            if ($sort) {
43
                return $this->sortData($this->dataSource[$tableName]);
44
            } else {
45
                return $this->dataSource[$tableName];
46
            }
47
        } else {
48
            throw new \Exception(sprintf(
49
                'Table "%s" does not exists',
50
                $tableName
51
            ));
52
        }
53
    }
54
55
    private function sortData(array $data): array
56
    {
57
        usort($data, function ($a, $b) {
58
            reset($a);
59
            reset($b);
60
61
            $a = $a[key($a)];
62
            $b = $b[key($b)];
63
64
            if ($a == $b) {
65
                return 0;
66
            }
67
68
            return ($a < $b) ? -1 : 1;
69
        });
70
71
        return $data;
72
    }
73
}
74