Passed
Push — master ( 501fc3...f64e27 )
by Paweł
47:53
created

LoadArticlesData::cropAndResizeImage()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 36
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 0
cts 22
cp 0
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 27
nc 2
nop 3
crap 6
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\ContentBundle\Model\ImageRendition;
21
use SWP\Bundle\FixturesBundle\AbstractFixture;
22
use SWP\Bundle\ContentBundle\Model\ArticleInterface;
23
use Symfony\Component\HttpFoundation\File\UploadedFile;
24
25
class LoadArticlesData extends AbstractFixture implements FixtureInterface, OrderedFixtureInterface
26
{
27
    private $manager;
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 5
    public function load(ObjectManager $manager)
33
    {
34 5
        $this->manager = $manager;
35 5
        $env = $this->getEnvironment();
36
37 5
        $this->loadRoutes($env, $manager);
38 5
        $this->loadArticles($env, $manager);
39
40 5
        $manager->flush();
41 5
    }
42
43 5
    public function loadRoutes($env, $manager)
44
    {
45
        $routes = [
46
            'dev' => [
47
                [
48
                    'name' => 'politics',
49
                    'variablePattern' => '/{slug}',
50
                    'requirements' => [
51
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
52
                    ],
53
                    'type' => 'collection',
54
                    'defaults' => [
55
                        'slug' => null,
56
                    ],
57
                    'templateName' => 'category.html.twig',
58
                    'articlesTemplateName' => 'article.html.twig',
59
                ],
60
                [
61
                    'name' => 'business',
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' => 'scitech',
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' => 'health',
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' => 'entertainment',
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' => 'sports',
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' => 'about',
127
                    'variablePattern' => '/{slug}',
128
                    'requirements' => [
129
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
130
                    ],
131
                    'type' => 'collection',
132
                    'defaults' => [
133
                        'slug' => null,
134
                    ],
135
                    'articlesTemplateName' => 'page.html.twig',
136
                ],
137
                [
138
                    'name' => 'home',
139
                    'type' => 'content',
140
                    'templateName' => 'index.html.twig',
141
                ],
142 5
            ],
143
            'test' => [
144
                [
145
                    'name' => 'news',
146
                    'variablePattern' => '/{slug}',
147
                    'requirements' => [
148
                        'slug' => '[a-zA-Z0-9*\-_\/]+',
149
                    ],
150
                    'type' => 'collection',
151
                    'defaults' => [
152
                        'slug' => null,
153
                    ],
154
                ],
155
                [
156
                    'name' => 'articles',
157
                    'type' => 'content',
158
                ],
159
                [
160
                    'name' => 'articles/features',
161
                    'type' => 'content',
162
                ],
163
            ],
164
        ];
165
166 5
        $routeService = $this->container->get('swp.service.route');
167
168 5 View Code Duplication
        foreach ($routes[$env] as $routeData) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
169 5
            $route = $this->container->get('swp.factory.route')->create();
170 5
            $route->setName($routeData['name']);
171 5
            $route->setType($routeData['type']);
172
173 5
            if (isset($routeData['cacheTimeInSeconds'])) {
174
                $route->setCacheTimeInSeconds($routeData['cacheTimeInSeconds']);
175
            }
176
177 5
            if (isset($routeData['templateName'])) {
178
                $route->setTemplateName($routeData['templateName']);
179
            }
180
181 5
            if (isset($routeData['articlesTemplateName'])) {
182
                $route->setArticlesTemplateName($routeData['articlesTemplateName']);
183
            }
184
185 5
            $route = $routeService->fillRoute($route);
186
187 5
            $manager->persist($route);
188
        }
189
190 5
        $manager->flush();
191 5
    }
192
193
    /**
194
     * Sets articles manually (not via Alice) for test env due to fatal error:
195
     * Method PHPCRProxies\__CG__\Doctrine\ODM\PHPCR\Document\Generic::__toString() must not throw an exception.
196
     */
197 5
    public function loadArticles($env, ObjectManager $manager)
198
    {
199 5
        if ($env !== 'test') {
200
            $articles = $this->loadFixtures(
201
                '@SWPFixturesBundle/Resources/fixtures/ORM/'.$env.'/article.yml',
202
                $manager,
203
                [
204
                    'providers' => [$this],
205
                ]
206
            );
207
208
            $renditions = [
209
                'original' => [],
210
                '770x515' => [
211
                    'width' => '770',
212
                    'height' => '515',
213
                ],
214
                '478x326' => [
215
                    'width' => '478',
216
                    'height' => '326',
217
                ],
218
                '960x480' => [
219
                    'width' => '960',
220
                    'height' => '480',
221
                ],
222
                '600x360' => [
223
                    'width' => '600',
224
                    'height' => '360',
225
                ],
226
                '400x240' => [
227
                    'width' => '400',
228
                    'height' => '240',
229
                ],
230
                '1000x1000' => [
231
                    'width' => '1000',
232
                    'height' => '1000',
233
                ],
234
            ];
235
236
            $mediaManager = $this->container->get('swp_content_bundle.manager.media');
237
238
            foreach ($renditions as $key => $rendition) {
239
                if ('original' === $key) {
240
                    continue;
241
                }
242
243
                for ($i = 1; $i <= 9; ++$i) {
244
                    $filename = '/tmp/'.$i.'org'.$key.'.jpg';
245
                    if (file_exists($filename)) {
246
                        continue;
247
                    }
248
249
                    $fakeImage = __DIR__.'/../../Resources/assets/'.$i.'org.jpg';
250
                    $this->cropAndResizeImage($fakeImage, $rendition, $filename);
251
                }
252
            }
253
254
            foreach ($articles as $article) {
255
                // randomly create two media (images) for each of the article
256
                for ($i = 0; $i < 2; ++$i) {
257
                    // create Media
258
                    $articleMediaClass = $this->container->getParameter('swp.model.media.class');
259
                    $articleMedia = new $articleMediaClass();
260
                    $articleMedia->setArticle($article);
261
                    $articleMedia->setKey('embedded'.uniqid());
262
                    $articleMedia->setBody('This is very nice image caption...');
263
                    $articleMedia->setByLine('By Best Editor');
264
                    $articleMedia->setLocated('Porto');
265
                    $articleMedia->setDescription('Media description');
266
                    $articleMedia->setUsageTerms('Some super open terms');
267
                    $articleMedia->setMimetype('image/jpeg');
268
                    $manager->persist($articleMedia);
269
270
                    $randNumber = rand(1, 9);
271
                    /* @var $rendition Rendition */
272
                    foreach ($renditions as $key => $rendition) {
273
                        if ('original' === $key) {
274
                            $fakeImage = __DIR__.'/../../Resources/assets/'.$randNumber.'org.jpg';
275
                            list($width, $height) = getimagesize($fakeImage);
276
                            $rendition['height'] = $height;
277
                            $rendition['width'] = $width;
278
                        } else {
279
                            $fakeImage = '/tmp/'.$randNumber.'org'.$key.'.jpg';
280
                        }
281
282
                        $mediaId = uniqid();
283
                        $uploadedFile = new UploadedFile(
284
                            $fakeImage,
285
                            $mediaId,
286
                            'image/jpeg',
287
                            filesize($fakeImage),
288
                            null,
289
                            true
290
                        );
291
                        $image = $mediaManager->handleUploadedFile($uploadedFile, $mediaId);
292
293
                        $imageRendition = new ImageRendition();
294
                        $imageRendition->setImage($image);
295
                        $imageRendition->setHeight($rendition['height']);
296
                        $imageRendition->setWidth($rendition['width']);
297
                        $imageRendition->setName($key);
298
                        $imageRendition->setMedia($articleMedia);
299
                        $articleMedia->addRendition($imageRendition);
300
                        $manager->persist($imageRendition);
301
                    }
302
                }
303
            }
304
        }
305
306
        $articles = [
307
            'test' => [
308
                [
309
                    'title' => 'Test news article',
310
                    'content' => 'Test news article content',
311
                    'route' => 'news',
312
                    'locale' => 'en',
313
                ],
314
                [
315
                    'title' => 'Test article',
316
                    'content' => 'Test article content',
317
                    'route' => 'news',
318
                    'locale' => 'en',
319
                ],
320
                [
321
                    'title' => 'Features',
322
                    'content' => 'Features content',
323
                    'route' => 'news',
324
                    'locale' => 'en',
325
                ],
326
                [
327
                    'title' => 'Features client1',
328
                    'content' => 'Features client1 content',
329
                    'route' => 'articles/features',
330
                    'locale' => 'en',
331
                ],
332 5
            ],
333
        ];
334
335 5
        if (isset($articles[$env])) {
336 5 View Code Duplication
            foreach ($articles[$env] as $articleData) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
337 5
                $article = $this->container->get('swp.factory.article')->create();
338 5
                $article->setTitle($articleData['title']);
339 5
                $article->setBody($articleData['content']);
340 5
                $article->setRoute($this->getRouteByName($articleData['route']));
341 5
                $article->setLocale($articleData['locale']);
342 5
                $article->setPublishable(true);
343 5
                $article->setPublishedAt(new \DateTime());
344 5
                $article->setStatus(ArticleInterface::STATUS_PUBLISHED);
345 5
                $manager->persist($article);
346
347 5
                $this->addReference($article->getSlug(), $article);
348
            }
349
350 5
            $manager->flush();
351
        }
352 5
    }
353
354
    /**
355
     * Article example metadata.
356
     *
357
     * @return array
358
     */
359
    public function articleMetadata()
360
    {
361
        $authors = [
362
            'Sarrah Staffwriter',
363
            'John Smith',
364
            'Test Persona',
365
            'Jane Stockwriter',
366
            'James Q. Reporter',
367
            'Karen Ruhiger',
368
            'George Langsamer',
369
        ];
370
371
        return [
372
            'located' => 'Sydney',
373
            'byline' => $authors[array_rand($authors)],
374
            'place' => [
375
                [
376
                    'qcode' => 'AUS',
377
                    'world_region' => 'Rest Of World',
378
                ], [
379
                    'qcode' => 'EUR',
380
                    'world_region' => 'Europe',
381
                ],
382
            ],
383
        ];
384
    }
385
386
    private function cropAndResizeImage($fakeImage, array $rendition, $targetFile)
387
    {
388
        $image = imagecreatefromjpeg($fakeImage);
389
        list($width, $height) = getimagesize($fakeImage);
390
391
        $renditionWidth = (int) $rendition['width'];
392
        $renditionHeight = (int) $rendition['height'];
393
394
        $aspectRatio = $width / $height;
395
        $newImageAspectRatio = $renditionWidth / $renditionHeight;
396
397
        if ($aspectRatio >= $newImageAspectRatio) {
398
            $newImageHeight = $renditionHeight;
399
            $newImageWidth = $width / ($height / $renditionHeight);
400
        } else {
401
            $newImageWidth = $renditionWidth;
402
            $newImageHeight = $height / ($width / $renditionWidth);
403
        }
404
405
        $newImage = imagecreatetruecolor($renditionWidth, $renditionHeight);
406
407
        imagecopyresampled($newImage,
408
            $image,
409
            0 - ($newImageWidth - $renditionWidth) / 2,
410
            0 - ($newImageHeight - $renditionHeight) / 2,
411
            0,
412
            0,
413
            $newImageWidth,
414
            $newImageHeight,
415
            $width,
416
            $height);
417
        imagejpeg($newImage, $targetFile, 80);
418
419
        imagedestroy($newImage);
420
        unset($image);
421
    }
422
423
    /**
424
     * {@inheritdoc}
425
     */
426 5
    public function getOrder()
427
    {
428 5
        return 1;
429
    }
430
}
431