Passed
Push — ci ( 4bddb0...d61335 )
by Antonio Oertel
05:01 queued 02:35
created

AbstractSegment::trim()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 2
eloc 2
nc 2
nop 2
crap 2
1
<?php
2
3
namespace PositionalFile\Segment;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Doctrine\Common\Collections\Collection;
7
use PositionalFile\Field\FieldInterface;
8
9
abstract class AbstractSegment implements SegmentInterface
10
{
11
12
    /**
13
     * @var Collection
14
     */
15
    protected $fields;
16
17 10
    public function __construct()
18
    {
19 10
        $this->fields = new ArrayCollection();
20 10
    }
21
22
    /**
23
     * @inheritdoc
24
     */
25 8
    public function addField(FieldInterface $field)
26
    {
27 8
        if (is_null($field->getSequential())) {
28 8
            $field->setSequential($this->getFields()->count());
29 8
        }
30 8
        $this->fields->add($field);
31
32 8
        return $this;
33
    }
34
35
    /**
36
     * @inheritdoc
37
     */
38 1
    public function setFields(Collection $fields)
39
    {
40 1
        $this->fields = $fields;
41
42 1
        return $this;
43
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48 9
    public function getFields()
49
    {
50 9
        return $this->fields;
51
    }
52
53
    /**
54
     * @inheritdoc
55
     */
56 7
    public function toString($separator = '')
57
    {
58 7
        $string = '';
59
60 7
        $fields = $this->sortFieldsBy('sequential');
61
62 7
        foreach ($fields as $field) {
63 7
            if (!empty($string)) {
64 7
                $string .= $separator;
65 7
            }
66 7
            $string .= $field->getFormattedValue();
67 7
        }
68
69 7
        return $string;
70
    }
71
72
    /**
73
     * @param string $property
74
     *
75
     * @return \Traversable
76
     */
77 7
    public function sortFieldsBy($property)
78
    {
79 7
        $fields = $this->getFields()->getIterator();
80
81 7
        $fields->uasort(function ($a, $b) use ($property) {
82 7
            $method = 'get' . ucfirst($property);
83
84 7
            return ($a->$method() == $b->$method() ? 0 : ($a->$method() > $b->$method() ? 1 : -1));
85 7
        });
86
87 7
        return $fields;
88
    }
89
}
90