zend-blog-3-backend

Форк
0
/
DataConverter.php 
353 строки · 10.7 Кб
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: morontt
5
 * Date: 22.11.14
6
 * Time: 12:33
7
 */
8

9
namespace App\API;
10

11
use App\API\Fractal\Collection;
12
use App\DTO\ArticleDTO;
13
use App\DTO\CategoryDTO;
14
use App\DTO\PygmentsCodeDTO;
15
use App\Entity;
16
use App\Model\Image;
17
use App\Repository\CategoryRepository;
18
use App\Repository\CommentRepository;
19
use App\Service\TextProcessor;
20
use App\Utils\Inflector;
21
use App\Utils\Pygment;
22
use App\Utils\RuTransform;
23
use DateTime;
24
use Doctrine\Common\Collections\ArrayCollection;
25
use Doctrine\ORM\EntityManager;
26
use Doctrine\ORM\EntityManagerInterface;
27
use League\Fractal\Manager;
28
use League\Fractal\Resource\Item;
29

30
/**
31
 * Class DataConverter
32
 *
33
 * @method array getCategory(Entity\Category $entity, $includes = null)
34
 * @method array getCategoryArray($collection, $includes = null)
35
 * @method array getComment(Entity\Comment $entity, $includes = null)
36
 * @method array getCommentArray($collection, $includes = null)
37
 * @method array getCommentator(Entity\CommentatorInterface $entity, $includes = null)
38
 * @method array getCommentatorArray($collection, $includes = null)
39
 * @method array getMediaFile(Image $entity, $includes = null)
40
 * @method array getMediaFileArray($collection, $includes = null)
41
 * @method array getPost(Entity\Post $entity, $includes = null)
42
 * @method array getPostArray($collection, $includes = null)
43
 * @method array getTag(Entity\Tag $entity, $includes = null)
44
 * @method array getTagArray($collection, $includes = null)
45
 * @method array getPygmentsLanguage(Entity\PygmentsLanguage $entity, $includes = null)
46
 * @method array getPygmentsLanguageArray($collection, $includes = null)
47
 * @method array getPygmentsCode(Entity\PygmentsCode $entity, $includes = null)
48
 * @method array getPygmentsCodeArray($collection, $includes = null)
49
 * @method array getUserAgent(Entity\TrackingAgent $entity, $includes = null)
50
 * @method array getUserAgentArray($collection, $includes = null)
51
 * @method array getTracking(Entity\Tracking $entity, $includes = null)
52
 * @method array getTrackingArray($collection, $includes = null)
53
 * @method array getTelegramUser(Entity\TelegramUser $entity, $includes = null)
54
 * @method array getTelegramUserArray($collection, $includes = null)
55
 * @method array getTelegramUpdate(Entity\TelegramUpdate $entity, $includes = null)
56
 * @method array getTelegramUpdateArray($collection, $includes = null)
57
 * @method array getUser(Entity\User $entity, $includes = null)
58
 * @method array getUserArray($collection, $includes = null)
59
 */
60
class DataConverter
61
{
62
    /**
63
     * @var Manager
64
     */
65
    protected Manager $fractal;
66

67
    /**
68
     * @var EntityManager
69
     */
70
    protected $em;
71

72
    /**
73
     * @var TextProcessor
74
     */
75
    protected TextProcessor $textProcessor;
76

77
    /**
78
     * @var CategoryRepository
79
     */
80
    private CategoryRepository $categoryRepository;
81

82
    /**
83
     * @var CommentRepository
84
     */
85
    private CommentRepository $commentsRepository;
86

87
    /**
88
     * @param EntityManagerInterface $em
89
     * @param TextProcessor $textProcessor
90
     * @param CommentRepository $commentsRepository
91
     * @param CategoryRepository $categoryRepository
92
     */
93
    public function __construct(
94
        EntityManagerInterface $em,
95
        TextProcessor $textProcessor,
96
        CommentRepository $commentsRepository,
97
        CategoryRepository $categoryRepository
98
    ) {
99
        $this->fractal = new Manager();
100
        $this->fractal->setSerializer(new Serializer());
101
        $this->categoryRepository = $categoryRepository;
102
        $this->commentsRepository = $commentsRepository;
103

104
        $this->em = $em;
105
        $this->textProcessor = $textProcessor;
106
    }
107

108
    /**
109
     * @param Entity\Category $entity
110
     * @param CategoryDTO $data
111
     *
112
     * @return array
113
     */
114
    public function saveCategory(Entity\Category $entity, CategoryDTO $data): array
115
    {
116
        Transformers\CategoryTransformer::reverseTransform($entity, $data);
117

118
        if ($data['parentId']) {
119
            $parent = $this->categoryRepository->find((int)$data['parentId']);
120
            $entity->setParent($parent);
121
        } else {
122
            $entity->setParent(null);
123
        }
124

125
        $this->categoryRepository->save($entity);
126

127
        return $this->getCategory($entity);
128
    }
129

130
    /**
131
     * @param Entity\Commentator $entity
132
     * @param array $data
133
     *
134
     * @return array
135
     */
136
    public function saveCommentator(Entity\Commentator $entity, array $data): array
137
    {
138
        Transformers\CommentatorTransformer::reverseTransform($entity, $data);
139

140
        $this->save($entity);
141

142
        return $this->getCommentator($entity);
143
    }
144

145
    /**
146
     * @param Entity\TrackingAgent $entity
147
     * @param array $data
148
     *
149
     * @return array
150
     */
151
    public function saveTrackingAgent(Entity\TrackingAgent $entity, array $data): array
152
    {
153
        Transformers\UserAgentTransformer::reverseTransform($entity, $data);
154

155
        $this->save($entity);
156

157
        return $this->getUserAgent($entity);
158
    }
159

160
    /**
161
     * @param Entity\Comment $entity
162
     * @param array $data
163
     *
164
     * @return array
165
     */
166
    public function saveComment(Entity\Comment $entity, array $data): array
167
    {
168
        Transformers\CommentTransformer::reverseTransform($entity, $data);
169
        $this->commentsRepository->save($entity);
170

171
        return $this->getComment($entity);
172
    }
173

174
    /**
175
     * @param Entity\Post $entity
176
     * @param ArticleDTO $data
177
     *
178
     * @throws \Doctrine\ORM\Exception\NotSupported
179
     * @throws \Doctrine\ORM\Exception\ORMException
180
     *
181
     * @return array
182
     */
183
    public function savePost(Entity\Post $entity, ArticleDTO $data): array
184
    {
185
        Transformers\PostTransformer::reverseTransform($entity, $data);
186

187
        $this->textProcessor->processing($entity);
188

189
        $entity->setCategory($this->em->getReference(Entity\Category::class, (int)$data['categoryId']));
190

191
        if ($entity->isHide()) {
192
            $entity->setTimeCreated(new DateTime());
193
        }
194

195
        $originalTags = new ArrayCollection();
196
        foreach ($entity->getTags() as $tag) {
197
            $originalTags->add($tag);
198
        }
199

200
        $tagsArray = array_map('trim', explode(',', $data['tagsString']));
201
        foreach ($tagsArray as $tagName) {
202
            if ($tagName) {
203
                $tag = $this->em->getRepository(Entity\Tag::class)->getTagForPost($tagName);
204
                if ($tag) {
205
                    if ($originalTags->contains($tag)) {
206
                        $originalTags->removeElement($tag);
207
                    } else {
208
                        $entity->addTag($tag);
209
                    }
210
                } else {
211
                    $tag = new Entity\Tag();
212
                    $tag
213
                        ->setName($tagName)
214
                        ->setUrl(RuTransform::ruTransform($tagName))
215
                    ;
216
                    $entity->addTag($tag);
217
                }
218
                $this->em->persist($tag);
219
            }
220
        }
221

222
        foreach ($originalTags as $tag) {
223
            $entity->removeTag($tag);
224
        }
225

226
        if (is_null($entity->getId())) {
227
            $postRepository = $this->em->getRepository(Entity\Post::class);
228
            $slug = $entity->getUrl();
229
            $oldPost = $postRepository->findOneBy(['url' => $slug]);
230
            if ($oldPost) {
231
                $inc = 2;
232
                do {
233
                    $newSlug = $slug . '-' . $inc;
234
                    $oldPost = $postRepository->findOneBy(['url' => $newSlug]);
235
                    $inc++;
236
                } while ($oldPost);
237
                $entity->setUrl($newSlug);
238
            }
239
        }
240

241
        $this->save($entity);
242

243
        return $this->getPost($entity);
244
    }
245

246
    /**
247
     * @param Entity\MediaFile $entity
248
     * @param array $data
249
     *
250
     * @return array
251
     */
252
    public function saveMediaFile(Entity\MediaFile $entity, array $data): array
253
    {
254
        Transformers\MediaFileTransformer::reverseTransform($entity, $data);
255

256
        if ($data['postId']) {
257
            $post = $this->em->getRepository(Entity\Post::class)->find((int)$data['postId']);
258
            if ($post) {
259
                $entity->setPost($post);
260
                if ($this->em->getRepository(Entity\MediaFile::class)->getCountByPostId((int)$data['postId']) === 0) {
261
                    $entity->setDefaultImage(true);
262
                }
263
            }
264
        } else {
265
            $entity->setPost(null);
266
        }
267

268
        $this->save($entity);
269

270
        return $this->getMediaFile(new Image($entity));
271
    }
272

273
    /**
274
     * @param Entity\PygmentsCode $entity
275
     * @param PygmentsCodeDTO $data
276
     *
277
     * @throws \Doctrine\ORM\Exception\ORMException
278
     *
279
     * @return array
280
     */
281
    public function savePygmentsCode(Entity\PygmentsCode $entity, PygmentsCodeDTO $data): array
282
    {
283
        $oldHash = $entity->getContentHash();
284
        Transformers\PygmentsCodeTransformer::reverseTransform($entity, $data);
285

286
        if ($data['languageId']) {
287
            $entity->setLanguage(
288
                $this->em->getReference(Entity\PygmentsLanguage::class, (int)$data['languageId'])
289
            );
290
        } else {
291
            $entity->setLanguage(null);
292
        }
293

294
        if ($oldHash !== $entity->getContentHash()) {
295
            $htmlObj = Pygment::highlight($entity->getSourceCode(), $entity->getLexer());
296
            $entity
297
                ->setSourceHtml($htmlObj->html())
298
                ->setSourceHtmlPreview($htmlObj->htmlPreview())
299
            ;
300
        }
301

302
        $this->save($entity);
303

304
        return $this->getPygmentsCode($entity);
305
    }
306

307
    /**
308
     * @param $method
309
     * @param $arguments
310
     *
311
     * @return array|null
312
     */
313
    public function __call($method, $arguments)
314
    {
315
        $matches = [];
316
        if (preg_match('/^get([A-Z]\w+)Array$/', $method, $matches)) {
317
            $class = 'App\\API\\Transformers\\' . $matches[1] . 'Transformer';
318
            $resource = new Collection(
319
                $arguments[0],
320
                new $class(),
321
                Inflector::pluralize(lcfirst($matches[1]))
322
            );
323

324
            if (!empty($arguments[1])) {
325
                $this->fractal->parseIncludes($arguments[1]);
326
            }
327

328
            $scope = $this->fractal->createData($resource);
329
        } elseif (preg_match('/^get([A-Z]\w+)$/', $method, $matches)) {
330
            $class = 'App\\API\\Transformers\\' . $matches[1] . 'Transformer';
331
            $resource = new Item($arguments[0], new $class(), lcfirst($matches[1]));
332

333
            if (!empty($arguments[1])) {
334
                $this->fractal->parseIncludes($arguments[1]);
335
            }
336

337
            $scope = $this->fractal->createData($resource);
338
        } else {
339
            throw new \RuntimeException(sprintf('Undefined method: %s', $method));
340
        }
341

342
        return $scope->toArray();
343
    }
344

345
    /**
346
     * @param $entity
347
     */
348
    protected function save($entity)
349
    {
350
        $this->em->persist($entity);
351
        $this->em->flush();
352
    }
353
}
354

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.