Passed
Push — 15.x ( f9b626 )
by Tim
04:47
created

CustomerObserver::loadRawEntity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * TechDivision\Import\Customer\Observers\CustomerObserver
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 2018 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-customer
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Customer\Observers;
22
23
use TechDivision\Import\Utils\EntityTypeCodes;
24
use TechDivision\Import\Observers\StateDetectorInterface;
25
use TechDivision\Import\Customer\Utils\GenderKeys;
26
use TechDivision\Import\Customer\Utils\ColumnKeys;
27
use TechDivision\Import\Customer\Utils\MemberNames;
28
use TechDivision\Import\Customer\Services\CustomerBunchProcessorInterface;
29
30
/**
31
 * Observer that create's the customer itself.
32
 *
33
 * @author    Tim Wagner <[email protected]>
34
 * @copyright 2018 TechDivision GmbH <[email protected]>
35
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
36
 * @link      https://github.com/techdivision/import-customer
37
 * @link      http://www.techdivision.com
38
 */
39
class CustomerObserver extends AbstractCustomerImportObserver
40
{
41
42
    /**
43
     * The customer bunch processor instance.
44
     *
45
     * @var \TechDivision\Import\Customer\Services\CustomerBunchProcessorInterface
46
     */
47
    protected $customerBunchProcessor;
48
49
    /**
50
     * The array with the available gender keys.
51
     *
52
     * @var array
53
     */
54
    protected $availableGenders = array(
55
        'Male'          => GenderKeys::GENDER_MALE,
56
        'Female'        => GenderKeys::GENDER_FEMALE,
57
        'Not Specified' => GenderKeys::GENDER_NOT_SPECIFIED
58
    );
59
60
    /**
61
     * Initializes the observer with the state detector instance.
62
     *
63
     * @param \TechDivision\Import\Customer\Services\CustomerBunchProcessorInterface $customerBunchProcessor The customer bunch processor instance
64
     * @param \TechDivision\Import\Observers\StateDetectorInterface                  $stateDetector          The state detector instance
65
     */
66
    public function __construct(
67
        CustomerBunchProcessorInterface $customerBunchProcessor,
68
        StateDetectorInterface $stateDetector = null
69
    ) {
70
71
        // set the customer processor and the raw entity loader
72
        $this->customerBunchProcessor = $customerBunchProcessor;
73
74
        // pass the state detector to the parent constructor
75
        parent::__construct($stateDetector);
76
    }
77
78
    /**
79
     * Return's the customer bunch processor instance.
80
     *
81
     * @return \TechDivision\Import\Customer\Services\CustomerBunchProcessorInterface The customer bunch processor instance
82
     */
83
    protected function getCustomerBunchProcessor()
84
    {
85
        return $this->customerBunchProcessor;
86
    }
87
88
    /**
89
     * Process the observer's business logic.
90
     *
91
     * @return void
92
     */
93
    protected function process()
94
    {
95
96
        // load email and website code
97
        $email = $this->getValue(ColumnKeys::EMAIL);
98
        $website = $this->getValue(ColumnKeys::WEBSITE);
99
100
        // query whether or not, we've found a new SKU => means we've found a new customer
101
        if ($this->hasBeenProcessed(array($email, $website))) {
102
            return;
103
        }
104
105
        // prepare the static entity values
106
        $customer = $this->initializeCustomer($this->prepareAttributes());
107
108
        // insert the entity and set the entity ID
109
        $this->setLastEntityId($this->persistCustomer($customer));
110
    }
111
112
    /**
113
     * Prepare the attributes of the entity that has to be persisted.
114
     *
115
     * @return array The prepared attributes
116
     */
117
    protected function prepareAttributes()
118
    {
119
120
        // initialize the customer values
121
        $email = $this->getValue(ColumnKeys::EMAIL);
122
        $groupId = $this->getValue(ColumnKeys::GROUP_ID);
123
        $storeId = $this->getValue(ColumnKeys::STORE_ID);
124
        $disableAutoGroupChange = $this->getValue(ColumnKeys::DISABLE_AUTO_GROUP_CHANGE);
125
        $prefix = $this->getValue(ColumnKeys::PREFIX);
126
        $firstname = $this->getValue(ColumnKeys::FIRSTNAME);
127
        $middlename = $this->getValue(ColumnKeys::MIDDLENAME);
128
        $lastname = $this->getValue(ColumnKeys::LASTNAME);
129
        $suffix = $this->getValue(ColumnKeys::SUFFIX);
130
        $passwordHash = $this->getValue(ColumnKeys::PASSWORD_HASH);
131
        $rpToken = $this->getValue(ColumnKeys::RP_TOKEN);
132
        $defaultShipping = $this->getValue(ColumnKeys::ADDRESS_DEFAULT_SHIPPING);
133
        $defaultBilling = $this->getValue(ColumnKeys::ADDRESS_DEFAULT_BILLING);
134
        $taxvat = $this->getValue(ColumnKeys::TAXVAT);
135
        $confirmation = $this->getValue(ColumnKeys::CONFIRMATION);
136
        $gender = $this->getGenderByValue($this->getValue(ColumnKeys::GENDER));
137
138
        // load the customer's addtional attributes
139
        $createdIn = $this->getValue(ColumnKeys::CREATED_IN);
140
        $incrementId = null;
141
        $isActive = 1;
142
        $failuresNum = 0;
143
        $firstFailure = null;
144
        $lockExpires = null;
145
146
        // prepare the date format for the created at/updated at dates
147
        $websiteId = $this->getStoreWebsiteIdByCode($this->getValue(ColumnKeys::WEBSITE));
148
        $dob = $this->getValue(ColumnKeys::DOB, date('Y-m-d H:i:s'), array($this, 'formatDate'));
149
        $createdAt = $this->getValue(ColumnKeys::CREATED_AT, date('Y-m-d H:i:s'), array($this, 'formatDate'));
150
        $updatedAt = $this->getValue(ColumnKeys::UPDATED_AT, date('Y-m-d H:i:s'), array($this, 'formatDate'));
151
        $rpTokenCreatedAt = $this->getValue(ColumnKeys::RP_TOKEN_CREATED_AT, date('Y-m-d H:i:s'), array($this, 'formatDate'));
152
153
        // return the prepared customer
154
        return $this->initializeEntity(
155
            $this->loadRawEntity(
156
                array(
157
                    MemberNames::WEBSITE_ID                => $websiteId,
158
                    MemberNames::EMAIL                     => $email,
159
                    MemberNames::GROUP_ID                  => $groupId,
160
                    MemberNames::INCREMENT_ID              => $incrementId,
161
                    MemberNames::STORE_ID                  => $storeId,
162
                    MemberNames::CREATED_AT                => $createdAt,
163
                    MemberNames::UPDATED_AT                => $updatedAt,
164
                    MemberNames::IS_ACTIVE                 => $isActive,
165
                    MemberNames::DISABLE_AUTO_GROUP_CHANGE => $disableAutoGroupChange,
166
                    MemberNames::CREATED_IN                => $createdIn,
167
                    MemberNames::PREFIX                    => $prefix,
168
                    MemberNames::FIRSTNAME                 => $firstname,
169
                    MemberNames::MIDDLENAME                => $middlename,
170
                    MemberNames::LASTNAME                  => $lastname,
171
                    MemberNames::SUFFIX                    => $suffix,
172
                    MemberNames::DOB                       => $dob,
173
                    MemberNames::PASSWORD_HASH             => $passwordHash,
174
                    MemberNames::RP_TOKEN                  => $rpToken,
175
                    MemberNames::RP_TOKEN_CREATED_AT       => $rpTokenCreatedAt,
176
                    MemberNames::DEFAULT_BILLING           => $defaultBilling,
177
                    MemberNames::DEFAULT_SHIPPING          => $defaultShipping,
178
                    MemberNames::TAXVAT                    => $taxvat,
179
                    MemberNames::CONFIRMATION              => $confirmation,
180
                    MemberNames::GENDER                    => $gender,
181
                    MemberNames::FAILURES_NUM              => $failuresNum,
182
                    MemberNames::FIRST_FAILURE             => $firstFailure,
183
                    MemberNames::LOCK_EXPIRES              => $lockExpires
184
                )
185
            )
186
        );
187
    }
188
189
    /**
190
     * Load's and return's a raw customer entity without primary key but the mandatory members only and nulled values.
191
     *
192
     * @param array $data An array with data that will be used to initialize the raw entity with
193
     *
194
     * @return array The initialized entity
195
     */
196
    protected function loadRawEntity(array $data = array())
197
    {
198
        return $this->getCustomerBunchProcessor()->loadRawEntity(EntityTypeCodes::CUSTOMER, $data);
199
    }
200
201
    /**
202
     * Initialize the customer with the passed attributes and returns an instance.
203
     *
204
     * @param array $attr The customer attributes
205
     *
206
     * @return array The initialized customer
207
     */
208
    protected function initializeCustomer(array $attr)
209
    {
210
211
        // load the customer with the passed SKU and merge it with the attributes
212
        if ($entity = $this->loadCustomerByEmailAndWebsiteId($attr[MemberNames::EMAIL], $attr[MemberNames::WEBSITE_ID])) {
213
            return $this->mergeEntity($entity, $attr);
214
        }
215
216
        // otherwise simply return the attributes
217
        return $attr;
218
    }
219
220
    /**
221
     * Return's the gender ID for the passed value.
222
     *
223
     * @param string $value The value to return the gender ID for
224
     *
225
     * @return integer The gender ID
226
     * @throws \Exception Is thrown, if the gender ID with the requested value is not available
227
     */
228
    protected function getGenderByValue($value)
229
    {
230
231
        // query whether or not, the requested gender ID is available
232
        if (isset($this->availableGenders[$value])) {
233
            return (integer) $this->availableGenders[$value];
234
        }
235
236
        // throw an exception, if not
237
        throw new \Exception(
238
            $this->appendExceptionSuffix(
239
                sprintf('Found invalid gender %s', $value)
240
            )
241
        );
242
    }
243
244
    /**
245
     * Return's the store website for the passed code.
246
     *
247
     * @param string $code The code of the store website to return the ID for
248
     *
249
     * @return integer The store website ID
250
     */
251
    protected function getStoreWebsiteIdByCode($code)
252
    {
253
        return $this->getSubject()->getStoreWebsiteIdByCode($code);
254
    }
255
256
    /**
257
     * Return's the customer with the passed email and website ID.
258
     *
259
     * @param string $email     The email of the customer to return
260
     * @param string $websiteId The website ID of the customer to return
261
     *
262
     * @return array|null The customer
263
     */
264
    protected function loadCustomerByEmailAndWebsiteId($email, $websiteId)
265
    {
266
        return $this->getCustomerBunchProcessor()->loadCustomerByEmailAndWebsiteId($email, $websiteId);
267
    }
268
269
    /**
270
     * Persist's the passed customer data and return's the ID.
271
     *
272
     * @param array $customer The customer data to persist
273
     *
274
     * @return string The ID of the persisted entity
275
     */
276
    protected function persistCustomer($customer)
277
    {
278
        return $this->getCustomerBunchProcessor()->persistCustomer($customer);
279
    }
280
281
    /**
282
     * Return's the attribute set of the product that has to be created.
283
     *
284
     * @return array The attribute set
285
     */
286
    protected function getAttributeSet()
287
    {
288
        return $this->getSubject()->getAttributeSet();
289
    }
290
291
    /**
292
     * Set's the ID of the customer that has been created recently.
293
     *
294
     * @param string $lastEntityId The entity ID
295
     *
296
     * @return void
297
     */
298
    protected function setLastEntityId($lastEntityId)
299
    {
300
        $this->getSubject()->setLastEntityId($lastEntityId);
301
    }
302
}
303