1 | <?php |
||
8 | class DeleteSafetyResourceCommand implements ResourceCommandInterface |
||
9 | { |
||
10 | /** |
||
11 | * @var ResourceDOInterface |
||
12 | */ |
||
13 | protected $resourceDO; |
||
14 | /** |
||
15 | * @var FilesystemInterface |
||
16 | */ |
||
17 | protected $filesystem; |
||
18 | |||
19 | 7 | public function __construct(ResourceDOInterface $resourceDO, FilesystemInterface $filesystem) |
|
20 | { |
||
21 | 7 | $this->resourceDO = $resourceDO; |
|
22 | 7 | $this->filesystem = $filesystem; |
|
23 | 7 | } |
|
24 | |||
25 | 7 | public function __invoke() |
|
26 | { |
||
27 | 7 | $version = $this->resourceDO->getVersion(); |
|
28 | 7 | $filePath = $this->resourceDO->getFilePath(); |
|
29 | 7 | if (!$this->resourceDO->getName() || !$this->resourceDO->getType() || !$this->resourceDO->getBaseDirectory()) { |
|
30 | 1 | throw new CommandErrorException('Cannot delete empty resource'); |
|
31 | } |
||
32 | 6 | if ($this->filesystem->has($filePath)) { |
|
33 | |||
34 | // Make backup of the default version |
||
35 | 5 | if (ResourceDOInterface::DEFAULT_VERSION === $version) { |
|
36 | 4 | $lastVersion = $this->findLastVersion(); |
|
37 | |||
38 | // But only if previous existing version is not the default and not has the same content as deleting |
||
39 | 4 | if (ResourceDOInterface::DEFAULT_VERSION !== $lastVersion) { |
|
40 | 2 | $lastVersionResourceDO = clone $this->resourceDO; |
|
41 | 2 | $lastVersionResourceDO->setVersion($lastVersion); |
|
42 | 2 | $command = new DestroyEqualResourceCommand( |
|
43 | $lastVersionResourceDO |
||
44 | 2 | , $this->resourceDO |
|
45 | 2 | , $this->filesystem |
|
46 | 2 | ); |
|
47 | 2 | $result = $command(); |
|
48 | 2 | if ($result === $this->resourceDO) { |
|
49 | |||
50 | // If the previous file version already the same, current version is already deleted |
||
51 | // and backup and yet another deletion is not needed anymore |
||
52 | 1 | return $this->resourceDO; |
|
53 | } |
||
54 | 1 | } |
|
55 | |||
56 | 3 | $command = new BackupResourceCommand($this->resourceDO, $this->filesystem); |
|
57 | 3 | $command($lastVersion); |
|
58 | 3 | } |
|
59 | |||
60 | 4 | $this->deleteFile($filePath); |
|
61 | |||
62 | 4 | return $this->resourceDO; |
|
63 | } |
||
64 | |||
65 | 1 | return $this->resourceDO; |
|
66 | } |
||
67 | |||
68 | /** |
||
69 | * @param $filePath |
||
70 | */ |
||
71 | 4 | protected function deleteFile($filePath) |
|
72 | { |
||
73 | 4 | if (!$this->filesystem->delete($filePath)) { |
|
74 | throw new CommandErrorException('The file cannot be removed: ' . $filePath); |
||
75 | } |
||
76 | 4 | } |
|
77 | |||
78 | /** |
||
79 | * @return int |
||
80 | */ |
||
81 | 4 | protected function findLastVersion() |
|
87 | } |