Exemplo n.º 1
0
 /**
  * Returns a generator selected by the user from a multilevel console menu.
  */
 protected function selectGenerator(InputInterface $input, OutputInterface $output)
 {
     // Narrow menu tree according to the active menu items.
     $active_menu_tree = $this->menuTree;
     foreach ($this->activeMenuItems as $active_menu_item) {
         $active_menu_tree = $active_menu_tree[$active_menu_item];
     }
     // The $active_menu_tree can be either an array of child menu items or
     // the TRUE value indicating that the user reached the final menu point and
     // active menu items contain the actual command name.
     if (is_array($active_menu_tree)) {
         $subtrees = $command_names = [];
         // We build $choices as an associative array to be able to find
         // later menu items by respective labels.
         foreach ($active_menu_tree as $menu_item => $subtree) {
             $menu_item_label = $this->createMenuItemLabel($menu_item, is_array($subtree));
             if (is_array($subtree)) {
                 $subtrees[$menu_item] = $menu_item_label;
             } else {
                 $command_names[$menu_item] = $menu_item_label;
             }
         }
         asort($subtrees);
         asort($command_names);
         // Generally the choices array consists of the following parts:
         // - Reference to the parent menu level.
         // - Sorted list of nested menu levels.
         // - Sorted list of commands.
         $choices = ['..' => '..'] + $subtrees + $command_names;
         $question = new ChoiceQuestion('<title>Select generator:</title>', array_values($choices));
         $question->setPrompt('  >>> ');
         $answer_label = $this->getHelper('question')->ask($input, $output, $question);
         $answer = array_search($answer_label, $choices);
         if (!$answer) {
             throw new \UnexpectedValueException(sprintf('"%s" menu item was not found', $answer_label));
         }
         if ($answer == '..') {
             // Exit the application if the user choices zero key
             // on the top menu level.
             if (count($this->activeMenuItems) == 0) {
                 return NULL;
             }
             // Set the menu one level higher.
             array_pop($this->activeMenuItems);
         } else {
             // Set the menu one level deeper.
             $this->activeMenuItems[] = $answer;
         }
         return $this->selectGenerator($input, $output);
     } else {
         return implode(':', $this->activeMenuItems);
     }
 }