Utils.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. namespace Knuckles\Scribe\Tools;
  3. use Closure;
  4. use DirectoryIterator;
  5. use Exception;
  6. use FastRoute\RouteParser\Std;
  7. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  8. use Illuminate\Routing\Route;
  9. use Illuminate\Support\Str;
  10. use Knuckles\Scribe\Exceptions\CouldntFindFactory;
  11. use Knuckles\Scribe\Tools\ConsoleOutputUtils as c;
  12. use League\Flysystem\Filesystem;
  13. use League\Flysystem\Local\LocalFilesystemAdapter;
  14. use ReflectionClass;
  15. use ReflectionException;
  16. use ReflectionFunction;
  17. use ReflectionFunctionAbstract;
  18. use Throwable;
  19. class Utils
  20. {
  21. public static function getUrlWithBoundParameters(string $uri, array $urlParameters = []): string
  22. {
  23. return self::replaceUrlParameterPlaceholdersWithValues($uri, $urlParameters);
  24. }
  25. /**
  26. * Transform parameters in URLs into real values (/users/{user} -> /users/2).
  27. * Uses @urlParam values specified by caller, otherwise just uses '1'.
  28. *
  29. * @param string $uri
  30. * @param array $urlParameters Dictionary of url params and example values
  31. *
  32. * @return string
  33. */
  34. public static function replaceUrlParameterPlaceholdersWithValues(string $uri, array $urlParameters): string
  35. {
  36. if (empty($urlParameters)) {
  37. return $uri;
  38. }
  39. if (self::isLumen()) {
  40. $boundUri = '';
  41. $possibilities = (new Std)->parse($uri);
  42. // See https://github.com/nikic/FastRoute#overriding-the-route-parser-and-dispatcher
  43. $possibilityWithAllSegmentsPresent = end($possibilities);
  44. foreach ($possibilityWithAllSegmentsPresent as $part) {
  45. if (!is_array($part)) {
  46. // It's just a path segment, not a URL parameter'
  47. $boundUri .= $part;
  48. continue;
  49. }
  50. $name = $part[0];
  51. $boundUri .= $urlParameters[$name];
  52. }
  53. return $boundUri;
  54. }
  55. foreach ($urlParameters as $parameterName => $example) {
  56. $uri = preg_replace('#\{' . $parameterName . '\??}#', $example, $uri);
  57. }
  58. // Remove unbound optional parameters with nothing
  59. $uri = preg_replace('#{([^/]+\?)}#', '', $uri);
  60. // Replace any unbound non-optional parameters with '1'
  61. $uri = preg_replace('#{([^/]+)}#', '1', $uri);
  62. return $uri;
  63. }
  64. public static function getRouteClassAndMethodNames(Route $route): array
  65. {
  66. $action = $route->getAction();
  67. $uses = $action['uses'];
  68. if ($uses !== null) {
  69. if (is_array($uses)) {
  70. return $uses;
  71. } elseif (is_string($uses)) {
  72. return explode('@', $uses);
  73. } elseif (static::isInvokableObject($uses)) {
  74. return [$uses, '__invoke'];
  75. }
  76. }
  77. if (array_key_exists(0, $action) && array_key_exists(1, $action)) {
  78. return [
  79. 0 => $action[0],
  80. 1 => $action[1],
  81. ];
  82. }
  83. throw new Exception("Couldn't get class and method names for route " . c::getRouteRepresentation($route) . '.');
  84. }
  85. public static function deleteDirectoryAndContents(string $dir, ?string $workingDir = null): void
  86. {
  87. if (class_exists(LocalFilesystemAdapter::class)) {
  88. // Flysystem 2+
  89. $workingDir ??= getcwd();
  90. $adapter = new LocalFilesystemAdapter($workingDir);
  91. $fs = new Filesystem($adapter);
  92. $dir = str_replace($workingDir, '', $dir);
  93. $fs->deleteDirectory($dir);
  94. } else {
  95. // v1
  96. $adapter = new \League\Flysystem\Adapter\Local($workingDir ?: getcwd());
  97. $fs = new Filesystem($adapter);
  98. $dir = str_replace($adapter->getPathPrefix(), '', $dir);
  99. $fs->deleteDir($dir);
  100. }
  101. }
  102. public static function listDirectoryContents(string $dir)
  103. {
  104. if (class_exists(LocalFilesystemAdapter::class)) {
  105. // Flysystem 2+
  106. $adapter = new LocalFilesystemAdapter(getcwd());
  107. $fs = new Filesystem($adapter);
  108. return $fs->listContents($dir);
  109. } else {
  110. // v1
  111. $adapter = new \League\Flysystem\Adapter\Local(getcwd()); // @phpstan-ignore-line
  112. $fs = new Filesystem($adapter); // @phpstan-ignore-line
  113. $dir = str_replace($adapter->getPathPrefix(), '', $dir); // @phpstan-ignore-line
  114. return $fs->listContents($dir);
  115. }
  116. }
  117. public static function copyDirectory(string $src, string $dest): void
  118. {
  119. if (!is_dir($src)) return;
  120. // If the destination directory does not exist create it
  121. if (!is_dir($dest)) {
  122. if (!mkdir($dest, 0777, true)) {
  123. // If the destination directory could not be created stop processing
  124. throw new Exception("Failed to create target directory: $dest");
  125. }
  126. }
  127. // Open the source directory to read in files
  128. $i = new DirectoryIterator($src);
  129. foreach ($i as $f) {
  130. if ($f->isFile()) {
  131. copy($f->getRealPath(), "$dest/" . $f->getFilename());
  132. } else if (!$f->isDot() && $f->isDir()) {
  133. self::copyDirectory($f->getRealPath(), "$dest/$f");
  134. }
  135. }
  136. }
  137. public static function deleteFilesMatching(string $dir, callable $condition): void
  138. {
  139. if (class_exists(LocalFilesystemAdapter::class)) {
  140. // Flysystem 2+
  141. $adapter = new LocalFilesystemAdapter(getcwd());
  142. $fs = new Filesystem($adapter);
  143. $contents = $fs->listContents(ltrim($dir, '/'));
  144. } else {
  145. // v1
  146. $adapter = new \League\Flysystem\Adapter\Local(getcwd()); // @phpstan-ignore-line
  147. $fs = new Filesystem($adapter); // @phpstan-ignore-line
  148. $dir = str_replace($adapter->getPathPrefix(), '', $dir); // @phpstan-ignore-line
  149. $contents = $fs->listContents(ltrim($dir, '/'));
  150. }
  151. foreach ($contents as $file) {
  152. // Flysystem v1 had items as arrays; v2 has objects.
  153. // v2 allows ArrayAccess, but when we drop v1 support (Laravel <9), we should switch to methods
  154. if ($file['type'] == 'file' && $condition($file) === true) {
  155. $fs->delete($file['path']);
  156. }
  157. }
  158. }
  159. /**
  160. * @param mixed $value
  161. *
  162. * @return bool
  163. */
  164. public static function isInvokableObject($value): bool
  165. {
  166. return is_object($value) && method_exists($value, '__invoke');
  167. }
  168. /**
  169. * Returns the route method or closure as an instance of ReflectionMethod or ReflectionFunction
  170. *
  171. * @param array $routeControllerAndMethod
  172. *
  173. * @return ReflectionFunctionAbstract
  174. * @throws ReflectionException
  175. *
  176. */
  177. public static function getReflectedRouteMethod(array $routeControllerAndMethod): ReflectionFunctionAbstract
  178. {
  179. [$class, $method] = $routeControllerAndMethod;
  180. if ($class instanceof Closure) {
  181. return new ReflectionFunction($class);
  182. }
  183. return (new ReflectionClass($class))->getMethod($method);
  184. }
  185. public static function isArrayType(string $typeName)
  186. {
  187. return Str::endsWith($typeName, '[]');
  188. }
  189. public static function getBaseTypeFromArrayType(string $typeName)
  190. {
  191. return substr($typeName, 0, -2);
  192. }
  193. public static function getModelFactory(string $modelName, array $states = [], array $relations = [])
  194. {
  195. // Factories are usually defined without the leading \ in the class name,
  196. // but the user might write it that way in a comment. Let's be safe.
  197. $modelName = ltrim($modelName, '\\');
  198. if (method_exists($modelName, 'factory')) { // Laravel 8 type factory
  199. /** @var \Illuminate\Database\Eloquent\Factories\Factory $factory */
  200. $factory = call_user_func_array([$modelName, 'factory'], []);
  201. foreach ($states as $state) {
  202. if (method_exists(get_class($factory), $state)) {
  203. $factory = $factory->$state();
  204. }
  205. }
  206. foreach ($relations as $relation) {
  207. // Support nested relations; see https://github.com/knuckleswtf/scribe/pull/364 for a detailed example
  208. // Example: App\Models\Author with=posts.categories
  209. $relationChain = explode('.', $relation);
  210. $relationVector = array_shift($relationChain);
  211. $relationModel = get_class((new $modelName())->{$relationVector}()->getModel());
  212. $relationType = get_class((new $modelName())->{$relationVector}());
  213. $factoryChain = empty($relationChain)
  214. ? call_user_func_array([$relationModel, 'factory'], [])
  215. : Utils::getModelFactory($relationModel, $states, $relationChain);
  216. if ($relationType === BelongsToMany::class) {
  217. $pivot = method_exists($factory, 'pivot' . $relationVector)
  218. ? $factory->{'pivot' . $relationVector}()
  219. : [];
  220. $factory = $factory->hasAttached($factoryChain, $pivot, $relationVector);
  221. } else {
  222. $factory = $factory->has($factoryChain, $relationVector);
  223. }
  224. }
  225. } else {
  226. try {
  227. $factory = factory($modelName);
  228. } catch (Throwable $e) {
  229. if (Str::contains($e->getMessage(), "Call to undefined function Knuckles\\Scribe\\Tools\\factory()")) {
  230. throw CouldntFindFactory::forModel($modelName);
  231. } else {
  232. throw $e;
  233. }
  234. }
  235. if (count($states)) {
  236. $factory = $factory->states($states);
  237. }
  238. }
  239. return $factory;
  240. }
  241. public static function isLumen(): bool
  242. {
  243. // See https://github.com/laravel/lumen-framework/blob/99330e6ca2198e228f5894cf84d843c2a539a250/src/Application.php#L163
  244. $app = app();
  245. if ($app
  246. && is_callable([$app, 'version'])
  247. && Str::startsWith($app->version(), 'Lumen')
  248. ) {
  249. return true;
  250. }
  251. return false;
  252. }
  253. }