|
|
- <?php
-
- namespace App\Menus;
-
- use PhpSchool\CliMenu\MenuItem\StaticItem;
- use Respect\Validation\Exceptions\NestedValidationException;
-
- /**
- *
- *
- *
- *
- */
- class ItemValidator
- {
- // items from menu
- private $items;
-
- // current message
- private $message;
-
- // validator
- private $validator;
-
- /**
- *
- *
- */
- public function __construct($validator)
- {
- $this->validator = $validator;
- $this->message = new StaticItem(''); // must create to compare in items
- }
-
- /**
- * remove all items from menu and save them
- *
- * @param [type] $menu
- *
- */
- private function clear(&$menu)
- {
- $this->items = $menu->getItems();
-
- foreach($menu->getItems() as $item) {
- $menu->removeItem($item);
- }
- }
-
- /**
- * add staticItem after item
- *
- * @param [type] $menu
- * @param [type] $after
- * @param [type] $target
- *
- */
- private function addAfter(&$menu, $after, $target)
- {
- $this->clear($menu);
-
- foreach($this->items as $item) {
- $menu->addItem($item);
-
- if ($after === $item) {
- $menu->addItem($target, true);
- }
- }
- }
-
- /**
- * remove staticItem
- *
- *
- * @param [type] $menu [description]
- * @param [type] $target [description]
- *
- */
- private function remove(&$menu, $target)
- {
- $this->clear($menu);
-
- foreach($this->items as $item) {
- if ($item === $target) {
- continue;
- }
-
- $menu->addItem($item);
- }
- }
-
- /**
- * validate,
- * if failed show staticItem with errors,
- * if not remove staticItem if found
- *
- * @param [type] $menu
- * @param [type] $item
- * @param [type] $data
- *
- */
- public function validate(&$menu, $item, $data)
- {
- try {
- $this->validator->assert($data);
- } catch(NestedValidationException $exception) {
- $errors = $exception->getMessages();
- }
-
- if (isset($errors)) {
-
- // @TODO use ColorUtil
- $this->message->setText("\033[33m"."\xE2\x9A\xA0 ".join(' ', $errors));
- $this->addAfter($menu, $item, $this->message);
- } else {
- $this->remove($menu, $this->message);
- }
- }
- }
|