ShowModelCommand.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. <?php
  2. namespace Illuminate\Database\Console;
  3. use BackedEnum;
  4. use Illuminate\Contracts\Container\BindingResolutionException;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Relations\Relation;
  7. use Illuminate\Support\Facades\Gate;
  8. use Illuminate\Support\Str;
  9. use ReflectionClass;
  10. use ReflectionMethod;
  11. use ReflectionNamedType;
  12. use SplFileObject;
  13. use Symfony\Component\Console\Attribute\AsCommand;
  14. use Symfony\Component\Console\Output\OutputInterface;
  15. use UnitEnum;
  16. #[AsCommand(name: 'model:show')]
  17. class ShowModelCommand extends DatabaseInspectionCommand
  18. {
  19. /**
  20. * The console command name.
  21. *
  22. * @var string
  23. */
  24. protected $name = 'model:show {model}';
  25. /**
  26. * The console command description.
  27. *
  28. * @var string
  29. */
  30. protected $description = 'Show information about an Eloquent model';
  31. /**
  32. * The console command signature.
  33. *
  34. * @var string
  35. */
  36. protected $signature = 'model:show {model : The model to show}
  37. {--database= : The database connection to use}
  38. {--json : Output the model as JSON}';
  39. /**
  40. * The methods that can be called in a model to indicate a relation.
  41. *
  42. * @var array
  43. */
  44. protected $relationMethods = [
  45. 'hasMany',
  46. 'hasManyThrough',
  47. 'hasOneThrough',
  48. 'belongsToMany',
  49. 'hasOne',
  50. 'belongsTo',
  51. 'morphOne',
  52. 'morphTo',
  53. 'morphMany',
  54. 'morphToMany',
  55. 'morphedByMany',
  56. ];
  57. /**
  58. * Execute the console command.
  59. *
  60. * @return int
  61. */
  62. public function handle()
  63. {
  64. $class = $this->qualifyModel($this->argument('model'));
  65. try {
  66. $model = $this->laravel->make($class);
  67. $class = get_class($model);
  68. } catch (BindingResolutionException $e) {
  69. $this->components->error($e->getMessage());
  70. return 1;
  71. }
  72. if ($this->option('database')) {
  73. $model->setConnection($this->option('database'));
  74. }
  75. $this->display(
  76. $class,
  77. $model->getConnection()->getName(),
  78. $model->getConnection()->getTablePrefix().$model->getTable(),
  79. $this->getPolicy($model),
  80. $this->getAttributes($model),
  81. $this->getRelations($model),
  82. $this->getEvents($model),
  83. $this->getObservers($model),
  84. );
  85. return 0;
  86. }
  87. /**
  88. * Get the first policy associated with this model.
  89. *
  90. * @param \Illuminate\Database\Eloquent\Model $model
  91. * @return string
  92. */
  93. protected function getPolicy($model)
  94. {
  95. $policy = Gate::getPolicyFor($model::class);
  96. return $policy ? $policy::class : null;
  97. }
  98. /**
  99. * Get the column attributes for the given model.
  100. *
  101. * @param \Illuminate\Database\Eloquent\Model $model
  102. * @return \Illuminate\Support\Collection
  103. */
  104. protected function getAttributes($model)
  105. {
  106. $connection = $model->getConnection();
  107. $schema = $connection->getSchemaBuilder();
  108. $table = $model->getTable();
  109. $columns = $schema->getColumns($table);
  110. $indexes = $schema->getIndexes($table);
  111. return collect($columns)
  112. ->map(fn ($column) => [
  113. 'name' => $column['name'],
  114. 'type' => $column['type'],
  115. 'increments' => $column['auto_increment'],
  116. 'nullable' => $column['nullable'],
  117. 'default' => $this->getColumnDefault($column, $model),
  118. 'unique' => $this->columnIsUnique($column['name'], $indexes),
  119. 'fillable' => $model->isFillable($column['name']),
  120. 'hidden' => $this->attributeIsHidden($column['name'], $model),
  121. 'appended' => null,
  122. 'cast' => $this->getCastType($column['name'], $model),
  123. ])
  124. ->merge($this->getVirtualAttributes($model, $columns));
  125. }
  126. /**
  127. * Get the virtual (non-column) attributes for the given model.
  128. *
  129. * @param \Illuminate\Database\Eloquent\Model $model
  130. * @param array $columns
  131. * @return \Illuminate\Support\Collection
  132. */
  133. protected function getVirtualAttributes($model, $columns)
  134. {
  135. $class = new ReflectionClass($model);
  136. return collect($class->getMethods())
  137. ->reject(
  138. fn (ReflectionMethod $method) => $method->isStatic()
  139. || $method->isAbstract()
  140. || $method->getDeclaringClass()->getName() === Model::class
  141. )
  142. ->mapWithKeys(function (ReflectionMethod $method) use ($model) {
  143. if (preg_match('/^get(.+)Attribute$/', $method->getName(), $matches) === 1) {
  144. return [Str::snake($matches[1]) => 'accessor'];
  145. } elseif ($model->hasAttributeMutator($method->getName())) {
  146. return [Str::snake($method->getName()) => 'attribute'];
  147. } else {
  148. return [];
  149. }
  150. })
  151. ->reject(fn ($cast, $name) => collect($columns)->contains('name', $name))
  152. ->map(fn ($cast, $name) => [
  153. 'name' => $name,
  154. 'type' => null,
  155. 'increments' => false,
  156. 'nullable' => null,
  157. 'default' => null,
  158. 'unique' => null,
  159. 'fillable' => $model->isFillable($name),
  160. 'hidden' => $this->attributeIsHidden($name, $model),
  161. 'appended' => $model->hasAppended($name),
  162. 'cast' => $cast,
  163. ])
  164. ->values();
  165. }
  166. /**
  167. * Get the relations from the given model.
  168. *
  169. * @param \Illuminate\Database\Eloquent\Model $model
  170. * @return \Illuminate\Support\Collection
  171. */
  172. protected function getRelations($model)
  173. {
  174. return collect(get_class_methods($model))
  175. ->map(fn ($method) => new ReflectionMethod($model, $method))
  176. ->reject(
  177. fn (ReflectionMethod $method) => $method->isStatic()
  178. || $method->isAbstract()
  179. || $method->getDeclaringClass()->getName() === Model::class
  180. || $method->getNumberOfParameters() > 0
  181. )
  182. ->filter(function (ReflectionMethod $method) {
  183. if ($method->getReturnType() instanceof ReflectionNamedType
  184. && is_subclass_of($method->getReturnType()->getName(), Relation::class)) {
  185. return true;
  186. }
  187. $file = new SplFileObject($method->getFileName());
  188. $file->seek($method->getStartLine() - 1);
  189. $code = '';
  190. while ($file->key() < $method->getEndLine()) {
  191. $code .= trim($file->current());
  192. $file->next();
  193. }
  194. return collect($this->relationMethods)
  195. ->contains(fn ($relationMethod) => str_contains($code, '$this->'.$relationMethod.'('));
  196. })
  197. ->map(function (ReflectionMethod $method) use ($model) {
  198. $relation = $method->invoke($model);
  199. if (! $relation instanceof Relation) {
  200. return null;
  201. }
  202. return [
  203. 'name' => $method->getName(),
  204. 'type' => Str::afterLast(get_class($relation), '\\'),
  205. 'related' => get_class($relation->getRelated()),
  206. ];
  207. })
  208. ->filter()
  209. ->values();
  210. }
  211. /**
  212. * Get the Events that the model dispatches.
  213. *
  214. * @param \Illuminate\Database\Eloquent\Model $model
  215. * @return \Illuminate\Support\Collection
  216. */
  217. protected function getEvents($model)
  218. {
  219. return collect($model->dispatchesEvents())
  220. ->map(fn (string $class, string $event) => [
  221. 'event' => $event,
  222. 'class' => $class,
  223. ])->values();
  224. }
  225. /**
  226. * Get the Observers watching this model.
  227. *
  228. * @param \Illuminate\Database\Eloquent\Model $model
  229. * @return \Illuminate\Support\Collection
  230. */
  231. protected function getObservers($model)
  232. {
  233. $listeners = $this->getLaravel()->make('events')->getRawListeners();
  234. // Get the Eloquent observers for this model...
  235. $listeners = array_filter($listeners, function ($v, $key) use ($model) {
  236. return Str::startsWith($key, 'eloquent.') && Str::endsWith($key, $model::class);
  237. }, ARRAY_FILTER_USE_BOTH);
  238. // Format listeners Eloquent verb => Observer methods...
  239. $extractVerb = function ($key) {
  240. preg_match('/eloquent.([a-zA-Z]+)\: /', $key, $matches);
  241. return $matches[1] ?? '?';
  242. };
  243. $formatted = [];
  244. foreach ($listeners as $key => $observerMethods) {
  245. $formatted[] = [
  246. 'event' => $extractVerb($key),
  247. 'observer' => array_map(fn ($obs) => is_string($obs) ? $obs : 'Closure', $observerMethods),
  248. ];
  249. }
  250. return collect($formatted);
  251. }
  252. /**
  253. * Render the model information.
  254. *
  255. * @param string $class
  256. * @param string $database
  257. * @param string $table
  258. * @param string $policy
  259. * @param \Illuminate\Support\Collection $attributes
  260. * @param \Illuminate\Support\Collection $relations
  261. * @param \Illuminate\Support\Collection $events
  262. * @param \Illuminate\Support\Collection $observers
  263. * @return void
  264. */
  265. protected function display($class, $database, $table, $policy, $attributes, $relations, $events, $observers)
  266. {
  267. $this->option('json')
  268. ? $this->displayJson($class, $database, $table, $policy, $attributes, $relations, $events, $observers)
  269. : $this->displayCli($class, $database, $table, $policy, $attributes, $relations, $events, $observers);
  270. }
  271. /**
  272. * Render the model information as JSON.
  273. *
  274. * @param string $class
  275. * @param string $database
  276. * @param string $table
  277. * @param string $policy
  278. * @param \Illuminate\Support\Collection $attributes
  279. * @param \Illuminate\Support\Collection $relations
  280. * @param \Illuminate\Support\Collection $events
  281. * @param \Illuminate\Support\Collection $observers
  282. * @return void
  283. */
  284. protected function displayJson($class, $database, $table, $policy, $attributes, $relations, $events, $observers)
  285. {
  286. $this->output->writeln(
  287. collect([
  288. 'class' => $class,
  289. 'database' => $database,
  290. 'table' => $table,
  291. 'policy' => $policy,
  292. 'attributes' => $attributes,
  293. 'relations' => $relations,
  294. 'events' => $events,
  295. 'observers' => $observers,
  296. ])->toJson()
  297. );
  298. }
  299. /**
  300. * Render the model information for the CLI.
  301. *
  302. * @param string $class
  303. * @param string $database
  304. * @param string $table
  305. * @param string $policy
  306. * @param \Illuminate\Support\Collection $attributes
  307. * @param \Illuminate\Support\Collection $relations
  308. * @param \Illuminate\Support\Collection $events
  309. * @param \Illuminate\Support\Collection $observers
  310. * @return void
  311. */
  312. protected function displayCli($class, $database, $table, $policy, $attributes, $relations, $events, $observers)
  313. {
  314. $this->newLine();
  315. $this->components->twoColumnDetail('<fg=green;options=bold>'.$class.'</>');
  316. $this->components->twoColumnDetail('Database', $database);
  317. $this->components->twoColumnDetail('Table', $table);
  318. if ($policy) {
  319. $this->components->twoColumnDetail('Policy', $policy);
  320. }
  321. $this->newLine();
  322. $this->components->twoColumnDetail(
  323. '<fg=green;options=bold>Attributes</>',
  324. 'type <fg=gray>/</> <fg=yellow;options=bold>cast</>',
  325. );
  326. foreach ($attributes as $attribute) {
  327. $first = trim(sprintf(
  328. '%s %s',
  329. $attribute['name'],
  330. collect(['increments', 'unique', 'nullable', 'fillable', 'hidden', 'appended'])
  331. ->filter(fn ($property) => $attribute[$property])
  332. ->map(fn ($property) => sprintf('<fg=gray>%s</>', $property))
  333. ->implode('<fg=gray>,</> ')
  334. ));
  335. $second = collect([
  336. $attribute['type'],
  337. $attribute['cast'] ? '<fg=yellow;options=bold>'.$attribute['cast'].'</>' : null,
  338. ])->filter()->implode(' <fg=gray>/</> ');
  339. $this->components->twoColumnDetail($first, $second);
  340. if ($attribute['default'] !== null) {
  341. $this->components->bulletList(
  342. [sprintf('default: %s', $attribute['default'])],
  343. OutputInterface::VERBOSITY_VERBOSE
  344. );
  345. }
  346. }
  347. $this->newLine();
  348. $this->components->twoColumnDetail('<fg=green;options=bold>Relations</>');
  349. foreach ($relations as $relation) {
  350. $this->components->twoColumnDetail(
  351. sprintf('%s <fg=gray>%s</>', $relation['name'], $relation['type']),
  352. $relation['related']
  353. );
  354. }
  355. $this->newLine();
  356. $this->components->twoColumnDetail('<fg=green;options=bold>Events</>');
  357. if ($events->count()) {
  358. foreach ($events as $event) {
  359. $this->components->twoColumnDetail(
  360. sprintf('%s', $event['event']),
  361. sprintf('%s', $event['class']),
  362. );
  363. }
  364. }
  365. $this->newLine();
  366. $this->components->twoColumnDetail('<fg=green;options=bold>Observers</>');
  367. if ($observers->count()) {
  368. foreach ($observers as $observer) {
  369. $this->components->twoColumnDetail(
  370. sprintf('%s', $observer['event']),
  371. implode(', ', $observer['observer'])
  372. );
  373. }
  374. }
  375. $this->newLine();
  376. }
  377. /**
  378. * Get the cast type for the given column.
  379. *
  380. * @param string $column
  381. * @param \Illuminate\Database\Eloquent\Model $model
  382. * @return string|null
  383. */
  384. protected function getCastType($column, $model)
  385. {
  386. if ($model->hasGetMutator($column) || $model->hasSetMutator($column)) {
  387. return 'accessor';
  388. }
  389. if ($model->hasAttributeMutator($column)) {
  390. return 'attribute';
  391. }
  392. return $this->getCastsWithDates($model)->get($column) ?? null;
  393. }
  394. /**
  395. * Get the model casts, including any date casts.
  396. *
  397. * @param \Illuminate\Database\Eloquent\Model $model
  398. * @return \Illuminate\Support\Collection
  399. */
  400. protected function getCastsWithDates($model)
  401. {
  402. return collect($model->getDates())
  403. ->filter()
  404. ->flip()
  405. ->map(fn () => 'datetime')
  406. ->merge($model->getCasts());
  407. }
  408. /**
  409. * Get the default value for the given column.
  410. *
  411. * @param array $column
  412. * @param \Illuminate\Database\Eloquent\Model $model
  413. * @return mixed|null
  414. */
  415. protected function getColumnDefault($column, $model)
  416. {
  417. $attributeDefault = $model->getAttributes()[$column['name']] ?? null;
  418. return match (true) {
  419. $attributeDefault instanceof BackedEnum => $attributeDefault->value,
  420. $attributeDefault instanceof UnitEnum => $attributeDefault->name,
  421. default => $attributeDefault ?? $column['default'],
  422. };
  423. }
  424. /**
  425. * Determine if the given attribute is hidden.
  426. *
  427. * @param string $attribute
  428. * @param \Illuminate\Database\Eloquent\Model $model
  429. * @return bool
  430. */
  431. protected function attributeIsHidden($attribute, $model)
  432. {
  433. if (count($model->getHidden()) > 0) {
  434. return in_array($attribute, $model->getHidden());
  435. }
  436. if (count($model->getVisible()) > 0) {
  437. return ! in_array($attribute, $model->getVisible());
  438. }
  439. return false;
  440. }
  441. /**
  442. * Determine if the given attribute is unique.
  443. *
  444. * @param string $column
  445. * @param array $indexes
  446. * @return bool
  447. */
  448. protected function columnIsUnique($column, $indexes)
  449. {
  450. return collect($indexes)->contains(
  451. fn ($index) => count($index['columns']) === 1 && $index['columns'][0] === $column && $index['unique']
  452. );
  453. }
  454. /**
  455. * Qualify the given model class base name.
  456. *
  457. * @param string $model
  458. * @return string
  459. *
  460. * @see \Illuminate\Console\GeneratorCommand
  461. */
  462. protected function qualifyModel(string $model)
  463. {
  464. if (str_contains($model, '\\') && class_exists($model)) {
  465. return $model;
  466. }
  467. $model = ltrim($model, '\\/');
  468. $model = str_replace('/', '\\', $model);
  469. $rootNamespace = $this->laravel->getNamespace();
  470. if (Str::startsWith($model, $rootNamespace)) {
  471. return $model;
  472. }
  473. return is_dir(app_path('Models'))
  474. ? $rootNamespace.'Models\\'.$model
  475. : $rootNamespace.$model;
  476. }
  477. }