Completed
Pull Request — master (#19)
by John
04:27
created

FieldSorter   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 1
dl 0
loc 48
ccs 0
cts 12
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getOrderByFieldType() 0 8 2
A sort() 0 14 2
1
<?php
2
3
namespace Graze\CiffRenderer\Parser;
4
5
use Graze\CiffRenderer\Parser\FieldType;
6
use Graze\CiffRenderer\Exception\UnsupportedFieldTypeException;
7
8
class FieldSorter
9
{
10
    /**
11
     * @var int
12
     */
13
    protected $fieldTypeToOrder = [
14
        FieldType::FIELD_STATIC_GRAPHIC    => 1,
15
        FieldType::FIELD_FIXED_TEXT        => 2,
16
        FieldType::FIELD_BARCODE           => 3,
17
        FieldType::FIELD_DATE              => 4,
18
        FieldType::FIELD_OFFSET_DATE       => 5,
19
        FieldType::FIELD_MERGE_FIELD       => 6,
20
        FieldType::FIELD_GRAPHIC_PRIMITIVE => 7
21
    ];
22
23
    /**
24
     * @param int $fieldType
25
     * @return int
26
     * @throws UnsupportedFieldTypeException;
27
     */
28
    private function getOrderByFieldType($fieldType)
29
    {
30
        if (!isset($this->fieldTypeToOrder[$fieldType])) {
31
            throw new UnsupportedFieldTypeException($fieldType);
32
        }
33
34
        return $this->fieldTypeToOrder[$fieldType];
35
    }
36
37
    /**
38
     * @param array $fields
39
     * @return array
40
     */
41
    public function sort(array $fields)
42
    {
43
        $fieldKeyToOrder = [];
44
        foreach ($fields as $key => $field) {
45
            $fieldType = (string) $field->FldType; // @codingStandardsIgnoreLine
46
            $fieldKeyToOrder[$key] = $this->getOrderByFieldType($fieldType);
47
        }
48
49
        // sort
50
        asort($fieldKeyToOrder);
51
52
        // apply the sort to the fields
53
        return array_replace($fieldKeyToOrder, $fields);
54
    }
55
}
56