Utils.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. <?php
  2. namespace Knuckles\Scribe\Tools;
  3. use Closure;
  4. use Exception;
  5. use FastRoute\RouteParser\Std;
  6. use Illuminate\Routing\Route;
  7. use Illuminate\Support\Str;
  8. use Knuckles\Scribe\Tools\ConsoleOutputUtils as c;
  9. use League\Flysystem\Adapter\Local;
  10. use League\Flysystem\Filesystem;
  11. use ReflectionClass;
  12. use ReflectionException;
  13. use ReflectionFunction;
  14. use ReflectionFunctionAbstract;
  15. class Utils
  16. {
  17. public static function getUrlWithBoundParameters(Route $route, array $urlParameters = []): string
  18. {
  19. $uri = $route->uri();
  20. return self::replaceUrlParameterPlaceholdersWithValues($uri, $urlParameters);
  21. }
  22. /**
  23. * Transform parameters in URLs into real values (/users/{user} -> /users/2).
  24. * Uses @urlParam values specified by caller, otherwise just uses '1'.
  25. *
  26. * @param string $uri
  27. * @param array $urlParameters Dictionary of url params and example values
  28. *
  29. * @return mixed
  30. */
  31. public static function replaceUrlParameterPlaceholdersWithValues(string $uri, array $urlParameters)
  32. {
  33. if (empty($urlParameters)) {
  34. return $uri;
  35. }
  36. if (self::isLumen()) {
  37. $boundUri = '';
  38. $possibilities = (new Std)->parse($uri);
  39. // See https://github.com/nikic/FastRoute#overriding-the-route-parser-and-dispatcher
  40. $possibilityWithAllSegmentsPresent = end($possibilities);
  41. foreach ($possibilityWithAllSegmentsPresent as $part) {
  42. if (!is_array($part)) {
  43. // It's just a path segment, not a URL parameter'
  44. $boundUri .= $part;
  45. continue;
  46. }
  47. $name = $part[0];
  48. $boundUri .= $urlParameters[$name];
  49. }
  50. return $boundUri;
  51. }
  52. foreach ($urlParameters as $parameterName => $example) {
  53. $uri = preg_replace('#\{' . $parameterName . '\??}#', $example, $uri);
  54. }
  55. // Remove unbound optional parameters with nothing
  56. $uri = preg_replace('#{([^/]+\?)}#', '', $uri);
  57. // Replace any unbound non-optional parameters with '1'
  58. $uri = preg_replace('#{([^/]+)}#', '1', $uri);
  59. return $uri;
  60. }
  61. public static function getRouteClassAndMethodNames(Route $route): array
  62. {
  63. $action = $route->getAction();
  64. $uses = $action['uses'];
  65. if ($uses !== null) {
  66. if (is_array($uses)) {
  67. return $uses;
  68. } elseif (is_string($uses)) {
  69. return explode('@', $uses);
  70. } elseif (static::isInvokableObject($uses)) {
  71. return [$uses, '__invoke'];
  72. }
  73. }
  74. if (array_key_exists(0, $action) && array_key_exists(1, $action)) {
  75. return [
  76. 0 => $action[0],
  77. 1 => $action[1],
  78. ];
  79. }
  80. throw new Exception("Couldn't get class and method names for route " . c::getRouteRepresentation($route) . '.');
  81. }
  82. public static function deleteDirectoryAndContents($dir, $base = null)
  83. {
  84. $dir = ltrim($dir, '/');
  85. $adapter = new Local($base ?: realpath(__DIR__ . '/../../'));
  86. $fs = new Filesystem($adapter);
  87. $fs->deleteDir($dir);
  88. }
  89. /**
  90. * @param mixed $value
  91. *
  92. * @return bool
  93. */
  94. public static function isInvokableObject($value): bool
  95. {
  96. return is_object($value) && method_exists($value, '__invoke');
  97. }
  98. /**
  99. * Returns the route method or closure as an instance of ReflectionMethod or ReflectionFunction
  100. *
  101. * @param array $routeControllerAndMethod
  102. *
  103. * @return ReflectionFunctionAbstract
  104. * @throws ReflectionException
  105. *
  106. */
  107. public static function getReflectedRouteMethod(array $routeControllerAndMethod): ReflectionFunctionAbstract
  108. {
  109. [$class, $method] = $routeControllerAndMethod;
  110. if ($class instanceof Closure) {
  111. return new ReflectionFunction($class);
  112. }
  113. return (new ReflectionClass($class))->getMethod($method);
  114. }
  115. public static function isArrayType(string $typeName)
  116. {
  117. return Str::endsWith($typeName, '[]');
  118. }
  119. public static function getBaseTypeFromArrayType(string $typeName)
  120. {
  121. return substr($typeName, 0, -2);
  122. }
  123. public static function getModelFactory(string $modelName, array $states = [])
  124. {
  125. if (!function_exists('factory')) { // Laravel 8 type factory
  126. $factory = call_user_func_array([$modelName, 'factory'], []);
  127. if (count($states)) {
  128. foreach ($states as $state) {
  129. $factory = $factory->$state();
  130. }
  131. }
  132. } else {
  133. $factory = factory($modelName);
  134. if (count($states)) {
  135. $factory = $factory->states($states);
  136. }
  137. }
  138. return $factory;
  139. }
  140. public static function isLumen(): bool
  141. {
  142. // See https://github.com/laravel/lumen-framework/blob/99330e6ca2198e228f5894cf84d843c2a539a250/src/Application.php#L163
  143. $app = app();
  144. if ($app
  145. && is_callable([$app, 'version'])
  146. && Str::startsWith($app->version(), 'Lumen')
  147. ) {
  148. return true;
  149. }
  150. return false;
  151. }
  152. public static function arrayMapRecursive($arr, $fn)
  153. {
  154. return array_map(function ($item) use ($fn) {
  155. return is_array($item) ? self::arrayMapRecursive($item, $fn) : $fn($item);
  156. }, $arr);
  157. }
  158. }