|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Enqueue\AsyncCommand; |
| 4 | + |
| 5 | +final class RunCommand implements \JsonSerializable |
| 6 | +{ |
| 7 | + /** |
| 8 | + * @var string |
| 9 | + */ |
| 10 | + private $command; |
| 11 | + |
| 12 | + /** |
| 13 | + * @var string[] |
| 14 | + */ |
| 15 | + private $arguments; |
| 16 | + |
| 17 | + /** |
| 18 | + * @var string[] |
| 19 | + */ |
| 20 | + private $options; |
| 21 | + |
| 22 | + /** |
| 23 | + * @param string $command |
| 24 | + * @param string[] $arguments |
| 25 | + * @param string[] $options |
| 26 | + */ |
| 27 | + public function __construct($command, array $arguments = [], array $options = []) |
| 28 | + { |
| 29 | + $this->command = $command; |
| 30 | + $this->arguments = $arguments; |
| 31 | + $this->options = $options; |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * @return string |
| 36 | + */ |
| 37 | + public function getCommandLine() |
| 38 | + { |
| 39 | + $optionsString = ''; |
| 40 | + foreach ($this->options as $name => $value) { |
| 41 | + $optionsString .= " $name=$value"; |
| 42 | + } |
| 43 | + $optionsString = trim($optionsString); |
| 44 | + |
| 45 | + $argumentsString = ''; |
| 46 | + foreach ($this->arguments as $value) { |
| 47 | + $argumentsString .= " $value"; |
| 48 | + } |
| 49 | + $argumentsString = trim($argumentsString); |
| 50 | + |
| 51 | + return trim($this->command.' '.$argumentsString.' '.$optionsString); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @return string |
| 56 | + */ |
| 57 | + public function getCommand(): string |
| 58 | + { |
| 59 | + return $this->command; |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * @return string[] |
| 64 | + */ |
| 65 | + public function getArguments(): array |
| 66 | + { |
| 67 | + return $this->arguments; |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * @return string[] |
| 72 | + */ |
| 73 | + public function getOptions(): array |
| 74 | + { |
| 75 | + return $this->options; |
| 76 | + } |
| 77 | + |
| 78 | + public function jsonSerialize() |
| 79 | + { |
| 80 | + return [ |
| 81 | + 'command' => $this->command, |
| 82 | + 'arguments' => $this->arguments, |
| 83 | + 'options' => $this->options, |
| 84 | + ]; |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * @param string $json |
| 89 | + * |
| 90 | + * @return self |
| 91 | + */ |
| 92 | + public static function jsonUnserialize($json) |
| 93 | + { |
| 94 | + $data = json_decode($json, true); |
| 95 | + if (JSON_ERROR_NONE !== json_last_error()) { |
| 96 | + throw new \InvalidArgumentException(sprintf( |
| 97 | + 'The malformed json given. Error %s and message %s', |
| 98 | + json_last_error(), |
| 99 | + json_last_error_msg() |
| 100 | + )); |
| 101 | + } |
| 102 | + |
| 103 | + return new self($data['command'], $data['arguments'], $data['options']); |
| 104 | + } |
| 105 | +} |
0 commit comments