Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SortOrder.php
Go to the documentation of this file.
1 <?php
7 namespace Magento\Framework\Api;
8 
11 
18 {
19  const FIELD = 'field';
20  const DIRECTION = 'direction';
21  const SORT_ASC = 'ASC';
22  const SORT_DESC = 'DESC';
23 
30  public function __construct(array $data = [])
31  {
32  parent::__construct($data);
33  if (null !== $this->getDirection()) {
34  $this->validateDirection($this->getDirection());
35  }
36  if ($this->getField() !== null) {
37  $this->validateField($this->getField());
38  }
39  }
40 
46  public function getField()
47  {
48  return $this->_get(SortOrder::FIELD);
49  }
50 
59  public function setField($field)
60  {
61  $this->validateField($field);
62 
63  return $this->setData(SortOrder::FIELD, $field);
64  }
65 
71  public function getDirection()
72  {
73  return $this->_get(SortOrder::DIRECTION);
74  }
75 
84  public function setDirection($direction)
85  {
86  $this->validateDirection($direction);
87  return $this->setData(SortOrder::DIRECTION, $this->normalizeDirectionInput($direction));
88  }
89 
97  private function validateDirection($direction): void
98  {
99  $this->validateDirectionIsString($direction);
100  $this->validateDirectionIsAscOrDesc($direction);
101  }
102 
108  private function validateDirectionIsString($direction): void
109  {
110  if (!is_string($direction)) {
111  throw new InputException(new Phrase(
112  'The sort order has to be specified as a string, got %1.',
113  [gettype($direction)]
114  ));
115  }
116  }
117 
123  private function validateDirectionIsAscOrDesc($direction): void
124  {
125  $normalizedDirection = $this->normalizeDirectionInput($direction);
126  if (!in_array($normalizedDirection, [SortOrder::SORT_ASC, SortOrder::SORT_DESC], true)) {
127  throw new InputException(new Phrase(
128  'The sort order has to be specified as %1 for ascending order or %2 for descending order.',
130  ));
131  }
132  }
133 
138  private function normalizeDirectionInput($direction)
139  {
140  return strtoupper($direction);
141  }
142 
150  private function validateField(string $field): void
151  {
152  if (preg_match('/[^a-z0-9\_]/i', $field)) {
153  throw new InputException(
154  new Phrase(
155  'Sort order field %1 contains restricted symbols',
156  [$field]
157  )
158  );
159  }
160  }
161 }