TimeTravel::undeleteEntity()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 13
rs 10
1
<?php
2
/*
3
 * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
4
 *
5
 *  Copyright (C) 2019 - 2022 Jan Böhmer (https://github.com/jbtronics)
6
 *
7
 *  This program is free software: you can redistribute it and/or modify
8
 *  it under the terms of the GNU Affero General Public License as published
9
 *  by the Free Software Foundation, either version 3 of the License, or
10
 *  (at your option) any later version.
11
 *
12
 *  This program is distributed in the hope that it will be useful,
13
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 *  GNU Affero General Public License for more details.
16
 *
17
 *  You should have received a copy of the GNU Affero General Public License
18
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
declare(strict_types=1);
22
23
namespace App\Services\LogSystem;
24
25
use App\Entity\Attachments\AttachmentType;
26
use App\Entity\Base\AbstractDBElement;
27
use App\Entity\Base\AbstractStructuralDBElement;
28
use App\Entity\Contracts\TimeStampableInterface;
29
use App\Entity\Contracts\TimeTravelInterface;
30
use App\Entity\LogSystem\AbstractLogEntry;
31
use App\Entity\LogSystem\CollectionElementDeleted;
32
use App\Entity\LogSystem\ElementEditedLogEntry;
33
use App\Repository\LogEntryRepository;
34
use Brick\Math\BigDecimal;
35
use DateTime;
36
use Doctrine\Common\Collections\Collection;
37
use Doctrine\ORM\EntityManagerInterface;
38
use Doctrine\ORM\Mapping\ClassMetadata;
39
use Doctrine\ORM\Mapping\ClassMetadataInfo;
40
use Doctrine\ORM\Mapping\MappingException;
41
use DoctrineExtensions\Query\Mysql\Date;
42
use Exception;
43
use InvalidArgumentException;
44
use ReflectionClass;
45
46
class TimeTravel
47
{
48
    protected EntityManagerInterface $em;
49
    protected LogEntryRepository $repo;
50
51
    public function __construct(EntityManagerInterface $em)
52
    {
53
        $this->em = $em;
54
        $this->repo = $em->getRepository(AbstractLogEntry::class);
55
    }
56
57
58
    /**
59
     * Undeletes the element with the given ID.
60
     *
61
     * @param string $class The class name of the element that should be undeleted
62
     * @param int    $id    the ID of the element that should be undeleted
63
     */
64
    public function undeleteEntity(string $class, int $id): AbstractDBElement
65
    {
66
        $log = $this->repo->getUndeleteDataForElement($class, $id);
67
        $element = new $class();
68
        $this->applyEntry($element, $log);
69
70
        //Set internal ID so the element can be reverted
71
        $this->setField($element, 'id', $id);
72
73
        //Let database determine when it will be created
74
        $this->setField($element, 'addedDate', null);
75
76
        return $element;
77
    }
78
79
    /**
80
     * Revert the given element to the state it has on the given timestamp.
81
     *
82
     * @param AbstractLogEntry[] $reverted_elements
83
     *
84
     * @throws Exception
85
     */
86
    public function revertEntityToTimestamp(AbstractDBElement $element, DateTime $timestamp, array $reverted_elements = []): void
87
    {
88
        if (!$element instanceof TimeStampableInterface) {
89
            throw new InvalidArgumentException('$element must have a Timestamp!');
90
        }
91
92
        if ($timestamp > new DateTime('now')) {
93
            throw new InvalidArgumentException('You can not travel to the future (yet)...');
94
        }
95
96
        //Skip this process if already were reverted...
97
        if (in_array($element, $reverted_elements, true)) {
98
            return;
99
        }
100
        $reverted_elements[] = $element;
101
102
        $history = $this->repo->getTimetravelDataForElement($element, $timestamp);
103
104
        /*
105
        if (!$this->repo->getElementExistedAtTimestamp($element, $timestamp)) {
106
            $element = null;
107
            return;
108
        }*/
109
110
        foreach ($history as $logEntry) {
111
            if ($logEntry instanceof ElementEditedLogEntry) {
112
                $this->applyEntry($element, $logEntry);
113
            }
114
            if ($logEntry instanceof CollectionElementDeleted) {
115
                //Undelete element and add it to collection again
116
                $undeleted = $this->undeleteEntity(
117
                    $logEntry->getDeletedElementClass(),
118
                    $logEntry->getDeletedElementID()
119
                );
120
                if ($this->repo->getElementExistedAtTimestamp($undeleted, $timestamp)) {
121
                    $this->revertEntityToTimestamp($undeleted, $timestamp, $reverted_elements);
122
                    $collection = $this->getField($element, $logEntry->getCollectionName());
123
                    if ($collection instanceof Collection) {
124
                        $collection->add($undeleted);
125
                    }
126
                }
127
            }
128
        }
129
130
        // Revert any of the associated elements
131
        $metadata = $this->em->getClassMetadata(get_class($element));
132
        $associations = $metadata->getAssociationMappings();
133
        foreach ($associations as $field => $mapping) {
134
            if (
135
                ($element instanceof AbstractStructuralDBElement && ('parts' === $field || 'children' === $field))
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($element instanceof App...attachments' === $field, Probably Intended Meaning: $element instanceof App\...ttachments' === $field)
Loading history...
136
                || ($element instanceof AttachmentType && 'attachments' === $field)
137
            ) {
138
                continue;
139
            }
140
141
            //Revert many to one association (one element in property)
142
            if (
143
                ClassMetadataInfo::MANY_TO_ONE === $mapping['type']
144
                || ClassMetadataInfo::ONE_TO_ONE === $mapping['type']
145
            ) {
146
                $target_element = $this->getField($element, $field);
147
                if (null !== $target_element && $element->getLastModified() > $timestamp) {
148
                    $this->revertEntityToTimestamp($target_element, $timestamp, $reverted_elements);
149
                }
150
            } elseif ( //Revert *_TO_MANY associations (collection properties)
151
                (ClassMetadataInfo::MANY_TO_MANY === $mapping['type']
152
                    || ClassMetadataInfo::ONE_TO_MANY === $mapping['type'])
153
                && false === $mapping['isOwningSide']
154
            ) {
155
                $target_elements = $this->getField($element, $field);
156
                if (null === $target_elements || count($target_elements) > 10) {
157
                    continue;
158
                }
159
                foreach ($target_elements as $target_element) {
160
                    if (null !== $target_element && $element->getLastModified() >= $timestamp) {
161
                        //Remove the element from collection, if it did not existed at $timestamp
162
                        if (!$this->repo->getElementExistedAtTimestamp(
163
                                $target_element,
164
                                $timestamp
165
                            ) && $target_elements instanceof Collection) {
166
                            $target_elements->removeElement($target_element);
167
                        }
168
                        $this->revertEntityToTimestamp($target_element, $timestamp, $reverted_elements);
169
                    }
170
                }
171
            }
172
        }
173
    }
174
175
    /**
176
     * This function decodes the array which is created during the json_encode of a datetime object and returns a DateTime object.
177
     * @param  array  $input
178
     * @return DateTime
179
     * @throws Exception
180
     */
181
    private function dateTimeDecode(?array $input): ?\DateTime
182
    {
183
        //Allow null values
184
        if ($input === null) {
0 ignored issues
show
introduced by
The condition $input === null is always false.
Loading history...
185
            return null;
186
        }
187
188
        return new \DateTime($input['date'], new \DateTimeZone($input['timezone']));
189
    }
190
191
    /**
192
     * Apply the changeset in the given LogEntry to the element.
193
     *
194
     * @throws MappingException
195
     */
196
    public function applyEntry(AbstractDBElement $element, TimeTravelInterface $logEntry): void
197
    {
198
        //Skip if this does not provide any info...
199
        if (!$logEntry->hasOldDataInformations()) {
200
            return;
201
        }
202
        if (!$element instanceof TimeStampableInterface) {
203
            return;
204
        }
205
        $metadata = $this->em->getClassMetadata(get_class($element));
206
        $old_data = $logEntry->getOldData();
207
208
        foreach ($old_data as $field => $data) {
209
            if ($metadata->hasField($field)) {
210
                //We need to convert the string to a BigDecimal first
211
                if (!$data instanceof BigDecimal && ('big_decimal' === $metadata->getFieldMapping($field)['type'])) {
212
                    $data = BigDecimal::of($data);
213
                }
214
215
                if (!$data instanceof DateTime && ('datetime' === $metadata->getFieldMapping($field)['type'])) {
216
                    $data = $this->dateTimeDecode($data);
217
                }
218
219
                $this->setField($element, $field, $data);
220
            }
221
            if ($metadata->hasAssociation($field)) {
222
                $mapping = $metadata->getAssociationMapping($field);
223
                $target_class = $mapping['targetEntity'];
224
                //Try to extract the old ID:
225
                if (is_array($data) && isset($data['@id'])) {
226
                    $entity = $this->em->getPartialReference($target_class, $data['@id']);
227
                    $this->setField($element, $field, $entity);
228
                }
229
            }
230
        }
231
232
        $this->setField($element, 'lastModified', $logEntry->getTimestamp());
233
    }
234
235
    protected function getField(AbstractDBElement $element, string $field)
236
    {
237
        $reflection = new ReflectionClass(get_class($element));
238
        $property = $reflection->getProperty($field);
239
        $property->setAccessible(true);
240
241
        return $property->getValue($element);
242
    }
243
244
    /**
245
     * @param DateTime|int|null $new_value
246
     */
247
    protected function setField(AbstractDBElement $element, string $field, $new_value): void
248
    {
249
        $reflection = new ReflectionClass(get_class($element));
250
        $property = $reflection->getProperty($field);
251
        $property->setAccessible(true);
252
253
        $property->setValue($element, $new_value);
254
    }
255
}
256