1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Model\ResourceModel;
use Magento\Customer\Model\Customer\NotificationStorage;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Validator\Exception as ValidatorException;
use Magento\Framework\Exception\AlreadyExistsException;
/**
* Customer entity resource model
*
* @api
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @since 100.0.2
*/
class Customer extends \Magento\Eav\Model\Entity\VersionControl\AbstractEntity
{
/**
* @var \Magento\Framework\Validator\Factory
*/
protected $_validatorFactory;
/**
* Core store config
*
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_scopeConfig;
/**
* @var \Magento\Framework\Stdlib\DateTime
*/
protected $dateTime;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @var NotificationStorage
*/
private $notificationStorage;
/**
* @param \Magento\Eav\Model\Entity\Context $context
* @param \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot $entitySnapshot
* @param \Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite $entityRelationComposite
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Framework\Validator\Factory $validatorFactory
* @param \Magento\Framework\Stdlib\DateTime $dateTime
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param array $data
*/
public function __construct(
\Magento\Eav\Model\Entity\Context $context,
\Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot $entitySnapshot,
\Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite $entityRelationComposite,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\Validator\Factory $validatorFactory,
\Magento\Framework\Stdlib\DateTime $dateTime,
\Magento\Store\Model\StoreManagerInterface $storeManager,
$data = []
) {
parent::__construct($context, $entitySnapshot, $entityRelationComposite, $data);
$this->_scopeConfig = $scopeConfig;
$this->_validatorFactory = $validatorFactory;
$this->dateTime = $dateTime;
$this->storeManager = $storeManager;
$this->setType('customer');
$this->setConnection('customer_read', 'customer_write');
}
/**
* Retrieve customer entity default attributes
*
* @return string[]
*/
protected function _getDefaultAttributes()
{
return [
'created_at',
'updated_at',
'increment_id',
'store_id',
'website_id'
];
}
/**
* Check customer scope, email and confirmation key before saving
*
* @param \Magento\Framework\DataObject $customer
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function _beforeSave(\Magento\Framework\DataObject $customer)
{
/** @var \Magento\Customer\Model\Customer $customer */
if ($customer->getStoreId() === null) {
$customer->setStoreId($this->storeManager->getStore()->getId());
}
$customer->getGroupId();
parent::_beforeSave($customer);
if (!$customer->getEmail()) {
throw new ValidatorException(__('The customer email is missing. Enter and try again.'));
}
$connection = $this->getConnection();
$bind = ['email' => $customer->getEmail()];
$select = $connection->select()->from(
$this->getEntityTable(),
[$this->getEntityIdField()]
)->where(
'email = :email'
);
if ($customer->getSharingConfig()->isWebsiteScope()) {
$bind['website_id'] = (int)$customer->getWebsiteId();
$select->where('website_id = :website_id');
}
if ($customer->getId()) {
$bind['entity_id'] = (int)$customer->getId();
$select->where('entity_id != :entity_id');
}
$result = $connection->fetchOne($select, $bind);
if ($result) {
throw new AlreadyExistsException(
__('A customer with the same email address already exists in an associated website.')
);
}
// set confirmation key logic
if ($customer->getForceConfirmed() || $customer->getPasswordHash() == '') {
$customer->setConfirmation(null);
} elseif (!$customer->getId() && $customer->isConfirmationRequired()) {
$customer->setConfirmation($customer->getRandomConfirmationKey());
}
// remove customer confirmation key from database, if empty
if (!$customer->getConfirmation()) {
$customer->setConfirmation(null);
}
if (!$customer->getData('ignore_validation_flag')) {
$this->_validate($customer);
}
return $this;
}
/**
* Validate customer entity
*
* @param \Magento\Customer\Model\Customer $customer
* @return void
* @throws \Magento\Framework\Validator\Exception
*/
protected function _validate($customer)
{
$validator = $this->_validatorFactory->createValidator('customer', 'save');
if (!$validator->isValid($customer)) {
throw new ValidatorException(
null,
null,
$validator->getMessages()
);
}
}
/**
* Retrieve notification storage
*
* @return NotificationStorage
*/
private function getNotificationStorage()
{
if ($this->notificationStorage === null) {
$this->notificationStorage = ObjectManager::getInstance()->get(NotificationStorage::class);
}
return $this->notificationStorage;
}
/**
* Save customer addresses and set default addresses in attributes backend
*
* @param \Magento\Framework\DataObject $customer
* @return $this
*/
protected function _afterSave(\Magento\Framework\DataObject $customer)
{
$this->getNotificationStorage()->add(
NotificationStorage::UPDATE_CUSTOMER_SESSION,
$customer->getId()
);
return parent::_afterSave($customer);
}
/**
* Retrieve select object for loading base entity row
*
* @param \Magento\Framework\DataObject $object
* @param string|int $rowId
* @return \Magento\Framework\DB\Select
*/
protected function _getLoadRowSelect($object, $rowId)
{
$select = parent::_getLoadRowSelect($object, $rowId);
if ($object->getWebsiteId() && $object->getSharingConfig()->isWebsiteScope()) {
$select->where('website_id =?', (int)$object->getWebsiteId());
}
return $select;
}
/**
* Load customer by email
*
* @param \Magento\Customer\Model\Customer $customer
* @param string $email
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function loadByEmail(\Magento\Customer\Model\Customer $customer, $email)
{
$connection = $this->getConnection();
$bind = ['customer_email' => $email];
$select = $connection->select()->from(
$this->getEntityTable(),
[$this->getEntityIdField()]
)->where(
'email = :customer_email'
);
if ($customer->getSharingConfig()->isWebsiteScope()) {
if (!$customer->hasData('website_id')) {
throw new \Magento\Framework\Exception\LocalizedException(
__("A customer website ID wasn't specified. The ID must be specified to use the website scope.")
);
}
$bind['website_id'] = (int)$customer->getWebsiteId();
$select->where('website_id = :website_id');
}
$customerId = $connection->fetchOne($select, $bind);
if ($customerId) {
$this->load($customer, $customerId);
} else {
$customer->setData([]);
}
return $this;
}
/**
* Change customer password
*
* @param \Magento\Customer\Model\Customer $customer
* @param string $newPassword
* @return $this
*/
public function changePassword(\Magento\Customer\Model\Customer $customer, $newPassword)
{
$customer->setPassword($newPassword);
return $this;
}
/**
* Check whether there are email duplicates of customers in global scope
*
* @return bool
*/
public function findEmailDuplicates()
{
$connection = $this->getConnection();
$select = $connection->select()->from(
$this->getTable('customer_entity'),
['email', 'cnt' => 'COUNT(*)']
)->group(
'email'
)->order(
'cnt DESC'
)->limit(
1
);
$lookup = $connection->fetchRow($select);
if (empty($lookup)) {
return false;
}
return $lookup['cnt'] > 1;
}
/**
* Check customer by id
*
* @param int $customerId
* @return bool
*/
public function checkCustomerId($customerId)
{
$connection = $this->getConnection();
$bind = ['entity_id' => (int)$customerId];
$select = $connection->select()->from(
$this->getTable('customer_entity'),
'entity_id'
)->where(
'entity_id = :entity_id'
)->limit(
1
);
$result = $connection->fetchOne($select, $bind);
if ($result) {
return true;
}
return false;
}
/**
* Get customer website id
*
* @param int $customerId
* @return int
*/
public function getWebsiteId($customerId)
{
$connection = $this->getConnection();
$bind = ['entity_id' => (int)$customerId];
$select = $connection->select()->from(
$this->getTable('customer_entity'),
'website_id'
)->where(
'entity_id = :entity_id'
);
return $connection->fetchOne($select, $bind);
}
/**
* Custom setter of increment ID if its needed
*
* @param \Magento\Framework\DataObject $object
* @return $this
*/
public function setNewIncrementId(\Magento\Framework\DataObject $object)
{
if ($this->_scopeConfig->getValue(
\Magento\Customer\Model\Customer::XML_PATH_GENERATE_HUMAN_FRIENDLY_ID,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
)
) {
parent::setNewIncrementId($object);
}
return $this;
}
/**
* Change reset password link token
*
* Stores new reset password link token and its creation time
*
* @param \Magento\Customer\Model\Customer $customer
* @param string $passwordLinkToken
* @return $this
*/
public function changeResetPasswordLinkToken(\Magento\Customer\Model\Customer $customer, $passwordLinkToken)
{
if (is_string($passwordLinkToken) && !empty($passwordLinkToken)) {
$customer->setRpToken($passwordLinkToken);
$customer->setRpTokenCreatedAt(
(new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT)
);
}
return $this;
}
}