Completed
Push — master ( af5cb4...f7d729 )
by Tim
12s
created

ClearMediaGalleryObserver::process()   C

Complexity

Conditions 11
Paths 42

Size

Total Lines 64
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
dl 0
loc 64
ccs 0
cts 42
cp 0
rs 6.0563
c 0
b 0
f 0
cc 11
eloc 31
nc 42
nop 0
crap 132

How to fix   Long Method    Complexity   

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
 * TechDivision\Import\Product\Media\Observers\ClearMediaGalleryObserver
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2016 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import-product-media
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Product\Media\Observers;
22
23
use TechDivision\Import\Product\Media\Utils\ColumnKeys;
24
use TechDivision\Import\Product\Media\Utils\MemberNames;
25
use TechDivision\Import\Product\Observers\AbstractProductImportObserver;
26
use TechDivision\Import\Product\Media\Services\ProductMediaProcessorInterface;
27
28
/**
29
 * Observer that cleaned up a product's media gallery information.
30
 *
31
 * @author    Tim Wagner <[email protected]>
32
 * @copyright 2016 TechDivision GmbH <[email protected]>
33
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
34
 * @link      https://github.com/techdivision/import-product-media
35
 * @link      http://www.techdivision.com
36
 */
37
class ClearMediaGalleryObserver extends AbstractProductImportObserver
38
{
39
40
    /**
41
     * The product media processor instance.
42
     *
43
     * @var \TechDivision\Import\Product\Media\Services\ProductMediaProcessorInterface
44
     */
45
    protected $productMediaProcessor;
46
47
    /**
48
     * Initialize the observer with the passed product media processor instance.
49
     *
50
     * @param \TechDivision\Import\Product\Media\Services\ProductMediaProcessorInterface $productMediaProcessor The product media processor instance
51
     */
52
    public function __construct(ProductMediaProcessorInterface $productMediaProcessor)
53
    {
54
        $this->productMediaProcessor = $productMediaProcessor;
55
    }
56
57
    /**
58
     * Return's the product media processor instance.
59
     *
60
     * @return \TechDivision\Import\Product\Media\Services\ProductMediaProcessorInterface The product media processor instance
61
     */
62
    protected function getProductMediaProcessor()
63
    {
64
        return $this->productMediaProcessor;
65
    }
66
67
    /**
68
     * Process the observer's business logic.
69
     *
70
     * @return array The processed row
71
     */
72
    protected function process()
73
    {
74
75
        // initialize the array for the actual images
76
        $actualImageNames = array();
77
78
        // iterate over the available image fields
79
        foreach (array_keys($this->getImageTypes()) as $imageColumnName) {
80
            if ($this->hasValue($imageColumnName) && !in_array($imageName = $this->getValue($imageColumnName), $actualImageNames)) {
81
                $actualImageNames[] = $imageName;
82
            }
83
        }
84
85
        // query whether or not, we've additional images
86
        if ($additionalImages = $this->getValue(ColumnKeys::ADDITIONAL_IMAGES, null, array($this, 'explode'))) {
87
            foreach ($additionalImages as $additionalImageName) {
88
                // do nothing if the image has already been added, e. g. it is the base image
89
                if (in_array($additionalImageName, $actualImageNames)) {
90
                    continue;
91
                }
92
93
                // else, add the image to the array
94
                $actualImageNames[] = $additionalImageName;
95
            }
96
        }
97
98
        // load the existing media gallery entities for the produdct with the given SKU
99
        $existingProductMediaGalleries = $this->getProductMediaProcessor()
100
                                              ->getProductMediaGalleriesBySku($sku = $this->getValue(ColumnKeys::SKU));
101
102
        // remove the images that are NOT longer available in the CSV file
103
        foreach ($existingProductMediaGalleries as $existingProductMediaGallery) {
104
            // do nothing if the file still exists
105
            if (in_array($existingImageName = $existingProductMediaGallery[MemberNames::VALUE], $actualImageNames)) {
106
                continue;
107
            }
108
109
            try {
110
                // remove the old image from the database
111
                $this->getProductMediaProcessor()
112
                     ->deleteProductMediaGallery(array(MemberNames::VALUE_ID => $existingProductMediaGallery[MemberNames::VALUE_ID]));
113
114
                // log a debug message that the image has been removed
115
                $this->getSubject()
116
                     ->getSystemLogger()
117
                     ->debug(sprintf('Successfully removed image "%s" from media gallery for product with SKU "%s"', $existingImageName, $sku));
118
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
119
            } catch (\Exception $e) {
120
                // log a warning if debug mode has been enabled and the file is NOT available
121
                if ($this->getSubject()->isDebugMode()) {
122
                    $this->getSubject()
123
                         ->getSystemLogger()
124
                         ->warning($this->getSubject()->appendExceptionSuffix($e->getMessage()));
125
                } else {
126
                    throw $e;
127
                }
128
            }
129
        }
130
131
        // log a message that the images has been cleaned-up
132
        $this->getSubject()
133
             ->getSystemLogger()
134
             ->debug(sprintf('Successfully cleaned-up media gallery for product with SKU "%s"', $sku));
135
    }
136
137
    /**
138
     * Load's the product media gallery entities with the passed SKU.
139
     *
140
     * @param string $sku The SKU to load the media gallery entities for
141
     *
142
     * @return array The product media gallery entities
143
     */
144
    protected function getProductMediaGalleriesBySku($sku)
145
    {
146
        return $this->getProductMediaProcessor()->getProductMediaGalleriesBySku($sku);
147
    }
148
149
    /**
150
     * Return's the array with the available image types and their label columns.
151
     *
152
     * @return array The array with the available image types
153
     */
154
    protected function getImageTypes()
155
    {
156
        return $this->getSubject()->getImageTypes();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Subjects\SubjectInterface as the method getImageTypes() does only exist in the following implementations of said interface: TechDivision\Import\Prod...a\Subjects\MediaSubject, TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
157
    }
158
}
159