OpenSource CLI-App to install and handle stuff related to Web-Server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
2.3 KiB

4 years ago
  1. <?php
  2. namespace App\Menus;
  3. use PhpSchool\CliMenu\MenuItem\StaticItem;
  4. use Respect\Validation\Exceptions\NestedValidationException;
  5. /**
  6. *
  7. *
  8. *
  9. *
  10. */
  11. class ItemValidator
  12. {
  13. // items from menu
  14. private $items;
  15. // current message
  16. private $message;
  17. // validator
  18. private $validator;
  19. /**
  20. *
  21. *
  22. */
  23. public function __construct($validator)
  24. {
  25. $this->validator = $validator;
  26. $this->message = new StaticItem(''); // must create to compare in items
  27. }
  28. /**
  29. * remove all items from menu and save them
  30. *
  31. * @param [type] $menu
  32. *
  33. */
  34. private function clear(&$menu)
  35. {
  36. $this->items = $menu->getItems();
  37. foreach($menu->getItems() as $item) {
  38. $menu->removeItem($item);
  39. }
  40. }
  41. /**
  42. * add staticItem after item
  43. *
  44. * @param [type] $menu
  45. * @param [type] $after
  46. * @param [type] $target
  47. *
  48. */
  49. private function addAfter(&$menu, $after, $target)
  50. {
  51. $this->clear($menu);
  52. foreach($this->items as $item) {
  53. $menu->addItem($item);
  54. if ($after === $item) {
  55. $menu->addItem($target, true);
  56. }
  57. }
  58. }
  59. /**
  60. * remove staticItem
  61. *
  62. *
  63. * @param [type] $menu [description]
  64. * @param [type] $target [description]
  65. *
  66. */
  67. private function remove(&$menu, $target)
  68. {
  69. $this->clear($menu);
  70. foreach($this->items as $item) {
  71. if ($item === $target) {
  72. continue;
  73. }
  74. $menu->addItem($item);
  75. }
  76. }
  77. /**
  78. * validate,
  79. * if failed show staticItem with errors,
  80. * if not remove staticItem if found
  81. *
  82. * @param [type] $menu
  83. * @param [type] $item
  84. * @param [type] $data
  85. *
  86. */
  87. public function validate(&$menu, $item, $data)
  88. {
  89. try {
  90. $this->validator->assert($data);
  91. } catch(NestedValidationException $exception) {
  92. $errors = $exception->getMessages();
  93. }
  94. if (isset($errors)) {
  95. // @TODO use ColorUtil
  96. $this->message->setText("\033[33m"."\xE2\x9A\xA0 ".join(' ', $errors));
  97. $this->addAfter($menu, $item, $this->message);
  98. } else {
  99. $this->remove($menu, $this->message);
  100. }
  101. }
  102. }