Skip to content

Commit d05b3bf

Browse files
author
Sergey Semenov
committed
Merge remote-tracking branch 'origin/MAGETWO-49820-Customer-validation' into BUGS
2 parents b85e8ea + 2aa6e5a commit d05b3bf

File tree

13 files changed

+49
-253
lines changed

13 files changed

+49
-253
lines changed

app/code/Magento/Customer/Model/AccountManagement.php

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,11 @@
1717
use Magento\Customer\Model\Config\Share as ConfigShare;
1818
use Magento\Customer\Model\Customer as CustomerModel;
1919
use Magento\Customer\Model\Metadata\Validator;
20+
use Magento\Eav\Model\Validator\Attribute\Backend;
2021
use Magento\Framework\Api\ExtensibleDataObjectConverter;
2122
use Magento\Framework\App\Area;
2223
use Magento\Framework\App\Config\ScopeConfigInterface;
24+
use Magento\Framework\App\ObjectManager;
2325
use Magento\Framework\Encryption\EncryptorInterface as Encryptor;
2426
use Magento\Framework\Encryption\Helper\Security;
2527
use Magento\Framework\Event\ManagerInterface;
@@ -280,6 +282,11 @@ class AccountManagement implements AccountManagementInterface
280282
*/
281283
private $emailNotification;
282284

285+
/**
286+
* @var \Magento\Eav\Model\Validator\Attribute\Backend
287+
*/
288+
private $eavValidator;
289+
283290
/**
284291
* @param CustomerFactory $customerFactory
285292
* @param ManagerInterface $eventManager
@@ -831,31 +838,39 @@ protected function createPasswordHash($password)
831838
return $this->encryptor->getHash($password, true);
832839
}
833840

841+
/**
842+
* @return Backend
843+
*/
844+
private function getEavValidator()
845+
{
846+
if ($this->eavValidator === null) {
847+
$this->eavValidator = ObjectManager::getInstance()->get(Backend::class);
848+
}
849+
return $this->eavValidator;
850+
}
851+
834852
/**
835853
* {@inheritdoc}
836854
*/
837855
public function validate(CustomerInterface $customer)
838856
{
839-
$customerData = $this->extensibleDataObjectConverter
840-
->toFlatArray($customer, [], '\Magento\Customer\Api\Data\CustomerInterface');
841-
$customerErrors = $this->validator->validateData($customerData, [], 'customer');
842-
843857
$validationResults = $this->validationResultsDataFactory->create();
844-
if ($customerErrors !== true) {
845-
return $validationResults->setIsValid(false)
846-
->setMessages($this->validator->getMessages());
847-
}
848858

849859
$oldAddresses = $customer->getAddresses();
850860
$customerModel = $this->customerFactory->create()->updateData(
851861
$customer->setAddresses([])
852862
);
853863
$customer->setAddresses($oldAddresses);
854864

855-
$result = $customerModel->validate();
856-
if (true !== $result && is_array($result)) {
865+
$result = $this->getEavValidator()->isValid($customerModel);
866+
if ($result === false && is_array($this->getEavValidator()->getMessages())) {
857867
return $validationResults->setIsValid(false)
858-
->setMessages($result);
868+
->setMessages(
869+
call_user_func_array(
870+
'array_merge',
871+
$this->getEavValidator()->getMessages()
872+
)
873+
);
859874
}
860875
return $validationResults->setIsValid(true)
861876
->setMessages([]);

app/code/Magento/Customer/Model/Customer.php

Lines changed: 3 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -966,52 +966,13 @@ public function setStore(\Magento\Store\Model\Store $store)
966966

967967
/**
968968
* Validate customer attribute values.
969-
* For existing customer password + confirmation will be validated only when password is set
970-
* (i.e. its change is requested)
971969
*
972-
* @return bool|string[]
973-
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
974-
* @SuppressWarnings(PHPMD.NPathComplexity)
970+
* @deprecated
971+
* @return bool
975972
*/
976973
public function validate()
977974
{
978-
$errors = [];
979-
if (!\Zend_Validate::is(trim($this->getFirstname()), 'NotEmpty')) {
980-
$errors[] = __('Please enter a first name.');
981-
}
982-
983-
if (!\Zend_Validate::is(trim($this->getLastname()), 'NotEmpty')) {
984-
$errors[] = __('Please enter a last name.');
985-
}
986-
987-
if (!\Zend_Validate::is($this->getEmail(), 'EmailAddress')) {
988-
$errors[] = __('Please correct this email address: "%1".', $this->getEmail());
989-
}
990-
991-
$entityType = $this->_config->getEntityType('customer');
992-
$attribute = $this->_config->getAttribute($entityType, 'dob');
993-
if ($attribute->getIsRequired() && '' == trim($this->getDob())) {
994-
$errors[] = __('Please enter a date of birth.');
995-
}
996-
$attribute = $this->_config->getAttribute($entityType, 'taxvat');
997-
if ($attribute->getIsRequired() && '' == trim($this->getTaxvat())) {
998-
$errors[] = __('Please enter a TAX/VAT number.');
999-
}
1000-
$attribute = $this->_config->getAttribute($entityType, 'gender');
1001-
if ($attribute->getIsRequired() && '' == trim($this->getGender())) {
1002-
$errors[] = __('Please enter a gender.');
1003-
}
1004-
1005-
$transport = new \Magento\Framework\DataObject(
1006-
['errors' => $errors]
1007-
);
1008-
$this->_eventManager->dispatch('customer_validate', ['customer' => $this, 'transport' => $transport]);
1009-
$errors = $transport->getErrors();
1010-
1011-
if (empty($errors)) {
1012-
return true;
1013-
}
1014-
return $errors;
975+
return true;
1015976
}
1016977

1017978
/**

app/code/Magento/Customer/Model/ResourceModel/CustomerRepository.php

Lines changed: 0 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,10 @@
77
namespace Magento\Customer\Model\ResourceModel;
88

99
use Magento\Customer\Api\CustomerMetadataInterface;
10-
use Magento\Customer\Model\Data\CustomerSecure;
1110
use Magento\Framework\Api\DataObjectHelper;
1211
use Magento\Framework\Api\ImageProcessorInterface;
1312
use Magento\Framework\Api\SearchCriteriaInterface;
1413
use Magento\Framework\Api\SortOrder;
15-
use Magento\Framework\Exception\InputException;
16-
use Magento\Framework\Exception\NoSuchEntityException;
1714

1815
/**
1916
* Customer repository.
@@ -139,8 +136,6 @@ public function __construct(
139136
*/
140137
public function save(\Magento\Customer\Api\Data\CustomerInterface $customer, $passwordHash = null)
141138
{
142-
$this->validate($customer);
143-
144139
$prevCustomerData = null;
145140
if ($customer->getId()) {
146141
$prevCustomerData = $this->getById($customer->getId());
@@ -320,75 +315,6 @@ public function deleteById($customerId)
320315
return true;
321316
}
322317

323-
/**
324-
* Validate customer attribute values.
325-
*
326-
* @param \Magento\Customer\Api\Data\CustomerInterface $customer
327-
* @throws InputException
328-
* @return void
329-
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
330-
* @SuppressWarnings(PHPMD.NPathComplexity)
331-
*/
332-
private function validate(\Magento\Customer\Api\Data\CustomerInterface $customer)
333-
{
334-
$exception = new InputException();
335-
if (!\Zend_Validate::is(trim($customer->getFirstname()), 'NotEmpty')) {
336-
$exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'firstname']));
337-
}
338-
339-
if (!\Zend_Validate::is(trim($customer->getLastname()), 'NotEmpty')) {
340-
$exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'lastname']));
341-
}
342-
343-
$isEmailAddress = \Zend_Validate::is(
344-
$customer->getEmail(),
345-
'EmailAddress'
346-
);
347-
348-
if (!$isEmailAddress) {
349-
$exception->addError(
350-
__(
351-
InputException::INVALID_FIELD_VALUE,
352-
['fieldName' => 'email', 'value' => $customer->getEmail()]
353-
)
354-
);
355-
}
356-
357-
$dob = $this->getAttributeMetadata('dob');
358-
if ($dob !== null && $dob->isRequired() && '' == trim($customer->getDob())) {
359-
$exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'dob']));
360-
}
361-
362-
$taxvat = $this->getAttributeMetadata('taxvat');
363-
if ($taxvat !== null && $taxvat->isRequired() && '' == trim($customer->getTaxvat())) {
364-
$exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'taxvat']));
365-
}
366-
367-
$gender = $this->getAttributeMetadata('gender');
368-
if ($gender !== null && $gender->isRequired() && '' == trim($customer->getGender())) {
369-
$exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'gender']));
370-
}
371-
372-
if ($exception->wasErrorAdded()) {
373-
throw $exception;
374-
}
375-
}
376-
377-
/**
378-
* Get attribute metadata.
379-
*
380-
* @param string $attributeCode
381-
* @return \Magento\Customer\Api\Data\AttributeMetadataInterface|null
382-
*/
383-
private function getAttributeMetadata($attributeCode)
384-
{
385-
try {
386-
return $this->customerMetadata->getAttributeMetadata($attributeCode);
387-
} catch (NoSuchEntityException $e) {
388-
return null;
389-
}
390-
}
391-
392318
/**
393319
* Helper function that adds a FilterGroup to the collection.
394320
*

app/code/Magento/Customer/Test/Unit/Model/CustomerTest.php

Lines changed: 0 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -138,49 +138,6 @@ public function testHashPassword()
138138
$this->assertEquals('hash', $this->_model->hashPassword('password', 'salt'));
139139
}
140140

141-
/**
142-
* @param $data
143-
* @param $expected
144-
*
145-
* @dataProvider validateDataProvider
146-
*/
147-
public function testValidate($data, $expected)
148-
{
149-
$this->_config->expects($this->exactly(3))
150-
->method('getAttribute')
151-
->will($this->returnValue($this->attributeCustomerMock));
152-
$this->attributeCustomerMock->expects($this->exactly(3))
153-
->method('getIsRequired')
154-
->will($this->returnValue(true));
155-
$this->_model->setData($data);
156-
$this->assertEquals($expected, $this->_model->validate());
157-
}
158-
159-
public function validateDataProvider()
160-
{
161-
$data = [
162-
'firstname' => 'First Name',
163-
'lastname' => 'Last Name',
164-
'email' => 'email@example.com',
165-
'dob' => '01.01.1970',
166-
'taxvat' => '10',
167-
'gender' => 'm',
168-
];
169-
return [
170-
[array_diff_key($data, ['firstname' => '']), ['Please enter a first name.']],
171-
[array_diff_key($data, ['lastname' => '']), ['Please enter a last name.']],
172-
[array_diff_key($data, ['email' => '']), ['Please correct this email address: "".']],
173-
[
174-
array_merge($data, ['email' => 'wrong@email']),
175-
['Please correct this email address: "wrong@email".']
176-
],
177-
[array_diff_key($data, ['dob' => '']), ['Please enter a date of birth.']],
178-
[array_diff_key($data, ['taxvat' => '']), ['Please enter a TAX/VAT number.']],
179-
[array_diff_key($data, ['gender' => '']), ['Please enter a gender.']],
180-
[$data, true],
181-
];
182-
}
183-
184141
/**
185142
* @expectedException \Magento\Framework\Exception\LocalizedException
186143
* @expectedExceptionMessage Please correct the transactional account email type.

app/code/Magento/Customer/Test/Unit/Model/ResourceModel/CustomerRepositoryTest.php

Lines changed: 2 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -179,52 +179,13 @@ protected function setUp()
179179
);
180180
}
181181

182-
/**
183-
* @SuppressWarnings(PHPMD.NPathComplexity)
184-
*/
185-
protected function prepareMocksForValidation($isValid = false)
186-
{
187-
$attributeMetaData = $this->getMockForAbstractClass(
188-
'Magento\Customer\Api\Data\AttributeMetadataInterface',
189-
[],
190-
'',
191-
false
192-
);
193-
$attributeMetaData->expects($this->atLeastOnce())
194-
->method('isRequired')
195-
->willReturn(true);
196-
$this->customerMetadata->expects($this->atLeastOnce())
197-
->method('getAttributeMetadata')
198-
->willReturn($attributeMetaData);
199-
200-
$this->customer->expects($this->once())
201-
->method('getFirstname')
202-
->willReturn($isValid ? 'Firstname' : false);
203-
$this->customer->expects($this->once())
204-
->method('getLastname')
205-
->willReturn($isValid ? 'Lastname' : false);
206-
$this->customer->expects($this->atLeastOnce())
207-
->method('getEmail')
208-
->willReturn($isValid ? 'example@example.com' : false);
209-
$this->customer->expects($this->once())
210-
->method('getDob')
211-
->willReturn($isValid ? '12/12/2015' : false);
212-
$this->customer->expects($this->atLeastOnce())
213-
->method('getTaxvat')
214-
->willReturn($isValid ? 'taxvat' : false);
215-
$this->customer->expects($this->once())
216-
->method('getGender')
217-
->willReturn($isValid ? 'gender' : false);
218-
}
219-
220182
/**
221183
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
222184
*/
223185
public function testSave()
224186
{
225187
$customerId = 1;
226188
$storeId = 2;
227-
$this->prepareMocksForValidation(true);
228189

229190
$region = $this->getMockForAbstractClass('Magento\Customer\Api\Data\RegionInterface', [], '', false);
230191
$address = $this->getMockForAbstractClass(
@@ -399,13 +360,13 @@ public function testSave()
399360
->method('getLockExpires')
400361
->willReturn('lockExpires');
401362

402-
$customerModel->expects($this->exactly(2))
363+
$customerModel->expects($this->once())
403364
->method('setRpToken')
404365
->willReturnMap([
405366
['rpToken', $customerModel],
406367
[null, $customerModel],
407368
]);
408-
$customerModel->expects($this->exactly(2))
369+
$customerModel->expects($this->once())
409370
->method('setRpTokenCreatedAt')
410371
->willReturnMap([
411372
['rpTokenCreatedAt', $customerModel],
@@ -466,7 +427,6 @@ public function testSaveWithPasswordHash()
466427
$customerId = 1;
467428
$storeId = 2;
468429
$passwordHash = 'ukfa4sdfa56s5df02asdf4rt';
469-
$this->prepareMocksForValidation(true);
470430

471431
$region = $this->getMockForAbstractClass('Magento\Customer\Api\Data\RegionInterface', [], '', false);
472432
$address = $this->getMockForAbstractClass(
@@ -635,15 +595,6 @@ public function testSaveWithPasswordHash()
635595
$this->model->save($this->customer, $passwordHash);
636596
}
637597

638-
/**
639-
* @expectedException \Magento\Framework\Exception\InputException
640-
*/
641-
public function testSaveWithException()
642-
{
643-
$this->prepareMocksForValidation(false);
644-
$this->model->save($this->customer);
645-
}
646-
647598
/**
648599
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
649600
*/

app/code/Magento/Eav/Model/Attribute/Data/AbstractData.php

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -364,9 +364,7 @@ protected function _validateInputRule($value)
364364
__("'%value%' appears to be a DNS hostname but cannot extract TLD part")
365365
__("'%value%' appears to be a DNS hostname but cannot match TLD against known list")
366366
*/
367-
$validator = new \Zend_Validate_EmailAddress(
368-
['allow' => ['allow' => \Zend_Validate_Hostname::ALLOW_ALL, 'tld' => false]]
369-
);
367+
$validator = new \Zend_Validate_EmailAddress();
370368
$validator->setMessage(
371369
__('"%1" invalid type entered.', $label),
372370
\Zend_Validate_EmailAddress::INVALID

app/code/Magento/Eav/Model/Entity/Attribute/AbstractAttribute.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,7 @@ protected function _getDefaultSourceModel()
594594
public function isValueEmpty($value)
595595
{
596596
/** @var array $emptyStringTypes list of attribute types that treat empty string as a possible value */
597-
$emptyStringTypes = ['int', 'decimal', 'datetime', 'varchar', 'text'];
597+
$emptyStringTypes = ['int', 'decimal', 'datetime', 'varchar', 'text', 'static'];
598598
$attributeType = $this->getBackend()->getType();
599599
return (is_array($value) && count($value) == 0)
600600
|| $value === null

0 commit comments

Comments
 (0)