Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Validator.php
Go to the documentation of this file.
1 <?php
8 
9 use InvalidArgumentException;
15 
19 class Validator implements ValidatorInterface
20 {
24  private $scopeResolverPool;
25 
29  public function __construct(ScopeResolverPool $scopeResolverPool)
30  {
31  $this->scopeResolverPool = $scopeResolverPool;
32  }
33 
37  public function isValid($scope, $scopeCode = null)
38  {
39  if ($scope === ScopeConfigInterface::SCOPE_TYPE_DEFAULT && empty($scopeCode)) {
40  return true;
41  }
42 
43  if ($scope === ScopeConfigInterface::SCOPE_TYPE_DEFAULT && !empty($scopeCode)) {
44  throw new LocalizedException(new Phrase(
45  'The "%1" scope can\'t include a scope code. Try again without entering a scope code.',
47  ));
48  }
49 
50  if (empty($scope)) {
51  throw new LocalizedException(new Phrase('A scope is missing. Enter a scope and try again.'));
52  }
53 
54  $this->validateScopeCode($scopeCode);
55 
56  try {
57  $scopeResolver = $this->scopeResolverPool->get($scope);
58  $scopeResolver->getScope($scopeCode)->getId();
59  } catch (InvalidArgumentException $e) {
60  throw new LocalizedException(
61  new Phrase('The "%1" value doesn\'t exist. Enter another value and try again.', [$scope])
62  );
63  } catch (NoSuchEntityException $e) {
64  throw new LocalizedException(
65  new Phrase('The "%1" value doesn\'t exist. Enter another value and try again.', [$scopeCode])
66  );
67  }
68 
69  return true;
70  }
71 
80  private function validateScopeCode($scopeCode)
81  {
82  if (empty($scopeCode)) {
83  throw new LocalizedException(new Phrase('A scope code is missing. Enter a code and try again.'));
84  }
85 
86  if (!preg_match('/^[a-z]+[a-z0-9_]*$/', $scopeCode)) {
87  throw new LocalizedException(new Phrase(
88  'The scope code can include only lowercase letters (a-z), numbers (0-9) and underscores (_). '
89  . 'Also, the first character must be a letter.'
90  ));
91  }
92  }
93 }
__construct(ScopeResolverPool $scopeResolverPool)
Definition: Validator.php:29
isValid($scope, $scopeCode=null)
Definition: Validator.php:37