Completed
Push — 0.1 ( 75f716...d81107 )
by Paweł
96:48 queued 48:27
created

ProcessArticleMediaListener   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 137
Duplicated Lines 8.76 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 26.32%

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 9
dl 12
loc 137
ccs 15
cts 57
cp 0.2632
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
C onArticleCreate() 12 29 11
A removeArticleMediaIfNeeded() 0 11 2
A handleMedia() 0 12 3
B replaceBodyImagesWithMedia() 0 33 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 * This file is part of the Superdesk Web Publisher Content Bundle.
5
 *
6
 * Copyright 2016 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\ContentBundle\EventListener;
16
17
use SWP\Bundle\ContentBundle\Doctrine\ArticleMediaRepositoryInterface;
18
use SWP\Bundle\ContentBundle\Doctrine\ORM\ArticleMediaRepository;
19
use SWP\Bundle\ContentBundle\Event\ArticleEvent;
20
use SWP\Bundle\ContentBundle\Factory\MediaFactoryInterface;
21
use SWP\Bundle\ContentBundle\Manager\MediaManagerInterface;
22
use SWP\Bundle\ContentBundle\Model\ArticleInterface;
23
use SWP\Bundle\ContentBundle\Model\ArticleMediaInterface;
24
use SWP\Component\Bridge\Model\ItemInterface;
25
use Symfony\Component\DomCrawler\Crawler;
26
27
class ProcessArticleMediaListener
28
{
29
    /**
30
     * @var ArticleMediaRepository
31
     */
32
    protected $articleMediaRepository;
33
34
    /**
35
     * @var MediaManagerInterface
36
     */
37
    protected $mediaManager;
38
39
    /**
40
     * @var MediaFactoryInterface
41
     */
42
    protected $mediaFactory;
43
44
    /**
45
     * ProcessArticleMediaListener constructor.
46
     *
47
     * @param ArticleMediaRepositoryInterface $articleMediaRepository
48
     * @param MediaManagerInterface           $mediaManager
49
     * @param MediaFactoryInterface           $mediaFactory
50
     */
51 6
    public function __construct(
52
        ArticleMediaRepositoryInterface $articleMediaRepository,
53
        MediaManagerInterface $mediaManager,
54
        MediaFactoryInterface $mediaFactory
55
    ) {
56 6
        $this->articleMediaRepository = $articleMediaRepository;
0 ignored issues
show
Documentation Bug introduced by
$articleMediaRepository is of type object<SWP\Bundle\Conten...diaRepositoryInterface>, but the property $articleMediaRepository was declared to be of type object<SWP\Bundle\Conten...ArticleMediaRepository>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
57 6
        $this->mediaManager = $mediaManager;
58 6
        $this->mediaFactory = $mediaFactory;
59 6
    }
60
61
    /**
62
     * @param ArticleEvent $event
63
     */
64 6
    public function onArticleCreate(ArticleEvent $event)
65
    {
66 6
        $package = $event->getPackage();
67 6
        $article = $event->getArticle();
68
69 6
        if (null !== $package && 0 === count($package->getItems())) {
70 3
            return;
71
        }
72
73 3
        foreach ($package->getItems() as $key => $packageItem) {
74 3 View Code Duplication
            if (ItemInterface::TYPE_PICTURE === $packageItem->getType() || ItemInterface::TYPE_FILE === $packageItem->getType()) {
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...
75
                $this->removeArticleMediaIfNeeded($key, $article);
76
77
                $articleMedia = $this->handleMedia($article, $key, $packageItem);
78
                $this->articleMediaRepository->persist($articleMedia);
79
            }
80
81 3
            if (null !== $packageItem->getItems() && 0 !== $packageItem->getItems()->count()) {
82
                foreach ($packageItem->getItems() as $key => $item) {
83 View Code Duplication
                    if (ItemInterface::TYPE_PICTURE === $item->getType() || ItemInterface::TYPE_FILE === $item->getType()) {
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...
84
                        $this->removeArticleMediaIfNeeded($key, $article);
85
86
                        $articleMedia = $this->handleMedia($article, $key, $item);
87 3
                        $this->articleMediaRepository->persist($articleMedia);
88
                    }
89
                }
90
            }
91
        }
92 3
    }
93
94
    private function removeArticleMediaIfNeeded($key, ArticleInterface $article)
95
    {
96
        $existingArticleMedia = $this->articleMediaRepository->findOneBy([
97
            'key' => $key,
98
            'article' => $article->getId(),
99
        ]);
100
101
        if (null !== $existingArticleMedia) {
102
            $this->articleMediaRepository->remove($existingArticleMedia);
103
        }
104
    }
105
106
    /**
107
     * @param ArticleInterface $article
108
     * @param string           $key
109
     * @param ItemInterface    $item
110
     *
111
     * @return ArticleMediaInterface
112
     */
113
    public function handleMedia(ArticleInterface $article, string $key, ItemInterface $item)
114
    {
115
        $articleMedia = $this->mediaFactory->create($article, $key, $item);
116
117
        if (ItemInterface::TYPE_PICTURE === $item->getType()) {
118
            $this->replaceBodyImagesWithMedia($article, $articleMedia);
119
        } elseif (ItemInterface::TYPE_FILE === $item->getType()) {
0 ignored issues
show
Unused Code introduced by
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
120
            //TODO: handle files upload
121
        }
122
123
        return $articleMedia;
124
    }
125
126
    /**
127
     * @param ArticleInterface      $article
128
     * @param ArticleMediaInterface $articleMedia
129
     */
130
    private function replaceBodyImagesWithMedia(ArticleInterface $article, ArticleMediaInterface $articleMedia)
131
    {
132
        $body = $article->getBody();
133
        $mediaId = $articleMedia->getKey();
134
        preg_match(
135
            "/(<!-- EMBED START Image {id: \"$mediaId\"} -->)(.+?)(<!-- EMBED END Image {id: \"$mediaId\"} -->)/im",
136
            str_replace(PHP_EOL, '', $body),
137
            $embeds
138
        );
139
        if (empty($embeds)) {
140
            return;
141
        }
142
143
        $figureString = $embeds[2];
144
        $crawler = new Crawler($figureString);
145
        $images = $crawler->filter('figure img');
146
        /** @var \DOMElement $imageElement */
147
        foreach ($images as $imageElement) {
148
            foreach ($articleMedia->getRenditions() as $rendition) {
149
                if (strpos($imageElement->getAttribute('src'), $rendition->getImage()->getAssetId()) !== false) {
150
                    $attributes = $imageElement->attributes;
151
                    while ($attributes->length) {
152
                        $imageElement->removeAttribute($attributes->item(0)->name);
153
                    }
154
                    $imageElement->setAttribute('src', $this->mediaManager->getMediaUri($rendition->getImage()));
155
                    $imageElement->setAttribute('data-media-id', $mediaId);
156
                    $imageElement->setAttribute('data-image-id', $rendition->getImage()->getAssetId());
157
                }
158
            }
159
        }
160
161
        $article->setBody(str_replace($figureString, $crawler->filter('body')->html(), $body));
162
    }
163
}
164