Example #1
0
 /**
  * Validates that the console options/arguments meets the definition
  * @param   Event   $event
  * @return  $this
  * @throws
  */
 public function validate(Event $event)
 {
     foreach ($this->getOptions() as $option) {
         if ($event->hasOption($option->getNames())) {
             //get the value
             $value = $event->getOption($option->getNames(), $option->getDefault());
             //check whether a value is allowed
             if (!$option->isValueAllowed() && !is_null($value)) {
                 throw new \RuntimeException("Option \"{$option->getName()}\" cannot have a value.");
             }
             //check whether a value is required
             if ($option->isValueRequired() && is_null($value)) {
                 throw new \RuntimeException("Option \"{$option->getName()}\" requires a value.");
             }
             //filter the value
             $filter = $option->getFilter();
             if ($filter) {
                 $value = call_user_func($filter, $value);
             }
             //update the value
             if ($event->hasOption($option->getShortName())) {
                 $event->setOption($option->getShortName(), $value);
             } else {
                 $event->setOption($option->getLongName(), $value);
             }
             //validate the value
             $validator = $option->getValidator();
             if ($validator) {
                 if (call_user_func($validator, $value) == false) {
                     throw new \RuntimeException("Option \"{$option->getName()}\" is invalid.");
                 }
             }
         } else {
             //check whether the option is required
             if ($option->isRequired()) {
                 throw new \RuntimeException("Option \"{$option->getName()}\" is required.");
             }
             //get the default value
             $default = $option->getDefault();
             //set the default value
             if ($option->isValueAllowed() && !is_null($default)) {
                 $event->setOption($option->getLongName(), $default);
             }
         }
     }
 }