Completed
Push — master ( 4da1f4...8b580e )
by Paweł
08:27
created

LoadArticlesData::loadRoutes()   C

Complexity

Conditions 7
Paths 17

Size

Total Lines 161
Code Lines 101

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 8.5786

Importance

Changes 0
Metric Value
dl 0
loc 161
rs 6.4589
c 0
b 0
f 0
ccs 15
cts 22
cp 0.6818
cc 7
eloc 101
nc 17
nop 2
crap 8.5786

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\PackageInterface;
26
use SWP\Bundle\FixturesBundle\AbstractFixture;
27
use Symfony\Component\HttpFoundation\File\UploadedFile;
28
29
class LoadArticlesData extends AbstractFixture implements FixtureInterface, OrderedFixtureInterface
30
{
31
    private $manager;
32 5
33
    /**
34 5
     * {@inheritdoc}
35 5
     */
36
    public function load(ObjectManager $manager)
37 5
    {
38 5
        $this->manager = $manager;
39
        $env = $this->getEnvironment();
40 5
41 5
        $tenantContext = $this->container->get('swp_multi_tenancy.tenant_context');
42
        $mediaManager = $this->container->get('swp_content_bundle.manager.media');
43 5
        if (null === $tenantContext->getTenant()) {
44
            $tenantContext->setTenant(
45
                $this->container->get('swp.repository.tenant')->findOneByCode('123abc')
46
            );
47
        }
48
        $mediaManager->setTenantContext($tenantContext);
49
50
        $this->loadRoutes($env, $manager);
51
        $this->loadArticles($env, $manager);
52
53
        $manager->flush();
54
    }
55
56
    public function loadRoutes($env, $manager)
57
    {
58
        $routes = [
59
            'dev' => [
60
                [
61
                    'name' => 'politics',
62
                    'variablePattern' => '/{slug}',
63
                    'requirements' => [
64
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
65
                    ],
66
                    'type' => 'collection',
67
                    'defaults' => [
68
                        'slug' => null,
69
                    ],
70
                    'templateName' => 'category.html.twig',
71
                    'articlesTemplateName' => 'article.html.twig',
72
                ],
73
                [
74
                    'name' => 'business',
75
                    'variablePattern' => '/{slug}',
76
                    'requirements' => [
77
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
78
                    ],
79
                    'type' => 'collection',
80
                    'defaults' => [
81
                        'slug' => null,
82
                    ],
83
                    'templateName' => 'category.html.twig',
84
                    'articlesTemplateName' => 'article.html.twig',
85
                ],
86
                [
87
                    'name' => 'scitech',
88
                    'variablePattern' => '/{slug}',
89
                    'requirements' => [
90
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
91
                    ],
92
                    'type' => 'collection',
93
                    'defaults' => [
94
                        'slug' => null,
95
                    ],
96
                    'templateName' => 'category.html.twig',
97
                    'articlesTemplateName' => 'article.html.twig',
98
                ],
99
                [
100
                    'name' => 'health',
101
                    'variablePattern' => '/{slug}',
102
                    'requirements' => [
103
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
104
                    ],
105
                    'type' => 'collection',
106
                    'defaults' => [
107
                        'slug' => null,
108
                    ],
109
                    'templateName' => 'category.html.twig',
110
                    'articlesTemplateName' => 'article.html.twig',
111
                ],
112
                [
113
                    'name' => 'entertainment',
114
                    'variablePattern' => '/{slug}',
115
                    'requirements' => [
116
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
117
                    ],
118
                    'type' => 'collection',
119
                    'defaults' => [
120
                        'slug' => null,
121
                    ],
122
                    'templateName' => 'category.html.twig',
123
                    'articlesTemplateName' => 'article.html.twig',
124
                ],
125
                [
126
                    'name' => 'sports',
127
                    'variablePattern' => '/{slug}',
128
                    'requirements' => [
129
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
130
                    ],
131
                    'type' => 'collection',
132
                    'defaults' => [
133
                        'slug' => null,
134
                    ],
135
                    'templateName' => 'category.html.twig',
136
                    'articlesTemplateName' => 'article.html.twig',
137
                ],
138
                [
139
                    'name' => 'about',
140
                    'variablePattern' => '/{slug}',
141
                    'requirements' => [
142 5
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
143
                    ],
144
                    'type' => 'collection',
145
                    'defaults' => [
146
                        'slug' => null,
147
                    ],
148
                    'articlesTemplateName' => 'page.html.twig',
149
                ],
150
                [
151
                    'name' => 'home',
152
                    'type' => 'content',
153
                    'templateName' => 'index.html.twig',
154
                ],
155
            ],
156
            'test' => [
157
                [
158
                    'name' => 'news',
159
                    'variablePattern' => '/{slug}',
160
                    'requirements' => [
161
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
162
                    ],
163
                    'type' => 'collection',
164
                    'defaults' => [
165
                        'slug' => null,
166 5
                    ],
167
                ],
168 5
                [
169 5
                    'name' => 'articles',
170 5
                    'type' => 'content',
171 5
                ],
172
                [
173 5
                    'name' => 'articles/features',
174
                    'type' => 'content',
175
                ],
176
                [
177 5
                    'name' => 'sports',
178
                    'type' => 'collection',
179
                    'parentName' => 'news',
180
                ],
181 5
            ],
182
        ];
183
184
        $routeService = $this->container->get('swp.service.route');
185 5
186
        $persistedRoutes = [];
187 5
        foreach ($routes[$env] as $routeData) {
188
            /** @var RouteInterface $route */
189
            $route = $this->container->get('swp.factory.route')->create();
190 5
            $route->setName($routeData['name']);
191 5
            $route->setType($routeData['type']);
192
193
            if (isset($routeData['cacheTimeInSeconds'])) {
194
                $route->setCacheTimeInSeconds($routeData['cacheTimeInSeconds']);
195
            }
196
197 5
            if (isset($routeData['templateName'])) {
198
                $route->setTemplateName($routeData['templateName']);
199 5
            }
200
201
            if (isset($routeData['articlesTemplateName'])) {
202
                $route->setArticlesTemplateName($routeData['articlesTemplateName']);
203
            }
204
205
            if (isset($routeData['parentName']) && isset($persistedRoutes[$routeData['parentName']])) {
206
                $route->setParent($persistedRoutes[$routeData['parentName']]);
207
            }
208
209
            $route = $routeService->fillRoute($route);
210
211
            $manager->persist($route);
212
            $persistedRoutes[$route->getName()] = $route;
213
        }
214
215
        $manager->flush();
216
    }
217
218
    /**
219
     * Sets articles manually (not via Alice) for test env due to fatal error:
220
     * Method PHPCRProxies\__CG__\Doctrine\ODM\PHPCR\Document\Generic::__toString() must not throw an exception.
221
     */
222
    public function loadArticles($env, ObjectManager $manager)
223
    {
224
        if ('test' !== $env) {
225
            $this->loadFixtures([
226
                '@SWPFixturesBundle/Resources/fixtures/ORM/'.$env.'/package.yml',
227
            ],
228
                $manager,
229
                [
230
                    'providers' => [$this],
231
                ]
232
            );
233
234
            $articles = $this->loadFixtures([
235
                    '@SWPFixturesBundle/Resources/fixtures/ORM/'.$env.'/article.yml',
236
                ],
237
                $manager,
238
                [
239
                    'providers' => [$this],
240
                ],
241
                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...
242
            );
243
244
            $renditions = [
245
                'original' => [],
246
                '770x515' => [
247
                    'width' => '770',
248
                    'height' => '515',
249
                ],
250
                '478x326' => [
251
                    'width' => '478',
252
                    'height' => '326',
253
                ],
254
                '480x480' => [
255
                    'width' => '480',
256
                    'height' => '480',
257
                ],
258
                '960x480' => [
259
                    'width' => '960',
260
                    'height' => '480',
261
                ],
262
                '600x360' => [
263
                    'width' => '600',
264
                    'height' => '360',
265
                ],
266
                '400x240' => [
267
                    'width' => '400',
268
                    'height' => '240',
269
                ],
270
                '1000x1000' => [
271
                    'width' => '1000',
272
                    'height' => '1000',
273
                ],
274
                '610x380' => [
275
                    'width' => '610',
276
                    'height' => '380',
277
                ],
278
                '1250x600' => [
279
                    'width' => '1250',
280
                    'height' => '600',
281
                ],
282
            ];
283
284
            $mediaManager = $this->container->get('swp_content_bundle.manager.media');
285
286
            foreach ($renditions as $key => $rendition) {
287
                if ('original' === $key) {
288
                    continue;
289
                }
290
291
                for ($i = 1; $i <= 9; ++$i) {
292
                    $filename = '/tmp/'.$i.'org'.$key.'.jpg';
293
                    if (file_exists($filename)) {
294
                        continue;
295
                    }
296
297
                    $fakeImage = __DIR__.'/../../Resources/assets/'.$i.'org.jpg';
298
                    $this->cropAndResizeImage($fakeImage, $rendition, $filename);
299
                }
300
            }
301
302
            foreach ($articles as $article) {
303
                // randomly create two media (images) for each of the article
304
                for ($i = 0; $i < 2; ++$i) {
305
                    // create Media
306
                    $articleMediaClass = $this->container->getParameter('swp.model.media.class');
307
                    $articleMedia = new $articleMediaClass();
308
                    $articleMedia->setArticle($article);
309
                    $articleMedia->setKey('embedded'.uniqid());
310
                    $articleMedia->setBody('This is very nice image caption...');
311
                    $articleMedia->setByLine('By Best Editor');
312
                    $articleMedia->setLocated('Porto');
313
                    $articleMedia->setDescription('Media description');
314
                    $articleMedia->setUsageTerms('Some super open terms');
315
                    $articleMedia->setMimetype('image/jpeg');
316
                    $manager->persist($articleMedia);
317
318
                    $randNumber = rand(1, 9);
319
                    /* @var $rendition Rendition */
320
                    foreach ($renditions as $key => $rendition) {
321
                        if ('original' === $key) {
322
                            $fakeImage = __DIR__.'/../../Resources/assets/'.$randNumber.'org.jpg';
323
                            list($width, $height) = getimagesize($fakeImage);
324
                            $rendition['height'] = $height;
325
                            $rendition['width'] = $width;
326
                        } else {
327
                            $fakeImage = '/tmp/'.$randNumber.'org'.$key.'.jpg';
328
                        }
329
330
                        $mediaId = uniqid();
331
                        $uploadedFile = new UploadedFile(
332
                            $fakeImage,
333
                            $mediaId,
334
                            'image/jpeg',
335
                            filesize($fakeImage),
336 5
                            null,
337
                            true
338
                        );
339 5
                        $image = $mediaManager->handleUploadedFile($uploadedFile, $mediaId);
340 5
                        $articleMedia->setImage($image);
341 5
342 5
                        $imageRendition = new ImageRendition();
343 5
                        $imageRendition->setImage($image);
344 5
                        $imageRendition->setHeight($rendition['height']);
345 5
                        $imageRendition->setWidth($rendition['width']);
346 5
                        $imageRendition->setName($key);
347 5
                        $imageRendition->setMedia($articleMedia);
348 5
                        $articleMedia->addRendition($imageRendition);
349 5
                        $manager->persist($imageRendition);
350
                    }
351 5
                }
352
            }
353
        }
354 5
355
        $articles = [
356 5
            'test' => [
357
                [
358
                    'title' => 'Test news article',
359
                    'content' => 'Test news article content',
360
                    'route' => 'news',
361
                    'locale' => 'en',
362
                    'pageViews' => 20,
363
                ],
364
                [
365
                    'title' => 'Test news sports article',
366
                    'content' => 'Test news sports article content',
367
                    'route' => 'sports',
368
                    'locale' => 'en',
369
                    'pageViews' => 30,
370
                ],
371
                [
372
                    'title' => 'Test article',
373
                    'content' => 'Test article content',
374
                    'route' => 'news',
375
                    'locale' => 'en',
376
                    'pageViews' => 10,
377
                ],
378
                [
379
                    'title' => 'Features',
380
                    'content' => 'Features content',
381
                    'route' => 'news',
382
                    'locale' => 'en',
383
                    'pageViews' => 5,
384
                ],
385
                [
386
                    'title' => 'Features client1',
387
                    'content' => 'Features client1 content',
388
                    'route' => 'articles/features',
389
                    'locale' => 'en',
390
                    'pageViews' => 0,
391
                ],
392
            ],
393
        ];
394
395
        $sources = ['Forbes', 'Reuters'];
396
        $secondSources = ['AAP', 'AFP'];
397
        $authors = ['John Doe', 'Test Person', 'Tom'];
398
399
        if (isset($articles[$env])) {
400
            $articleService = $this->container->get('swp.service.article');
401
            $sourcesFactory = $this->container->get('swp.factory.article_source');
402
            $articleSourcesService = $this->container->get('swp.service.article_source');
403
            foreach ($articles[$env] as $articleData) {
404
                /** @var ArticleInterface $article */
405
                $article = $this->container->get('swp.factory.article')->create();
406
                $article->setTitle($articleData['title']);
407
                $article->setBody($articleData['content']);
408
                $article->setRoute($this->getRouteByName($articleData['route']));
409
                $article->setLocale($articleData['locale']);
410
                $article->setCode(md5($articleData['title']));
411
                $article->setKeywords($this->articleKeywords());
412
413
                $author = new ArticleAuthor();
414
                $author->setRole('Writer');
415
                $author->setName($authors[array_rand($authors)]);
416
                $article->addAuthor($author);
417
418
                $articleSource = $sourcesFactory->create();
419
                $articleSource->setName($sources[array_rand($sources)]);
420
                $article->addSourceReference($articleSourcesService->getArticleSourceReference($article, $articleSource));
421
                $articleSourceSecond = $sourcesFactory->create();
422
                $articleSourceSecond->setName($secondSources[array_rand($secondSources)]);
423
                $article->addSourceReference($articleSourcesService->getArticleSourceReference($article, $articleSourceSecond));
424
                $package = $this->createPackage($articleData);
425
                $articleStatistics = $this->createArticleStatistics($articleData['pageViews'], $article);
426
                $manager->persist($articleStatistics);
427
                $manager->persist($package);
428
                $article->setPackage($package);
429
                $manager->persist($article);
430
                $articleService->publish($article);
431
432
                $this->addReference($article->getSlug(), $article);
433
            }
434
435
            $manager->flush();
436
        }
437
    }
438
439 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...
440
    {
441
        /** @var PackageInterface $package */
442
        $package = $this->container->get('swp.factory.package')->create();
443
        $package->setHeadline($articleData['title']);
444
        $package->setType('text');
445
        $package->setPubStatus('usable');
446
        $package->setGuid($this->container->get('swp_multi_tenancy.random_string_generator')->generate(10));
447
        $package->setLanguage('en');
448 5
        $package->setUrgency(1);
449
        $package->setPriority(1);
450 5
        $package->setVersion(1);
451
452
        return $package;
453
    }
454
455
    private function createArticleStatistics(int $pageViewsNumber, ArticleInterface $article)
456
    {
457
        /** @var ArticleStatisticsInterface $articleStatistics */
458
        $articleStatistics = $this->container->get('swp.factory.article_statistics')->create();
459
        $articleStatistics->setArticle($article);
460
        $articleStatistics->setPageViewsNumber($pageViewsNumber);
461
462
        return $articleStatistics;
463
    }
464
465
    /**
466
     * @return array
467
     */
468
    public function articleKeywords()
469
    {
470
        $keywords = [
471
            'city',
472
            'traffic',
473
            'car',
474
            'news',
475
            'building',
476
        ];
477
478
        shuffle($keywords);
479
480
        return $keywords;
481
    }
482
483
    /**
484
     * Article example metadata.
485
     *
486
     * @return array
487
     */
488
    public function articleMetadata()
489
    {
490
        $authors = [
491
            'Sarrah Staffwriter',
492
            'John Smith',
493
            'Test Persona',
494
            'Jane Stockwriter',
495
            'James Q. Reporter',
496
            'Karen Ruhiger',
497
            'George Langsamer',
498
        ];
499
500
        return [
501
            'located' => 'Sydney',
502
            'byline' => $authors[array_rand($authors)],
503
            'place' => [
504
                [
505
                    'qcode' => 'AUS',
506
                    'world_region' => 'Rest Of World',
507
                ], [
508
                    'qcode' => 'EUR',
509
                    'world_region' => 'Europe',
510
                ],
511
            ],
512
        ];
513
    }
514
515
    private function cropAndResizeImage($fakeImage, array $rendition, $targetFile)
516
    {
517
        $image = imagecreatefromjpeg($fakeImage);
518
        list($width, $height) = getimagesize($fakeImage);
519
520
        $renditionWidth = (int) $rendition['width'];
521
        $renditionHeight = (int) $rendition['height'];
522
523
        $aspectRatio = $width / $height;
524
        $newImageAspectRatio = $renditionWidth / $renditionHeight;
525
526
        if ($aspectRatio >= $newImageAspectRatio) {
527
            $newImageHeight = $renditionHeight;
528
            $newImageWidth = $width / ($height / $renditionHeight);
529
        } else {
530
            $newImageWidth = $renditionWidth;
531
            $newImageHeight = $height / ($width / $renditionWidth);
532
        }
533
534
        $newImage = imagecreatetruecolor($renditionWidth, $renditionHeight);
535
536
        imagecopyresampled($newImage,
537
            $image,
538
            0 - ($newImageWidth - $renditionWidth) / 2,
539
            0 - ($newImageHeight - $renditionHeight) / 2,
540
            0,
541
            0,
542
            $newImageWidth,
543
            $newImageHeight,
544
            $width,
545
            $height);
546
        imagejpeg($newImage, $targetFile, 80);
547
548
        imagedestroy($newImage);
549
        unset($image);
550
    }
551
552
    /**
553
     * {@inheritdoc}
554
     */
555
    public function getOrder()
556
    {
557
        return 1;
558
    }
559
}
560