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;
16 
21 class Validator implements ValidatorInterface
22 {
26  private $scopeResolverPool;
27 
31  public function __construct(ScopeResolverPool $scopeResolverPool)
32  {
33  $this->scopeResolverPool = $scopeResolverPool;
34  }
35 
39  public function isValid($scope, $scopeCode = null)
40  {
41  if ($scope === ScopeConfigInterface::SCOPE_TYPE_DEFAULT && empty($scopeCode)) {
42  return true;
43  }
44 
45  if ($scope === ScopeConfigInterface::SCOPE_TYPE_DEFAULT && !empty($scopeCode)) {
46  throw new LocalizedException(new Phrase(
47  'The "%1" scope can\'t include a scope code. Try again without entering a scope code.',
49  ));
50  }
51 
52  if (empty($scope)) {
53  throw new LocalizedException(new Phrase('A scope is missing. Enter a scope and try again.'));
54  }
55 
56  $this->validateScopeCode($scopeCode);
57 
58  try {
59  $scopeResolver = $this->scopeResolverPool->get($scope);
60  $scopeResolver->getScope($scopeCode)->getId();
61  } catch (InvalidArgumentException $e) {
62  throw new LocalizedException(
63  new Phrase('The "%1" value doesn\'t exist. Enter another value and try again.', [$scope])
64  );
65  } catch (NoSuchEntityException $e) {
66  throw new LocalizedException(
67  new Phrase('The "%1" value doesn\'t exist. Enter another value and try again.', [$scopeCode])
68  );
69  }
70 
71  return true;
72  }
73 
82  private function validateScopeCode($scopeCode)
83  {
84  if (empty($scopeCode)) {
85  throw new LocalizedException(new Phrase('A scope code is missing. Enter a code and try again.'));
86  }
87 
88  if (!preg_match('/^[a-z]+[a-z0-9_]*$/', $scopeCode)) {
89  throw new LocalizedException(new Phrase(
90  'The scope code can include only lowercase letters (a-z), numbers (0-9) and underscores (_). '
91  . 'Also, the first character must be a letter.'
92  ));
93  }
94  }
95 }
__construct(ScopeResolverPool $scopeResolverPool)
Definition: Validator.php:31