Completed
Push — master ( 249c16...582c12 )
by Paweł
16s
created

LoadArticlesData::getOrder()   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 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Superdesk Web Publisher Fixtures Bundle.
5
 *
6
 * Copyright 2015 Sourcefabric z.ú. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2015 Sourcefabric z.ú
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace SWP\Bundle\FixturesBundle\DataFixtures\ORM;
16
17
use Doctrine\Common\DataFixtures\FixtureInterface;
18
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
19
use Doctrine\Common\Persistence\ObjectManager;
20
use SWP\Bundle\AnalyticsBundle\Model\ArticleStatisticsInterface;
21
use SWP\Bundle\ContentBundle\Model\ArticleAuthor;
22
use SWP\Bundle\ContentBundle\Model\ArticleInterface;
23
use SWP\Bundle\ContentBundle\Model\ImageRendition;
24
use SWP\Bundle\ContentBundle\Model\RouteInterface;
25
use SWP\Bundle\CoreBundle\Model\ArticleEvent;
26
use SWP\Bundle\CoreBundle\Model\ArticleEventInterface;
27
use SWP\Bundle\CoreBundle\Model\PackageInterface;
28
use SWP\Bundle\FixturesBundle\AbstractFixture;
29
use Symfony\Component\HttpFoundation\File\UploadedFile;
30
31
class LoadArticlesData extends AbstractFixture implements FixtureInterface, OrderedFixtureInterface
32 5
{
33
    private $manager;
34 5
35 5
    /**
36
     * {@inheritdoc}
37 5
     */
38 5
    public function load(ObjectManager $manager)
39
    {
40 5
        $this->manager = $manager;
41 5
        $env = $this->getEnvironment();
42
43 5
        $tenantContext = $this->container->get('swp_multi_tenancy.tenant_context');
44
        $mediaManager = $this->container->get('swp_content_bundle.manager.media');
45
        if (null === $tenantContext->getTenant()) {
46
            $tenantContext->setTenant(
47
                $this->container->get('swp.repository.tenant')->findOneByCode('123abc')
48
            );
49
        }
50
        $mediaManager->setTenantContext($tenantContext);
51
52
        $this->loadRoutes($env, $manager);
53
        $this->loadArticles($env, $manager);
54
55
        $manager->flush();
56
    }
57
58
    public function loadRoutes($env, $manager)
59
    {
60
        $routes = [
61
            'dev' => [
62
                [
63
                    'name' => 'politics',
64
                    'variablePattern' => '/{slug}',
65
                    'requirements' => [
66
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
67
                    ],
68
                    'type' => 'collection',
69
                    'defaults' => [
70
                        'slug' => null,
71
                    ],
72
                    'templateName' => 'category.html.twig',
73
                    'articlesTemplateName' => 'article.html.twig',
74
                ],
75
                [
76
                    'name' => 'business',
77
                    'variablePattern' => '/{slug}',
78
                    'requirements' => [
79
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
80
                    ],
81
                    'type' => 'collection',
82
                    'defaults' => [
83
                        'slug' => null,
84
                    ],
85
                    'templateName' => 'category.html.twig',
86
                    'articlesTemplateName' => 'article.html.twig',
87
                ],
88
                [
89
                    'name' => 'scitech',
90
                    'variablePattern' => '/{slug}',
91
                    'requirements' => [
92
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
93
                    ],
94
                    'type' => 'collection',
95
                    'defaults' => [
96
                        'slug' => null,
97
                    ],
98
                    'templateName' => 'category.html.twig',
99
                    'articlesTemplateName' => 'article.html.twig',
100
                ],
101
                [
102
                    'name' => 'health',
103
                    'variablePattern' => '/{slug}',
104
                    'requirements' => [
105
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
106
                    ],
107
                    'type' => 'collection',
108
                    'defaults' => [
109
                        'slug' => null,
110
                    ],
111
                    'templateName' => 'category.html.twig',
112
                    'articlesTemplateName' => 'article.html.twig',
113
                ],
114
                [
115
                    'name' => 'entertainment',
116
                    'variablePattern' => '/{slug}',
117
                    'requirements' => [
118
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
119
                    ],
120
                    'type' => 'collection',
121
                    'defaults' => [
122
                        'slug' => null,
123
                    ],
124
                    'templateName' => 'category.html.twig',
125
                    'articlesTemplateName' => 'article.html.twig',
126
                ],
127
                [
128
                    'name' => 'sports',
129
                    'variablePattern' => '/{slug}',
130
                    'requirements' => [
131
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
132
                    ],
133
                    'type' => 'collection',
134
                    'defaults' => [
135
                        'slug' => null,
136
                    ],
137
                    'templateName' => 'category.html.twig',
138
                    'articlesTemplateName' => 'article.html.twig',
139
                ],
140
                [
141
                    'name' => 'about',
142 5
                    'variablePattern' => '/{slug}',
143
                    'requirements' => [
144
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
145
                    ],
146
                    'type' => 'collection',
147
                    'defaults' => [
148
                        'slug' => null,
149
                    ],
150
                    'articlesTemplateName' => 'page.html.twig',
151
                ],
152
                [
153
                    'name' => 'home',
154
                    'type' => 'content',
155
                    'templateName' => 'index.html.twig',
156
                ],
157
            ],
158
            'test' => [
159
                [
160
                    'name' => 'news',
161
                    'variablePattern' => '/{slug}',
162
                    'requirements' => [
163
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
164
                    ],
165
                    'type' => 'collection',
166 5
                    'defaults' => [
167
                        'slug' => null,
168 5
                    ],
169 5
                ],
170 5
                [
171 5
                    'name' => 'articles',
172
                    'type' => 'content',
173 5
                ],
174
                [
175
                    'name' => 'articles/features',
176
                    'type' => 'content',
177 5
                ],
178
                [
179
                    'name' => 'sports',
180
                    'type' => 'collection',
181 5
                    'parentName' => 'news',
182
                ],
183
            ],
184
        ];
185 5
186
        $routeService = $this->container->get('swp.service.route');
187 5
188
        $persistedRoutes = [];
189
        foreach ($routes[$env] as $routeData) {
190 5
            /** @var RouteInterface $route */
191 5
            $route = $this->container->get('swp.factory.route')->create();
192
            $route->setName($routeData['name']);
193
            $route->setType($routeData['type']);
194
195
            if (isset($routeData['cacheTimeInSeconds'])) {
196
                $route->setCacheTimeInSeconds($routeData['cacheTimeInSeconds']);
197 5
            }
198
199 5
            if (isset($routeData['templateName'])) {
200
                $route->setTemplateName($routeData['templateName']);
201
            }
202
203
            if (isset($routeData['articlesTemplateName'])) {
204
                $route->setArticlesTemplateName($routeData['articlesTemplateName']);
205
            }
206
207
            if (isset($routeData['parentName']) && isset($persistedRoutes[$routeData['parentName']])) {
208
                $route->setParent($persistedRoutes[$routeData['parentName']]);
209
            }
210
211
            $route = $routeService->fillRoute($route);
212
213
            $manager->persist($route);
214
            $persistedRoutes[$route->getName()] = $route;
215
        }
216
217
        $manager->flush();
218
    }
219
220
    /**
221
     * Sets articles manually (not via Alice) for test env due to fatal error:
222
     * Method PHPCRProxies\__CG__\Doctrine\ODM\PHPCR\Document\Generic::__toString() must not throw an exception.
223
     */
224
    public function loadArticles($env, ObjectManager $manager)
225
    {
226
        if ('test' !== $env) {
227
            $this->loadFixtures([
228
                '@SWPFixturesBundle/Resources/fixtures/ORM/'.$env.'/package.yml',
229
            ],
230
                $manager,
231
                [
232
                    'providers' => [$this],
233
                ]
234
            );
235
236
            $articles = $this->loadFixtures([
237
                    '@SWPFixturesBundle/Resources/fixtures/ORM/'.$env.'/article.yml',
238
                ],
239
                $manager,
240
                [
241
                    'providers' => [$this],
242
                ],
243
                true
0 ignored issues
show
Unused Code introduced by
The call to LoadArticlesData::loadFixtures() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
244
            );
245
246
            $renditions = [
247
                'original' => [],
248
                '770x515' => [
249
                    'width' => '770',
250
                    'height' => '515',
251
                ],
252
                '478x326' => [
253
                    'width' => '478',
254
                    'height' => '326',
255
                ],
256
                '480x480' => [
257
                    'width' => '480',
258
                    'height' => '480',
259
                ],
260
                '960x480' => [
261
                    'width' => '960',
262
                    'height' => '480',
263
                ],
264
                '600x360' => [
265
                    'width' => '600',
266
                    'height' => '360',
267
                ],
268
                '400x240' => [
269
                    'width' => '400',
270
                    'height' => '240',
271
                ],
272
                '1000x1000' => [
273
                    'width' => '1000',
274
                    'height' => '1000',
275
                ],
276
                '610x380' => [
277
                    'width' => '610',
278
                    'height' => '380',
279
                ],
280
                '1250x600' => [
281
                    'width' => '1250',
282
                    'height' => '600',
283
                ],
284
            ];
285
286
            $mediaManager = $this->container->get('swp_content_bundle.manager.media');
287
288
            foreach ($renditions as $key => $rendition) {
289
                if ('original' === $key) {
290
                    continue;
291
                }
292
293
                for ($i = 1; $i <= 9; ++$i) {
294
                    $filename = '/tmp/'.$i.'org'.$key.'.jpg';
295
                    if (file_exists($filename)) {
296
                        continue;
297
                    }
298
299
                    $fakeImage = __DIR__.'/../../Resources/assets/'.$i.'org.jpg';
300
                    $this->cropAndResizeImage($fakeImage, $rendition, $filename);
301
                }
302
            }
303
304
            foreach ($articles as $article) {
305
                // randomly create two media (images) for each of the article
306
                for ($i = 0; $i < 2; ++$i) {
307
                    // create Media
308
                    $articleMediaClass = $this->container->getParameter('swp.model.media.class');
309
                    $articleMedia = new $articleMediaClass();
310
                    $articleMedia->setArticle($article);
311
                    $articleMedia->setKey('embedded'.uniqid());
312
                    $articleMedia->setBody('This is very nice image caption...');
313
                    $articleMedia->setByLine('By Best Editor');
314
                    $articleMedia->setLocated('Porto');
315
                    $articleMedia->setDescription('Media description');
316
                    $articleMedia->setUsageTerms('Some super open terms');
317
                    $articleMedia->setMimetype('image/jpeg');
318
                    $manager->persist($articleMedia);
319
320
                    $randNumber = rand(1, 9);
321
                    /* @var $rendition Rendition */
322
                    foreach ($renditions as $key => $rendition) {
323
                        if ('original' === $key) {
324
                            $fakeImage = __DIR__.'/../../Resources/assets/'.$randNumber.'org.jpg';
325
                            list($width, $height) = getimagesize($fakeImage);
326
                            $rendition['height'] = $height;
327
                            $rendition['width'] = $width;
328
                        } else {
329
                            $fakeImage = '/tmp/'.$randNumber.'org'.$key.'.jpg';
330
                        }
331
332
                        $mediaId = uniqid();
333
                        $uploadedFile = new UploadedFile(
334
                            $fakeImage,
335
                            $mediaId,
336
                            'image/jpeg',
337 5
                            filesize($fakeImage),
338
                            null,
339
                            true
340 5
                        );
341 5
                        $image = $mediaManager->handleUploadedFile($uploadedFile, $mediaId);
342 5
                        $articleMedia->setImage($image);
343 5
344 5
                        $imageRendition = new ImageRendition();
345 5
                        $imageRendition->setImage($image);
346 5
                        $imageRendition->setHeight($rendition['height']);
347 5
                        $imageRendition->setWidth($rendition['width']);
348 5
                        $imageRendition->setName($key);
349 5
                        $imageRendition->setMedia($articleMedia);
350 5
                        $articleMedia->addRendition($imageRendition);
351
                        $manager->persist($imageRendition);
352 5
                    }
353
                }
354
            }
355 5
        }
356
357 5
        $articles = [
358
            'test' => [
359
                [
360
                    'title' => 'Test news article',
361
                    'content' => 'Test news article content',
362
                    'route' => 'news',
363
                    'locale' => 'en',
364
                    'pageViews' => 20,
365
                    'pageViewsDates' => [
366
                        '-1 day' => 3,
367
                        '-2 days' => 2,
368
                        '-3 days' => 3,
369
                        '-4 days' => 1,
370
                        '-5 days' => 6,
371
                        '-6 days' => 1,
372
                        '-7 days' => 4,
373
                    ],
374
                    'extra' => [
375
                        'custom-field' => 'my custom field',
376
                    ],
377
                ],
378
                [
379
                    'title' => 'Test news sports article',
380
                    'content' => 'Test news sports article content',
381
                    'route' => 'sports',
382
                    'locale' => 'en',
383
                    'pageViews' => 30,
384
                    'pageViewsDates' => [
385
                        '-1 day' => 3,
386
                        '-2 days' => 2,
387
                        '-3 days' => 8,
388
                        '-4 days' => 1,
389
                        '-5 days' => 6,
390
                        '-6 days' => 6,
391
                        '-7 days' => 4,
392
                    ],
393
                ],
394
                [
395
                    'title' => 'Test article',
396
                    'content' => 'Test article content',
397
                    'route' => 'news',
398
                    'locale' => 'en',
399
                    'pageViews' => 10,
400
                    'pageViewsDates' => [
401
                        '-1 day' => 3,
402
                        '-2 days' => 3,
403
                        '-4 days' => 1,
404
                        '-5 days' => 1,
405
                        '-6 days' => 1,
406
                        '-7 days' => 1,
407
                    ],
408
                ],
409
                [
410
                    'title' => 'Features',
411
                    'content' => 'Features content',
412
                    'route' => 'news',
413
                    'locale' => 'en',
414
                    'pageViews' => 5,
415
                    'pageViewsDates' => [
416
                        '- 7 days' => 5,
417
                    ],
418
                ],
419
                [
420
                    'title' => 'Features client1',
421
                    'content' => 'Features client1 content',
422
                    'route' => 'articles/features',
423
                    'locale' => 'en',
424
                    'pageViews' => 0,
425
                    'pageViewsDates' => [],
426
                ],
427
            ],
428
        ];
429
430
        $sources = ['Forbes', 'Reuters'];
431
        $secondSources = ['AAP', 'AFP'];
432
        $authors = ['John Doe', 'Test Person', 'Tom'];
433
434
        if (isset($articles[$env])) {
435
            $articleService = $this->container->get('swp.service.article');
436
            $sourcesFactory = $this->container->get('swp.factory.article_source');
437
            $articleSourcesService = $this->container->get('swp.service.article_source');
438
            foreach ($articles[$env] as $articleData) {
439
                /** @var ArticleInterface $article */
440
                $article = $this->container->get('swp.factory.article')->create();
441
                $article->setTitle($articleData['title']);
442
                $article->setBody($articleData['content']);
443
                $article->setRoute($this->getRouteByName($articleData['route']));
444
                $article->setLocale($articleData['locale']);
445
                $article->setCode(md5($articleData['title']));
446
                $article->setKeywords($this->articleKeywords());
447
448
                if (isset($articleData['extra'])) {
449 5
                    $article->setExtra($articleData['extra']);
450
                }
451 5
452
                $author = new ArticleAuthor();
453
                $author->setRole('Writer');
454
                $author->setName($authors[array_rand($authors)]);
455
                $article->addAuthor($author);
456
457
                $articleSource = $sourcesFactory->create();
458
                $articleSource->setName($sources[random_int(0, 1)]);
459
                $article->addSourceReference($articleSourcesService->getArticleSourceReference($article, $articleSource));
460
                $articleSourceSecond = $sourcesFactory->create();
461
                $articleSourceSecond->setName($secondSources[random_int(0, 1)]);
462
                $article->addSourceReference($articleSourcesService->getArticleSourceReference($article, $articleSourceSecond));
463
                $package = $this->createPackage($articleData);
464
                $articleStatistics = $this->createArticleStatistics($articleData['pageViews'], $articleData['pageViewsDates'], $article, $manager);
465
                $manager->persist($articleStatistics);
466
                $manager->persist($package);
467
                $article->setPackage($package);
468
                $manager->persist($article);
469
                $articleService->publish($article);
470
471
                $this->addReference($article->getSlug(), $article);
472
            }
473
474
            $manager->flush();
475
        }
476
    }
477
478 View Code Duplication
    private function createPackage(array $articleData)
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...
479
    {
480
        /** @var PackageInterface $package */
481
        $package = $this->container->get('swp.factory.package')->create();
482
        $package->setHeadline($articleData['title']);
483
        $package->setType('text');
484
        $package->setPubStatus('usable');
485
        $package->setGuid($this->container->get('swp_multi_tenancy.random_string_generator')->generate(10));
486
        $package->setLanguage('en');
487
        $package->setUrgency(1);
488
        $package->setPriority(1);
489
        $package->setVersion(1);
490
491
        return $package;
492
    }
493
494
    private function createArticleStatistics(int $pageViewsNumber, array $pageViewsDates, ArticleInterface $article, ObjectManager $manager)
495
    {
496
        /** @var ArticleStatisticsInterface $articleStatistics */
497
        $articleStatistics = $this->container->get('swp.factory.article_statistics')->create();
498
        $articleStatistics->setArticle($article);
499
        $articleStatistics->setPageViewsNumber($pageViewsNumber);
500
501
        $count = 0;
502
        foreach ($pageViewsDates as $dateValue => $number) {
503
            for ($i = $number; $i > 0; --$i) {
504
                $articleEvent = new ArticleEvent();
505
                $articleEvent->setArticleStatistics($articleStatistics);
506
                $articleEvent->setAction(ArticleEventInterface::ACTION_PAGEVIEW);
507
                $date = new \DateTime();
508
                $date->modify($dateValue);
509
                $date->setTime(mt_rand(0, 23), str_pad(mt_rand(0, 59), 2, '0', STR_PAD_LEFT));
510
                $articleEvent->setCreatedAt($date);
511
                $manager->persist($articleEvent);
512
                ++$count;
513
            }
514
        }
515
516
        return $articleStatistics;
517
    }
518
519
    /**
520
     * @return array
521
     */
522
    public function articleKeywords()
523
    {
524
        $keywords = [
525
            'city',
526
            'traffic',
527
            'car',
528
            'news',
529
            'building',
530
        ];
531
532
        shuffle($keywords);
533
534
        return $keywords;
535
    }
536
537
    /**
538
     * Article example metadata.
539
     *
540
     * @return array
541
     */
542
    public function articleMetadata()
543
    {
544
        $authors = [
545
            'Sarrah Staffwriter',
546
            'John Smith',
547
            'Test Persona',
548
            'Jane Stockwriter',
549
            'James Q. Reporter',
550
            'Karen Ruhiger',
551
            'George Langsamer',
552
        ];
553
554
        return [
555
            'located' => 'Sydney',
556
            'byline' => $authors[array_rand($authors)],
557
            'place' => [
558
                [
559
                    'qcode' => 'AUS',
560
                    'world_region' => 'Rest Of World',
561
                ], [
562
                    'qcode' => 'EUR',
563
                    'world_region' => 'Europe',
564
                ],
565
            ],
566
        ];
567
    }
568
569
    private function cropAndResizeImage($fakeImage, array $rendition, $targetFile)
570
    {
571
        $image = imagecreatefromjpeg($fakeImage);
572
        list($width, $height) = getimagesize($fakeImage);
573
574
        $renditionWidth = (int) $rendition['width'];
575
        $renditionHeight = (int) $rendition['height'];
576
577
        $aspectRatio = $width / $height;
578
        $newImageAspectRatio = $renditionWidth / $renditionHeight;
579
580
        if ($aspectRatio >= $newImageAspectRatio) {
581
            $newImageHeight = $renditionHeight;
582
            $newImageWidth = $width / ($height / $renditionHeight);
583
        } else {
584
            $newImageWidth = $renditionWidth;
585
            $newImageHeight = $height / ($width / $renditionWidth);
586
        }
587
588
        $newImage = imagecreatetruecolor($renditionWidth, $renditionHeight);
589
590
        imagecopyresampled($newImage,
591
            $image,
592
            0 - ($newImageWidth - $renditionWidth) / 2,
593
            0 - ($newImageHeight - $renditionHeight) / 2,
594
            0,
595
            0,
596
            $newImageWidth,
597
            $newImageHeight,
598
            $width,
599
            $height);
600
        imagejpeg($newImage, $targetFile, 80);
601
602
        imagedestroy($newImage);
603
        unset($image);
604
    }
605
606
    /**
607
     * {@inheritdoc}
608
     */
609
    public function getOrder()
610
    {
611
        return 1;
612
    }
613
}
614