Camel.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Knuckles\Camel;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Support\Collection;
  5. use Illuminate\Support\Str;
  6. use Knuckles\Camel\Output\EndpointData;
  7. use League\Flysystem\Adapter\Local;
  8. use League\Flysystem\Filesystem;
  9. use Symfony\Component\Yaml\Yaml;
  10. class Camel
  11. {
  12. /**
  13. * Load endpoints from the Camel files into groups (arrays).
  14. *
  15. * @param string $folder
  16. * @return array[]
  17. */
  18. public static function loadEndpointsIntoGroups(string $folder): array
  19. {
  20. $groups = [];
  21. self::loadEndpointsFromCamelFiles($folder, function ($group) use ($groups) {
  22. $group['endpoints'] = array_map(function (array $endpoint) {
  23. return new EndpointData($endpoint);
  24. }, $group['endpoints']);
  25. $groups[] = $group;
  26. });
  27. return $groups;
  28. }
  29. /**
  30. * Load endpoints from the Camel files into a flat list of endpoint arrays.
  31. *
  32. * @param string $folder
  33. * @return array[]
  34. */
  35. public static function loadEndpointsToFlatPrimitivesArray(string $folder): array
  36. {
  37. $endpoints = [];
  38. self::loadEndpointsFromCamelFiles($folder, function ($group) use ($endpoints) {
  39. foreach ($group['endpoints'] as $endpoint) {
  40. $endpoints[] = $endpoint;
  41. }
  42. });
  43. return $endpoints;
  44. }
  45. public static function loadEndpointsFromCamelFiles(string $folder, callable $callback)
  46. {
  47. $adapter = new Local(getcwd());
  48. $fs = new Filesystem($adapter);
  49. $contents = $fs->listContents($folder);;
  50. foreach ($contents as $object) {
  51. if ($object['type'] == 'file' && Str::endsWith($object['basename'], '.yaml')) {
  52. $group = Yaml::parseFile($object['path']);
  53. $callback($group);
  54. }
  55. }
  56. }
  57. public static function doesGroupContainEndpoint(array $group, EndpointData $endpoint): bool
  58. {
  59. return boolval(Arr::first($group['endpoints'], fn(EndpointData $e) => $e->endpointId() === $endpoint->endpointId()));
  60. }
  61. /**
  62. * @param array[] $endpoints
  63. *
  64. * @return array[]
  65. */
  66. public static function groupEndpoints(array $endpoints): array
  67. {
  68. $groupedEndpoints = collect($endpoints)
  69. ->groupBy('metadata.groupName')
  70. ->sortKeys(SORT_NATURAL);
  71. return $groupedEndpoints->map(fn(Collection $group) => [
  72. 'name' => $group[0]->metadata->groupName,
  73. 'description' => Arr::first($group, function ($endpointData) {
  74. return $endpointData->metadata->groupDescription !== '';
  75. })->metadata->groupDescription ?? '',
  76. 'endpoints' => $group->map(fn($endpointData) => $endpointData->forOutput())->all(),
  77. ])->all();
  78. }
  79. }