Utils.php 12 KB

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