YamlResponseParser.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Pheanstalk;
  3. use Pheanstalk\Contract\ResponseInterface;
  4. use Pheanstalk\Contract\ResponseParserInterface;
  5. use Pheanstalk\Exception\ClientException;
  6. use Pheanstalk\Response\ArrayResponse;
  7. /**
  8. * A response parser for commands that return a subset of YAML.
  9. *
  10. * Expected response is 'OK', 'NOT_FOUND' response is also handled.
  11. * Parser expects either a YAML list or dictionary, depending on mode.
  12. *
  13. * @author Paul Annesley
  14. */
  15. class YamlResponseParser implements ResponseParserInterface
  16. {
  17. const MODE_LIST = 'list';
  18. const MODE_DICT = 'dict';
  19. private $mode;
  20. /**
  21. * @param string $mode self::MODE_*
  22. */
  23. public function __construct(string $mode)
  24. {
  25. if (!in_array($mode, [self::MODE_DICT, self::MODE_LIST])) {
  26. throw new \InvalidArgumentException('Invalid mode');
  27. }
  28. $this->mode = $mode;
  29. }
  30. public function parseResponse(string $responseLine, ?string $responseData): ArrayResponse
  31. {
  32. if ($responseLine === ResponseInterface::RESPONSE_NOT_FOUND) {
  33. throw new Exception\ServerException(sprintf(
  34. 'Server reported %s',
  35. $responseLine
  36. ));
  37. }
  38. if (!preg_match('#^OK \d+$#', $responseLine)) {
  39. throw new Exception\ServerException(sprintf(
  40. 'Unhandled response: "%s"',
  41. $responseLine
  42. ));
  43. }
  44. $lines = array_filter(explode("\n", $responseData), function ($line) {
  45. return !empty($line) && $line !== '---';
  46. });
  47. return $this->mode === self::MODE_LIST ? $this->parseList($lines) : $this->parseDictionary($lines);
  48. }
  49. private function parseList(array $lines): ArrayResponse
  50. {
  51. $data = [];
  52. foreach ($lines as $line) {
  53. if (strncmp($line, '- ', 2) !== 0) {
  54. throw new ClientException("YAML parse error for line: $line" . print_r($lines, true));
  55. }
  56. $data[] = substr($line, 2);
  57. }
  58. return new ArrayResponse('OK', $data);
  59. }
  60. private function parseDictionary(array $lines): ArrayResponse
  61. {
  62. $data = [];
  63. foreach ($lines as $line) {
  64. if (!preg_match('#(\S+):\s*(.*)#', $line, $matches)) {
  65. throw new ClientException("YAML parse error for line: $line");
  66. }
  67. $data[$matches[1]] = $matches[2];
  68. }
  69. return new ArrayResponse('OK', $data);
  70. }
  71. }