File   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 181
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 53
c 2
b 0
f 0
dl 0
loc 181
rs 10
wmc 12

8 Methods

Rating   Name   Duplication   Size   Complexity  
A fillEntity() 0 25 2
A createEntity() 0 5 1
A update() 0 14 2
A deleteFile() 0 5 1
A __construct() 0 14 1
A create() 0 16 2
A uploadFile() 0 12 2
A delete() 0 11 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Files\Service\Execute;
6
7
use AbterPhp\Admin\Service\Execute\RepoServiceAbstract;
8
use AbterPhp\Files\Domain\Entities\File as Entity;
9
use AbterPhp\Files\Domain\Entities\FileCategory;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, AbterPhp\Files\Service\Execute\FileCategory. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
10
use AbterPhp\Files\Orm\FileCategoryRepo;
11
use AbterPhp\Files\Orm\FileRepo as GridRepo;
12
use AbterPhp\Files\Validation\Factory\File as ValidatorFactory;
13
use AbterPhp\Framework\Domain\Entities\IStringerEntity;
14
use AbterPhp\Framework\Filesystem\Uploader;
15
use Cocur\Slugify\Slugify;
16
use Opulence\Events\Dispatchers\IEventDispatcher;
17
use Opulence\Http\Requests\UploadedFile;
18
use Opulence\Orm\IUnitOfWork;
19
use Opulence\Orm\OrmException;
20
21
class File extends RepoServiceAbstract
22
{
23
    const INPUT_NAME_FILE = 'file';
24
25
    /** @var Slugify */
26
    protected $slugify;
27
28
    /** @var FileCategoryRepo */
29
    protected $fileCategoryRepo;
30
31
    /** @var Uploader */
32
    protected $uploader;
33
34
    /**
35
     * File constructor.
36
     *
37
     * @param GridRepo         $repo
38
     * @param ValidatorFactory $validatorFactory
39
     * @param IUnitOfWork      $unitOfWork
40
     * @param IEventDispatcher $eventDispatcher
41
     * @param Slugify          $slugify
42
     * @param FileCategoryRepo $fileCategoryRepo
43
     * @param Uploader         $uploader
44
     */
45
    public function __construct(
46
        GridRepo $repo,
47
        ValidatorFactory $validatorFactory,
48
        IUnitOfWork $unitOfWork,
49
        IEventDispatcher $eventDispatcher,
50
        Slugify $slugify,
51
        FileCategoryRepo $fileCategoryRepo,
52
        Uploader $uploader
53
    ) {
54
        parent::__construct($repo, $validatorFactory, $unitOfWork, $eventDispatcher);
55
56
        $this->slugify          = $slugify;
57
        $this->fileCategoryRepo = $fileCategoryRepo;
58
        $this->uploader         = $uploader;
59
    }
60
61
    /**
62
     * @param string[]       $postData
63
     * @param UploadedFile[] $fileData
64
     *
65
     * @return Entity
66
     * @throws OrmException
67
     */
68
    public function create(array $postData, array $fileData): IStringerEntity
69
    {
70
        $entity = $this->fillEntity($this->createEntity(''), $postData, $fileData);
71
72
        $this->uploadFile($entity, $fileData);
73
74
        $errors = $this->uploader->getErrors();
75
        if ($errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
76
            return $entity;
77
        }
78
79
        $this->repo->add($entity);
80
81
        $this->commitCreate($entity);
82
83
        return $entity;
84
    }
85
86
    /**
87
     * @param IStringerEntity $entity
88
     * @param string[]        $postData
89
     * @param UploadedFile[]  $fileData
90
     *
91
     * @return bool
92
     * @throws OrmException
93
     */
94
    public function update(IStringerEntity $entity, array $postData, array $fileData): bool
95
    {
96
        assert($entity instanceof Entity, new \InvalidArgumentException());
97
98
        $this->fillEntity($entity, $postData, $fileData);
99
100
        if (!empty($fileData)) {
101
            $this->deleteFile($entity);
102
            $this->uploadFile($entity, $fileData);
103
        }
104
105
        $this->commitUpdate($entity);
106
107
        return true;
108
    }
109
110
    /**
111
     * @param IStringerEntity $entity
112
     *
113
     * @return bool
114
     * @throws OrmException
115
     */
116
    public function delete(IStringerEntity $entity): bool
117
    {
118
        assert($entity instanceof Entity, new \InvalidArgumentException());
119
120
        $this->deleteFile($entity);
121
122
        $this->repo->delete($entity);
123
124
        $this->commitDelete($entity);
125
126
        return true;
127
    }
128
129
    /**
130
     * @param IStringerEntity $entity
131
     */
132
    public function deleteFile(IStringerEntity $entity)
133
    {
134
        assert($entity instanceof Entity, new \InvalidArgumentException());
135
136
        $this->uploader->delete($entity->getOldFilesystemName());
137
    }
138
139
    /**
140
     * @param IStringerEntity $entity
141
     * @param UploadedFile[]  $fileData
142
     */
143
    public function uploadFile(IStringerEntity $entity, array $fileData)
144
    {
145
        assert($entity instanceof Entity, new \InvalidArgumentException());
146
147
        $paths = $this->uploader->persist($fileData);
148
149
        if (!$paths) {
150
            return;
151
        }
152
153
        $entity->setFilesystemName($paths[static::INPUT_NAME_FILE]);
154
        $entity->setPublicName($fileData[static::INPUT_NAME_FILE]->getTempFilename());
155
    }
156
157
    /**
158
     * @param string $entityId
159
     *
160
     * @return Entity
161
     */
162
    public function createEntity(string $entityId): IStringerEntity
163
    {
164
        $fileCategory = new FileCategory('', '', '', false, []);
165
166
        return new Entity($entityId, '', '', '', '', $fileCategory);
167
    }
168
169
    /**
170
     * @param IStringerEntity $entity
171
     * @param array           $postData
172
     * @param UploadedFile[]  $fileData
173
     *
174
     * @return Entity
175
     * @throws OrmException
176
     */
177
    protected function fillEntity(IStringerEntity $entity, array $postData, array $fileData): IStringerEntity
178
    {
179
        assert($entity instanceof Entity, new \InvalidArgumentException());
180
181
        $categoryId  = $postData['category_id'];
182
        $description = $postData['description'];
183
184
        /** @var FileCategory $fileCategory */
185
        $fileCategory = $this->fileCategoryRepo->getById($categoryId);
186
187
        $entity
188
            ->setDescription($description)
189
            ->setCategory($fileCategory);
190
191
        if (array_key_exists(static::INPUT_NAME_FILE, $fileData)) {
192
            /** @var UploadedFile $uploadedFile */
193
            $uploadedFile = $fileData[static::INPUT_NAME_FILE];
194
195
            $entity
196
                ->setFilesystemName($uploadedFile->getFilename())
197
                ->setPublicName($uploadedFile->getTempFilename())
198
                ->setMime($uploadedFile->getMimeType());
199
        }
200
201
        return $entity;
202
    }
203
}
204