AnnotationParser.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Knuckles\Scribe\Tools;
  3. class AnnotationParser
  4. {
  5. /**
  6. * Parse an annotation like 'status=400 when="things go wrong" {"message": "failed"}'.
  7. * Attributes are always optional and may appear at the start or the end of the string.
  8. *
  9. * @param string $annotationContent
  10. */
  11. public static function parseIntoContentAndAttributes(string $annotationContent, array $allowedAttributes): array
  12. {
  13. $parsedAttributes = array_fill_keys($allowedAttributes, null);
  14. foreach ($allowedAttributes as $attribute) {
  15. preg_match("/$attribute=([^\\s'\"]+|\".+?\"|'.+?')\\s*/", $annotationContent, $attributeAndValue);
  16. if (count($attributeAndValue)) {
  17. [$matchingText, $attributeValue] = $attributeAndValue;
  18. $annotationContent = str_replace($matchingText, '', $annotationContent);
  19. $parsedAttributes[$attribute] = trim($attributeValue, '"\' ');
  20. }
  21. }
  22. return [
  23. 'content' => trim($annotationContent),
  24. 'attributes' => $parsedAttributes
  25. ];
  26. }
  27. /**
  28. * Parse an annotation like 'title=This message="everything good"' into a key-value array.
  29. * All non key-value fields will be ignored. Useful for `@apiResourceAdditional`,
  30. * where users may specify arbitrary attributes.
  31. *
  32. * @param string $annotationContent
  33. * @return array
  34. */
  35. public static function parseIntoAttributes(string $annotationContent): array
  36. {
  37. $attributes = $matches = [];
  38. preg_match_all(
  39. '/([^\s\'"]+|".+?"|\'.+?\')=([^\s\'"]+|".+?"|\'.+?\')/',
  40. $annotationContent,
  41. $matches,
  42. PREG_SET_ORDER,
  43. );
  44. foreach ($matches as $match) {
  45. $attributes[trim($match[1], '"\' ')] = trim($match[2], '"\' ');
  46. }
  47. return $attributes;
  48. }
  49. }