-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathSkuValidator.php
More file actions
98 lines (87 loc) · 2.82 KB
/
SkuValidator.php
File metadata and controls
98 lines (87 loc) · 2.82 KB
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
<?php
/**
* Copyright 2026 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);
namespace Magento\Inventory\Model\SourceItem\Validator;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Validation\ValidationResult;
use Magento\Framework\Validation\ValidationResultFactory;
use Magento\Inventory\Model\Validators\NoSpaceBeforeAndAfterString;
use Magento\Inventory\Model\Validators\NotAnEmptyString;
use Magento\InventoryApi\Api\Data\SourceItemInterface;
use Magento\InventoryApi\Model\SourceItemValidatorInterface;
/**
* Check that sku is valid
*/
class SkuValidator implements SourceItemValidatorInterface
{
/**
* @var ValidationResultFactory
*/
private $validationResultFactory;
/**
* @var NotAnEmptyString
*/
private $notAnEmptyString;
/**
* @var NoSpaceBeforeAndAfterString
*/
private $noSpaceBeforeAndAfterString;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @param ValidationResultFactory $validationResultFactory
* @param NotAnEmptyString $notAnEmptyString
* @param NoSpaceBeforeAndAfterString $noSpaceBeforeAndAfterString
* @param ProductRepositoryInterface $productRepository
*/
public function __construct(
ValidationResultFactory $validationResultFactory,
NotAnEmptyString $notAnEmptyString,
NoSpaceBeforeAndAfterString $noSpaceBeforeAndAfterString,
ProductRepositoryInterface $productRepository
) {
$this->validationResultFactory = $validationResultFactory;
$this->notAnEmptyString = $notAnEmptyString;
$this->noSpaceBeforeAndAfterString = $noSpaceBeforeAndAfterString;
$this->productRepository = $productRepository;
}
/**
* @inheritdoc
*/
public function validate(SourceItemInterface $source): ValidationResult
{
$value = $source->getSku();
$errors = [
$this->notAnEmptyString->execute(SourceItemInterface::SKU, (string)$value),
$this->noSpaceBeforeAndAfterString->execute(SourceItemInterface::SKU, (string)$value),
$this->validateSkuExists((string)$value)
];
$errors = array_merge(...$errors);
return $this->validationResultFactory->create(['errors' => $errors]);
}
/**
* Validate that product with given SKU exists
*
* @param string $sku
* @return array
*/
private function validateSkuExists(string $sku): array
{
$errors = [];
if (empty($sku)) {
return $errors;
}
try {
$this->productRepository->get($sku);
} catch (NoSuchEntityException $e) {
$errors[] = __('Product with SKU "%1" does not exist.', $sku);
}
return $errors;
}
}