Completed
Pull Request — master (#1)
by Karsten
03:23
created

RecordableHistory::getRecords()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace PeekAndPoke\Component\Slumber\Data\Journal\DomainModel;
4
5
/**
6
 * @author Karsten J. Gerber <[email protected]>
7
 */
8
class RecordableHistory
9
{
10
    /** @var Record[] */
11
    private $records;
12
    /** @var RecordDiff[] */
13
    private $diffs;
14
15
    /**
16
     * @param Record       $initial
17
     * @param Record       $final
18
     * @param RecordDiff[] $diffs
19
     *
20
     * @return RecordableHistory
21
     */
22
    public static function fromInitialAndFinalAndDiffs(Record $initial, Record $final, $diffs)
23
    {
24
        $ret        = new RecordableHistory([$initial, $final]);
25
        $ret->diffs = $diffs;
26
27
        return $ret;
28
    }
29
30
    /**
31
     * @param Record[] $records
32
     */
33
    public function __construct($records)
34
    {
35
        $this->records = $records;
36
    }
37
38
    /**
39
     * @return float
40
     */
41
    public function getCompactionRate()
42
    {
43
        $compacted    = 0;
44
        $notCompacted = 0;
45
46
        foreach ($this->records as $record) {
47
            if ($record->getIsCompacted() === false || $record->getCompactedHistory() === null) {
48
                $notCompacted++;
49
            } else {
50
                $compacted += count($record->getCompactedHistory()->getDiffs());
51
            }
52
        }
53
54
        if ($compacted + $notCompacted === 0) {
55
            return 0;
56
        }
57
58
        return $compacted / ($compacted + $notCompacted);
59
    }
60
61
    /**
62
     * @return Record
63
     */
64 View Code Duplication
    public function getInitialRecord()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
65
    {
66
        $record = count($this->records) > 0 ? $this->records[0] : new NullRecord();
67
68
        return $record->getIsCompacted() && $record->getCompactedHistory() !== null
69
            ? $record->getCompactedHistory()->getInitialRecord()
70
            : $record;
71
    }
72
73
    /**
74
     * @return Record
75
     */
76 View Code Duplication
    public function getFinalRecord()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
77
    {
78
        $record = count($this->records) > 0 ? $this->records[count($this->records) - 1] : new NullRecord();
79
80
        return $record->getIsCompacted() && $record->getCompactedHistory() !== null
81
            ? $record->getCompactedHistory()->getFinalRecord()
82
            : $record;
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function getRecords()
89
    {
90
        return $this->records;
91
    }
92
93
    /**
94
     * @return RecordDiff[]
95
     */
96
    public function getDiffs()
97
    {
98
        if ($this->diffs === null) {
99
            $this->calculateDiffs();
100
        }
101
102
        return $this->diffs;
103
    }
104
105
    protected function calculateDiffs()
106
    {
107
        $this->diffs = [];
108
109
        $previous = new NullRecord();
110
111
        foreach ($this->records as $current) {
112
113
            if ($current->getIsCompacted() === false) {
114
                $diff = $this->calculateDiff($previous, $current);
115
116
                if ($diff->getChangesCount() > 0) {
117
118
                    $this->diffs[] = $diff;
119
                }
120
121
                $previous = $current;
122
123
            } else {
124
125
                $history = $current->getCompactedHistory();
126
127
                if ($history) {
128
                    foreach ($history->getDiffs() as $diff) {
129
                        $this->diffs[] = $diff;
130
                    }
131
                }
132
133
                $previous = $history->getFinalRecord();
134
            }
135
        }
136
    }
137
138
    /**
139
     * @param Record $before
140
     * @param Record $after
141
     *
142
     * @return RecordDiff
143
     */
144
    protected function calculateDiff(Record $before, Record $after)
145
    {
146
        $diff = new RecordDiff($after->getChangeDate(), $after->getChangedBy());
147
148
        $beforeData = (array) $before->getRecordData();
149
        $afterData  = (array) $after->getRecordData();
150
151
        $this->diffRecursiveFromBeforeToAfter($diff, '', $beforeData, $afterData);
152
        $this->diffRecursiveFromAfterToBefore($diff, '', $beforeData, $afterData);
153
154
        return $diff;
155
    }
156
157
    /**
158
     * @param RecordDiff $diff
159
     * @param string     $pathInArray
160
     * @param mixed[]    $before
161
     * @param mixed[]    $after
162
     */
163 View Code Duplication
    private function diffRecursiveFromBeforeToAfter(RecordDiff $diff, $pathInArray, $before, $after)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
    {
165
        if (! is_array($before) && ! $before instanceof \Traversable) {
166
167
            $beforeValue = $this->convertToString($before);
168
            $afterValue  = $this->convertToString($after);
169
170
            if ($beforeValue !== $afterValue) {
171
                $diff->addChange(new RecordDiffEntry($pathInArray, $beforeValue, $afterValue));
172
            }
173
        } else {
174
175
            foreach ($before as $key => $beforeValue) {
176
177
                $afterValue = null;
178
179
                if ((is_array($after) || $after instanceof \ArrayAccess) && isset($after[$key])) {
180
                    $afterValue = $after[$key];
181
                }
182
183
                $this->diffRecursiveFromBeforeToAfter(
184
                    $diff,
185
                    empty($pathInArray) ? $key : $pathInArray . '.' . $key,
186
                    $beforeValue,
187
                    $afterValue
188
                );
189
            }
190
        }
191
    }
192
193
    /**
194
     * @param RecordDiff $diff
195
     * @param string     $pathInArray
196
     * @param array      $before
197
     * @param array      $after
198
     */
199 View Code Duplication
    private function diffRecursiveFromAfterToBefore(RecordDiff $diff, $pathInArray, $before, $after)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
200
    {
201
        if (! is_array($after) && ! $after instanceof \Traversable) {
202
203
            $beforeValue = $this->convertToString($before);
204
            $afterValue  = $this->convertToString($after);
205
206
            if ($beforeValue !== $afterValue) {
207
                $diff->addChange(new RecordDiffEntry($pathInArray, $beforeValue, $afterValue));
208
            }
209
        } else {
210
211
            // first compare from before to after
212
            foreach ($after as $key => $afterValue) {
213
214
                $beforeValue = null;
215
216
                if ((is_array($before) || $before instanceof \ArrayAccess) && isset($before[$key])) {
217
                    $beforeValue = $before[$key];
218
                }
219
220
                $processedKeys[] = $key;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$processedKeys was never initialized. Although not strictly required by PHP, it is generally a good practice to add $processedKeys = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
221
222
                $this->diffRecursiveFromAfterToBefore(
223
                    $diff,
224
                    empty($pathInArray) ? $key : $pathInArray . '.' . $key,
225
                    $beforeValue,
226
                    $afterValue
227
                );
228
            }
229
        }
230
    }
231
232
    /**
233
     * @param        $value
234
     * @param string $fallback
235
     *
236
     * @return string
237
     */
238
    private function convertToString($value, $fallback = 'N/A')
239
    {
240
        try {
241
            if (is_array($value)) {
242
                $str = json_encode($value, JSON_PRETTY_PRINT);
243
            } elseif ($value instanceof \MongoDate) {
244
                $date = (new \DateTime())->setTimestamp($value->sec);
245
                $str  = $date->format('c');
246
            } elseif ($value instanceof \DateTime) {
247
                $str = $value->format('c');
248
            } else {
249
                $str = (string) $value;
250
            }
251
        } catch (\Exception $e) {
252
            $str = $fallback;
253
        }
254
255
        return $str;
256
    }
257
}
258