Skip to content

Commit

Permalink
fix: Install & configure rector for laravel + apply fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-code-labx committed Apr 17, 2024
1 parent af19de1 commit e305e0c
Show file tree
Hide file tree
Showing 72 changed files with 285 additions and 276 deletions.
7 changes: 6 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"spatie/laravel-typescript-transformer": "^2.4"
},
"require-dev": {
"driftingly/rector-laravel": "^1.1",
"fakerphp/faker": "^1.23",
"filament/filament": "^3.2",
"larastan/larastan": "^v2.9",
Expand All @@ -41,6 +42,7 @@
"pestphp/pest-plugin-laravel": "^2.3",
"pestphp/pest-plugin-livewire": "^2.1",
"phpunit/phpunit": "^10",
"rector/rector": "^1.0.4",
"spatie/invade": "^1.1",
"spatie/pest-plugin-snapshots": "^2.1"
},
Expand All @@ -62,7 +64,10 @@
"test": "vendor/bin/pest --testsuite=RESTPresenter",
"test-coverage": "vendor/bin/pest --testsuite=RESTPresenter --coverage",
"test-starter-kit:lunar": "vendor/bin/pest --testsuite=starter-kit:lunar",
"format": "vendor/bin/pint"
"test:format": "pint --test",
"test:refactor": "rector --dry-run",
"format": "vendor/bin/pint",
"refactor": "rector"
},
"config": {
"sort-packages": true,
Expand Down
32 changes: 32 additions & 0 deletions rector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php83\Rector\ClassMethod\AddOverrideAttributeToOverriddenMethodsRector;
use RectorLaravel\Set\LaravelSetList;

return RectorConfig::configure()
->withPaths([
__DIR__ . '/src',
__DIR__ . '/tests',
])
->withSkip([
AddOverrideAttributeToOverriddenMethodsRector::class,
])
->withAttributesSets(
symfony: true,
doctrine: true,
)
->withPreparedSets(
deadCode: true,
codeQuality: true,
typeDeclarations: true,
privatization: true,
earlyReturn: true,
strictBooleans: true,
)
->withSets([
LaravelSetList::LARAVEL_110,
])
->withPhpSets();
2 changes: 1 addition & 1 deletion src/Commands/Generator/MakeAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ protected function buildResourceReplacements(): array
$resourceName = type($this->argument('name'))->asString();

return [
'{{ actionNamespace }}' => $kitNamespace
'{{ actionNamespace }}' => $kitNamespace !== '' && $kitNamespace !== '0'
? 'XtendPackages\\RESTPresenter\\' . $kitNamespace . '\\Actions\\' . $this->getNameInput() . '\\' . $this->getNameInput()
: 'XtendPackages\\RESTPresenter\\Resources\\' . Str::plural($resourceName) . '\\Actions\\' . $this->getNameInput() . '\\' . $this->getNameInput(),
'{{ aliasAction }}' => 'Xtend' . $this->getNameInput() . 'Action',
Expand Down
2 changes: 1 addition & 1 deletion src/Commands/Generator/MakeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ protected function getDefaultNamespace($rootNamespace): string
$namespace = type(config('rest-presenter.generator.namespace'))->asString();
$kitNamespace = type($this->argument('kit_namespace'))->asString();

if ($kitNamespace) {
if ($kitNamespace !== '' && $kitNamespace !== '0') {
return $namespace . '\\' . $kitNamespace;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Commands/Generator/MakeData.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class MakeData extends GeneratorCommand

protected $type = 'Data';

public function handle()
public function handle(): void
{
parent::handle();

Expand Down Expand Up @@ -108,7 +108,7 @@ protected function buildResourceReplacements(): array
*/
protected function transformFieldProperties(array $fields): string
{
return collect($fields)->map(function (array $fieldProperties, string $field) {
return collect($fields)->map(function (array $fieldProperties, string $field): string {
$fieldType = strtolower(type($fieldProperties['type'])->asString());
$propertyType = match ($fieldType) {
'int', 'integer', 'bigint' => 'int',
Expand Down
6 changes: 2 additions & 4 deletions src/Commands/Generator/MakePresenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class MakePresenter extends GeneratorCommand

protected $type = 'Presenter';

public function handle()
public function handle(): void
{
if ($this->hasArgument('fields') && is_array($this->argument('fields'))) {
$name = type($this->argument('name'))->asString();
Expand Down Expand Up @@ -75,9 +75,7 @@ protected function getPresenterNamespace(): string
->plural()
->value();

$resourceNamespace = $this->argument('kit_namespace')
? $this->argument('kit_namespace')
: $resourceDirectory;
$resourceNamespace = $this->argument('kit_namespace') ?: $resourceDirectory;

$resourceNamespace = type($resourceNamespace)->asString();
return $resourceNamespace . '\\Presenters\\' . $presenterNamespace;
Expand Down
24 changes: 12 additions & 12 deletions src/Commands/Generator/MakeResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class MakeResource extends GeneratorCommand
*/
protected Collection $presentersArgument;

public function handle()
public function handle(): void
{
$this->actions ??= collect();
$this->filters ??= collect();
Expand Down Expand Up @@ -179,7 +179,7 @@ protected function transformActions(): string
}

return $this->actions->map(
fn ($action) => "'$action' => Actions\\" . ucfirst($action) . '::class',
fn ($action): string => "'$action' => Actions\\" . ucfirst($action) . '::class',
)->implode(",\n\t\t\t") . ',';
}

Expand All @@ -190,7 +190,7 @@ protected function transformFilters(): string
}

return $this->filters->map(
fn ($filter) => "'$filter' => Filters\\" . ucfirst($filter) . '::class',
fn ($filter): string => "'$filter' => Filters\\" . ucfirst($filter) . '::class',
)->implode(",\n\t\t\t") . ',';
}

Expand All @@ -201,7 +201,7 @@ protected function transformPresenters(): string
}

return $this->getPresenters()->map(
function ($presenter, $presenterKey) {
function (string $presenter, $presenterKey): string {
$presenterNamespace = Str::of($presenterKey)
->replace('Presenter', '')
->studly()
Expand Down Expand Up @@ -284,7 +284,7 @@ protected function promptForModel(InputInterface $input): void
{
$model = search(
label: 'Which model should the resource use?',
options: fn () => $this->scanModels(), // @phpstan-ignore-line
options: fn (): array => $this->scanModels(), // @phpstan-ignore-line
placeholder: 'Search for a model...',
hint: 'Press <comment>Enter</> to select the model.'
);
Expand Down Expand Up @@ -363,7 +363,7 @@ protected function promptForPresenters(InputInterface $input, bool $init = true)
hint: 'Press <comment>Enter</> to confirm the presenter name.'
);

if ($presenterName) {
if ($presenterName !== '' && $presenterName !== '0') {
$fields = $this->generateModelFields()->keyBy('name');
$selectedFields = multiselect(
label: 'Select the fields you would like to include in the presenter:',
Expand Down Expand Up @@ -422,12 +422,12 @@ protected function generateFilterSuggestions(): Collection
$reflect = new ReflectionClass($this->model);

return collect($reflect->getMethods(ReflectionMethod::IS_PUBLIC))
->filter(function (ReflectionMethod $method) {
->filter(function (ReflectionMethod $method): bool {
$returnNamedType = $method->getReturnType() instanceof ReflectionNamedType ? $method->getReturnType()->getName() : '';

return $returnNamedType && is_subclass_of($returnNamedType, Relation::class);
})
->mapWithKeys(function (ReflectionMethod $method) {
->mapWithKeys(function (ReflectionMethod $method): array {
$returnNamedType = $method->getReturnType() instanceof ReflectionNamedType ? $method->getReturnType()->getName() : '';

return [
Expand All @@ -443,12 +443,12 @@ protected function scanModels(): array
{
return collect(app('files')->allFiles(app_path()))
->filter(fn (SplFileInfo $file) => Str::endsWith($file->getFilename(), '.php'))
->map(fn (SplFileInfo $file) => $file->getRelativePathname())
->map(fn (SplFileInfo $file): string => $file->getRelativePathname())
->map(fn (string $file) => 'App\\' . str_replace(['/', '.php'], ['\\', ''], $file))
->filter(fn (string $class) => class_exists($class))
->map(fn (string $class) => new ReflectionClass($class))
->filter(fn (string $class): bool => class_exists($class))
->map(fn (string $class): \ReflectionClass => new ReflectionClass($class))
->filter(fn (ReflectionClass $class) => $class->isSubclassOf(Model::class))
->mapWithKeys(fn (ReflectionClass $class) => [$class->getName() => $class->getShortName()])
->mapWithKeys(fn (ReflectionClass $class): array => [$class->getName() => $class->getShortName()])
->toArray();
}
}
4 changes: 1 addition & 3 deletions src/Commands/Generator/Writers/ModuleWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ public function format(TypesCollection $collection): string
/** @var \ArrayIterator<int, \Spatie\TypeScriptTransformer\Structures\TransformedType> $iterator */
$iterator = $collection->getIterator();

$iterator->uasort(function (TransformedType $a, TransformedType $b) {
return strcmp(type($a->name)->asString(), type($b->name)->asString());
});
$iterator->uasort(fn(TransformedType $a, TransformedType $b): int => strcmp(type($a->name)->asString(), type($b->name)->asString()));

foreach ($iterator as $type) {
/** @var TransformedType $type */
Expand Down
18 changes: 8 additions & 10 deletions src/Commands/RESTPresenterSetupCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,13 @@ protected function publishingServiceProvider(): void
}

$callable = [ServiceProvider::class, 'addProviderToBootstrapFile'];
if (is_callable($callable)) {
call_user_func($callable, 'App\\Providers\\RESTPresenterServiceProvider', $providersPath);
}
call_user_func($callable, 'App\\Providers\\RESTPresenterServiceProvider', $providersPath);
}

protected function publishingDefaultResources(): void
{
collect($this->filesystem->directories(__DIR__ . '/../Resources'))
->map(fn ($resource) => Str::singular(basename($resource)))
->map(fn ($resource) => Str::singular(basename((string) $resource)))
->each(fn ($resource) => $this->call('rest-presenter:make-resource', [
'model' => 'App\\Models\\' . Str::singular($resource),
'name' => $resource,
Expand All @@ -122,11 +120,11 @@ protected function publishStarterKits(): void

/** @var \Illuminate\Support\Collection<string, string> $unpublishedStarterKits */
$unpublishedStarterKits = collect($this->filesystem->allFiles($starterKitsDirectory))
->map(fn ($file) => $file->getRelativePathname())
->filter(fn ($file) => ! $this->filesystem->exists($generatedKitsDirectory . '/' . $file))
->filter(fn ($file) => str_ends_with($file, 'ApiKitServiceProvider.php'))
->map(fn ($file) => str_replace('ApiKitServiceProvider.php', '', basename($file)))
->map(fn ($kit) => $kit)
->map(fn ($file): string => $file->getRelativePathname())
->filter(fn ($file): bool => ! $this->filesystem->exists($generatedKitsDirectory . '/' . $file))
->filter(fn ($file): bool => str_ends_with($file, 'ApiKitServiceProvider.php'))
->map(fn ($file): string|array => str_replace('ApiKitServiceProvider.php', '', basename($file)))
->map(fn ($kit): string => $kit)
->values();

if ($unpublishedStarterKits->isEmpty()) {
Expand All @@ -141,7 +139,7 @@ protected function publishStarterKits(): void
hint: 'You can re-run this command to install more starter kits later',
);

if (! $starterKits) {
if ($starterKits === []) {
return;
}

Expand Down
16 changes: 8 additions & 8 deletions src/Commands/XtendStarterKit.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ protected function extendControllers(string $starterKitsDirectory, string $kitPa
if ($this->kitCanExtendControllers($starterKitsDirectory, $kitPath)) {
collect($this->filesystem->allFiles($starterKitsDirectory . '/' . $kitPath . '/Http/Controllers'))
->filter(fn (SplFileInfo $file) => Str::endsWith($file->getFilename(), 'Controller.php'))
->each(function (SplFileInfo $file) use ($kitPath) {
->each(function (SplFileInfo $file) use ($kitPath): void {
$path = $file->getRelativePathName();
$kitNamespace = Str::of($kitPath)
->replace('/', '\\')->prepend('StarterKits\\')
Expand All @@ -84,7 +84,7 @@ protected function extendResources(string $starterKitsDirectory, string $kitPath
if ($this->kitCanExtendResources($starterKitsDirectory, $kitPath)) {
collect($this->filesystem->allFiles($starterKitsDirectory . '/' . $kitPath . '/Resources'))
->filter(fn (SplFileInfo $file) => Str::endsWith($file->getFilename(), 'ResourceController.php'))
->each(function (SplFileInfo $file) use ($starterKitsDirectory, $kitPath) {
->each(function (SplFileInfo $file) use ($starterKitsDirectory, $kitPath): void {
$path = $file->getRelativePath();
$kitNamespace = Str::of($kitPath)
->replace('/', '\\')->prepend('StarterKits\\')
Expand All @@ -93,7 +93,7 @@ protected function extendResources(string $starterKitsDirectory, string $kitPath

$resource = basename($path);
$resourcePath = $kitPath . '/Resources/' . $path;
$kitNamespace = $kitNamespace . (class_basename($resource) !== $path ? '\\' . $resource : '');
$kitNamespace .= class_basename($resource) !== $path ? '\\' . $resource : '';

$this->extendActions($starterKitsDirectory, $resourcePath, $kitNamespace);
$this->extendPresenters($starterKitsDirectory, $resourcePath, $kitNamespace);
Expand All @@ -116,7 +116,7 @@ protected function autoDiscoverResources(string $kitPath): void
default => false,
};

if (! $supportedKit) {
if ($supportedKit === false) {
$this->components->warn(__('No supported kit was found for ":kit_namespace"', ['kit_namespace' => $kitNamespace]));

return;
Expand All @@ -137,13 +137,13 @@ protected function autoDiscoverResources(string $kitPath): void
->before('\\Base')
->value();

collect($resources)->each(function ($resource, $resourceNamespace) use ($kitNamespace) {
collect($resources)->each(function (array $resource, string $resourceNamespace) use ($kitNamespace): void {
$resourceName = Str::of($resourceNamespace)
->classBasename()
->singular()
->value();

if ($resource['fields']) {
if ($resource['fields'] !== '' && $resource['fields'] !== '0') {
$this->call(
command: 'rest-presenter:make-presenter',
arguments: [
Expand Down Expand Up @@ -182,7 +182,7 @@ protected function extendActions(string $starterKitsDirectory, string $resourceP
}

collect($this->filesystem->directories($starterKitsDirectory . '/' . $resourcePath . '/Actions'))
->each(function ($path) use ($kitNamespace) {
->each(function ($path) use ($kitNamespace): void {
$action = basename($path);

$this->call('rest-presenter:make-action', [
Expand All @@ -202,7 +202,7 @@ protected function extendPresenters(string $starterKitsDirectory, string $resour
}

collect($this->filesystem->directories($starterKitsDirectory . '/' . $resourcePath . '/Presenters'))
->each(function ($path) use ($kitNamespace) {
->each(function ($path) use ($kitNamespace): void {
$presenter = basename($path);

$this->call('rest-presenter:make-presenter', [
Expand Down
23 changes: 9 additions & 14 deletions src/Concerns/InteractsWithDbSchema.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,38 +22,33 @@ protected function getAllTableNames(): Collection
*/
protected function getTableColumns(string $table, bool $withProperties = false): Collection
{
$columns = collect(! $withProperties
? Schema::getColumnListing($table)
: Schema::getColumns($table),
);

if (DB::connection()->getDriverName() === 'sqlite' && $withProperties) {
$columns = $this->replaceJsonColumnsSqliteWorkaround($table);
return $this->replaceJsonColumnsSqliteWorkaround($table);
}

return $columns;
return collect($withProperties
? Schema::getColumns($table)
: Schema::getColumnListing($table),
);
}

/**
* @param string $table
* @param array<string> $exclude
*
* @return \Illuminate\Support\Collection<string, string>
*/
protected function getTableColumnsForRelation(string $table, array $exclude = []): Collection
{
return $this->getTableColumns($table)->filter(
fn (string $column) => ! in_array($column, $exclude),
fn (string $column): bool => ! in_array($column, $exclude),
);
}

protected function findTableByName(string $table, bool $exactMatch = true): mixed
{
return $this->getAllTableNames()
->first(
fn ($tableName) => ! $exactMatch
? Str::endsWith(type($tableName)->asString(), $table)
: $tableName === $table,
fn ($tableName) => $exactMatch
? $tableName === $table
: Str::endsWith(type($tableName)->asString(), $table),
);
}

Expand Down
Loading

0 comments on commit e305e0c

Please sign in to comment.