Completed
Push — master ( c740cf...e24aa2 )
by Tim
13s
created

CatalogAttributeObserver::getLastAttributeId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * TechDivision\Import\Attribute\Observers\CatalogAttributeObserver
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-attribute
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Attribute\Observers;
22
23
use TechDivision\Import\Attribute\Utils\ColumnKeys;
24
use TechDivision\Import\Attribute\Utils\MemberNames;
25
use TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface;
26
27
/**
28
 * Observer that create's the EAV catalog attribute itself.
29
 *
30
 * @author    Tim Wagner <[email protected]>
31
 * @copyright 2016 TechDivision GmbH <[email protected]>
32
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
33
 * @link      https://github.com/techdivision/import-attribute
34
 * @link      http://www.techdivision.com
35
 */
36
class CatalogAttributeObserver extends AbstractAttributeImportObserver
37
{
38
39
    /**
40
     * The attribute processor instance.
41
     *
42
     * @var \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface
43
     */
44
    protected $attributeBunchProcessor;
45
46
    /**
47
     * The array with the possible column names.
48
     *
49
     * @var array
50
     */
51
    protected $columnNames = array(
52
        ColumnKeys::FRONTEND_INPUT_RENDERER,
53
        ColumnKeys::IS_GLOBAL,
54
        ColumnKeys::IS_VISIBLE,
55
        ColumnKeys::IS_SEARCHABLE,
56
        ColumnKeys::IS_FILTERABLE,
57
        ColumnKeys::IS_COMPARABLE,
58
        ColumnKeys::IS_VISIBLE_ON_FRONT,
59
        ColumnKeys::IS_HTML_ALLOWED_ON_FRONT,
60
        ColumnKeys::IS_USED_FOR_PRICE_RULES,
61
        ColumnKeys::IS_FILTERABLE_IN_SEARCH,
62
        ColumnKeys::USED_IN_PRODUCT_LISTING,
63
        ColumnKeys::USED_FOR_SORT_BY,
64
        ColumnKeys::APPLY_TO,
65
        ColumnKeys::IS_VISIBLE_IN_ADVANCED_SEARCH,
66
        ColumnKeys::POSITION,
67
        ColumnKeys::IS_WYSIWYG_ENABLED,
68
        ColumnKeys::IS_USED_FOR_PROMO_RULES,
69
        ColumnKeys::IS_REQUIRED_IN_ADMIN_STORE,
70
        ColumnKeys::IS_USED_IN_GRID,
71
        ColumnKeys::IS_VISIBLE_IN_GRID,
72
        ColumnKeys::IS_FILTERABLE_IN_GRID,
73
        ColumnKeys::SEARCH_WEIGHT,
74
        ColumnKeys::ADDITIONAL_DATA
75
    );
76
77
    /**
78
     * Initializes the observer with the passed subject instance.
79
     *
80
     * @param \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface $attributeBunchProcessor The attribute bunch processor instance
81
     */
82
    public function __construct(AttributeBunchProcessorInterface $attributeBunchProcessor)
83
    {
84
        $this->attributeBunchProcessor = $attributeBunchProcessor;
85
    }
86
87
    /**
88
     * Process the observer's business logic.
89
     *
90
     * @return void
91
     */
92
    protected function process()
93
    {
94
95
        // query whether or not, we've found a new attribute code => means we've found a new attribute
96
        if ($this->hasBeenProcessed($this->getValue(ColumnKeys::ATTRIBUTE_CODE))) {
97
            return;
98
        }
99
100
        // initialize and persist the EAV catalog attribute
101
        $this->persistCatalogAttribute($this->initializeAttribute($this->prepareAttributes()));
102
    }
103
104
    /**
105
     * Prepare the attributes of the entity that has to be persisted.
106
     *
107
     * @return array The prepared attributes
108
     */
109
    protected function prepareAttributes()
110
    {
111
112
        // load the recently created EAV attribute ID
113
        $attributeId = $this->getLastAttributeId();
114
115
        // initialize the attributes
116
        $attr = array(MemberNames::ATTRIBUTE_ID => $attributeId);
117
118
        // iterate over the possible columns and handle the data
119
        foreach ($this->columnNames as $columnName) {
120
            // query whether or not, the column is available in the CSV file
121
            if ($this->getSubject()->hasHeader($columnName)) {
122
                // custom handling for the additional_data column
123
                if ($columnName === ColumnKeys::ADDITIONAL_DATA) {
124
                    // load the additional data
125
                    $explodedAdditionalData = $this->getValue(ColumnKeys::ADDITIONAL_DATA, array(), array($this->getSubject(), 'explode'));
126
127
                    // query whether or not additional data has been set
128
                    if (sizeof($explodedAdditionalData) > 0) {
129
                        // load and extract the additional data
130
                        $additionalData = array();
131
                        foreach ($explodedAdditionalData as $value) {
132
                            list ($key, $val) = $this->getSubject()->explode($value, '=');
133
                            $additionalData[$key] = $val;
134
                        }
135
136
                        // set the additional data
137
                        $attr[$columnName] = $additionalData;
138
                    }
139
140
                } else {
141
                    // query whether or not a column contains a value
142
                    if ($this->hasValue($columnName)) {
143
                        $attr[$columnName] = $this->getValue($columnName);
144
                    }
145
                }
146
            }
147
        }
148
149
        // return the prepared product
150
        return $this->initializeEntity($attr);
151
    }
152
153
    /**
154
     * Serialize the additional_data attribute of the passed array.
155
     *
156
     * @param array $attr The attribute with the data to serialize
157
     *
158
     * @return array The attribute with the serialized additional_data
159
     */
160
    protected function serializeAdditionalData(array $attr)
161
    {
162
163
        // serialize the additional data value if available
164
        if (isset($attr[MemberNames::ADDITIONAL_DATA]) && is_array($attr[MemberNames::ADDITIONAL_DATA])) {
165
            $attr[MemberNames::ADDITIONAL_DATA] = serialize($attr[MemberNames::ADDITIONAL_DATA]);
166
        }
167
168
        // return the attribute
169
        return $attr;
170
    }
171
172
    /**
173
     * Initialize the attribute with the passed attributes and returns an instance.
174
     *
175
     * @param array $attr The attribute attributes
176
     *
177
     * @return array The initialized attribute
178
     */
179
    protected function initializeAttribute(array $attr)
180
    {
181
        return $this->serializeAdditionalData($attr);
182
    }
183
184
    /**
185
     * Return's the attribute bunch processor instance.
186
     *
187
     * @return \TechDivision\Import\Attribute\Services\AttributeBunchProcessorInterface The attribute bunch processor instance
188
     */
189
    protected function getAttributeBunchProcessor()
190
    {
191
        return $this->attributeBunchProcessor;
192
    }
193
194
    /**
195
     * Map's the passed attribute code to the attribute ID that has been created recently.
196
     *
197
     * @param string $attributeCode The attribute code that has to be mapped
198
     *
199
     * @return void
200
     */
201
    protected function addAttributeCodeIdMapping($attributeCode)
202
    {
203
        $this->getSubject()->addAttributeCodeIdMapping($attributeCode);
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 addAttributeCodeIdMapping() does only exist in the following implementations of said interface: TechDivision\Import\Attr...e\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...
204
    }
205
206
    /**
207
     * Queries whether or not the attribute with the passed code has already been processed.
208
     *
209
     * @param string $attributeCode The attribute code to check
210
     *
211
     * @return boolean TRUE if the path has been processed, else FALSE
212
     */
213
    protected function hasBeenProcessed($attributeCode)
214
    {
215
        return $this->getSubject()->hasBeenProcessed($attributeCode);
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 hasBeenProcessed() does only exist in the following implementations of said interface: TechDivision\Import\Attr...rs\AttributeSubjectImpl, TechDivision\Import\Attr...e\Subjects\BunchSubject, TechDivision\Import\Attr...\Subjects\OptionSubject.

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...
216
    }
217
218
    /**
219
     * Return's the ID of the attribute that has been created recently.
220
     *
221
     * @return integer The attribute ID
222
     */
223
    protected function getLastAttributeId()
224
    {
225
        return $this->getSubject()->getLastAttributeId();
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 getLastAttributeId() does only exist in the following implementations of said interface: TechDivision\Import\Attr...rs\AttributeSubjectImpl, TechDivision\Import\Attr...e\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...
226
    }
227
228
    /**
229
     * Persist the passed EAV catalog attribute.
230
     *
231
     * @param array $catalogAttribute The EAV catalog attribute to persist
232
     *
233
     * @return void
234
     */
235
    protected function persistCatalogAttribute(array $catalogAttribute)
236
    {
237
        return $this->getAttributeBunchProcessor()->persistCatalogAttribute($catalogAttribute);
238
    }
239
}
240