Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(laravel): adds make:state-provider command #6706

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
->in(__DIR__)
->exclude([
'src/Core/Bridge/Symfony/Maker/Resources/skeleton',
'src/Laravel/Console/Maker/Resources/skeleton',
'src/Laravel/config',
'tests/Fixtures/app/var',
'docs/guides',
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## v4.0.4

### Features

* [4c0c6348b](https://github.com/api-platform/core/pull/6706/commits/4c0c6348bcbef5e3b942d33b2e0ca318b5cb04f5) feat(laravel): adds make:state-provider command

## v4.0.3

### Bug fixes
Expand Down
5 changes: 4 additions & 1 deletion src/Laravel/ApiPlatformProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -1040,7 +1040,10 @@ function (Application $app) {
});

if ($this->app->runningInConsole()) {
$this->commands([Console\InstallCommand::class]);
$this->commands([
Console\InstallCommand::class,
Console\Maker\MakeStateProviderCommand::class,
]);
}
}

Expand Down
81 changes: 81 additions & 0 deletions src/Laravel/Console/Maker/MakeStateProviderCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Laravel\Console\Maker;

use ApiPlatform\Laravel\Console\Maker\Utils\AppServiceProviderTagger;
use ApiPlatform\Laravel\Console\Maker\Utils\StateDirectoryManager;
use ApiPlatform\Laravel\Console\Maker\Utils\StateProviderGenerator;
use ApiPlatform\Laravel\Console\Maker\Utils\SuccessMessageTrait;
use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Filesystem\Filesystem;

final class MakeStateProviderCommand extends Command
{
use SuccessMessageTrait;

protected $signature = 'make:state-provider';

protected $description = 'Creates an API Platform state provider';

public function __construct(
private readonly Filesystem $filesystem,
private readonly StateProviderGenerator $stateProviderGenerator,
private readonly AppServiceProviderTagger $appServiceProviderTagger,
private readonly StateDirectoryManager $stateDirectoryManager,
) {
parent::__construct();
}

/**
* @throws FileNotFoundException
*/
public function handle(): int
{
$providerName = $this->askForProviderName();
$directoryPath = $this->stateDirectoryManager->ensureStateDirectoryExists();

$filePath = $this->stateProviderGenerator->getFilePath($directoryPath, $providerName);
if ($this->stateProviderGenerator->isFileExists($filePath)) {
$this->error(\sprintf('[ERROR] The file "%s" can\'t be generated because it already exists.', $filePath));

return self::FAILURE;
}

$this->stateProviderGenerator->generate($filePath, $providerName);
if (!$this->filesystem->exists($filePath)) {
$this->error(\sprintf('[ERROR] The file "%s" could not be created.', $filePath));

return self::FAILURE;
}

$this->appServiceProviderTagger->addTagToServiceProvider($providerName);

$this->writeSuccessMessage($filePath);

return self::SUCCESS;
}

private function askForProviderName(): string
{
do {
$providerName = $this->ask('Choose a class name for your state provider (e.g. <fg=yellow>AwesomeStateProvider</>)');
if (empty($providerName)) {
$this->error('[ERROR] This value cannot be blank.');
}
} while (empty($providerName));

return $providerName;
}
}
16 changes: 16 additions & 0 deletions src/Laravel/Console/Maker/Resources/skeleton/StateProvider.tpl.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace {{ namespace }};

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;

final class {{ class_name }} implements ProviderInterface
{
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
// Retrieve the state from somewhere
}
}
84 changes: 84 additions & 0 deletions src/Laravel/Console/Maker/Utils/AppServiceProviderTagger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Laravel\Console\Maker\Utils;

use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Filesystem\Filesystem;

final readonly class AppServiceProviderTagger
{
/** @var string */
private const SERVICE_PROVIDER_PATH = 'Providers/AppServiceProvider.php';

/** @var string */
private const ITEM_PROVIDER_USE_STATEMENT = 'use ApiPlatform\Laravel\Eloquent\State\ItemProvider;';

public function __construct(private Filesystem $filesystem)
{
}

/**
* @throws FileNotFoundException
*/
public function addTagToServiceProvider(string $providerName): void
{
$serviceProviderPath = app_path(self::SERVICE_PROVIDER_PATH);

$this->ensureServiceProviderExists($serviceProviderPath);

$serviceProviderContent = $this->filesystem->get($serviceProviderPath);

$this->addUseStatement($serviceProviderContent, self::ITEM_PROVIDER_USE_STATEMENT);
$this->addUseStatement($serviceProviderContent, $this->getProviderNamespace($providerName));
$this->addTag($serviceProviderContent, $providerName, $serviceProviderPath);
}

private function ensureServiceProviderExists(string $path): void
{
if (!$this->filesystem->exists($path)) {
throw new \RuntimeException('The AppServiceProvider is missing!');
}
}

private function addUseStatement(string &$content, string $useStatement): void
{
if (!str_contains($content, $useStatement)) {
$content = preg_replace(
'/^(namespace\s[^;]+;\s*)(\n)/m',
"$1\n$useStatement$2",
$content,
1
);
}
}

private function addTag(string &$content, string $providerName, string $serviceProviderPath): void
{
$tagStatement = \sprintf("\n\n\t\t\$this->app->tag(%s::class, ItemProvider::class);", $providerName);
if (!str_contains($content, $tagStatement)) {
$content = preg_replace(
'/(public function register\(\)[^{]*{)(.*?)(\s*}\s*})/s',
"$1$2$tagStatement$3",
$content
);

$this->filesystem->put($serviceProviderPath, $content);
}
}

public function getProviderNamespace(string $providerName): string
{
return \sprintf('use App\\State\\%s;', $providerName);
}
}
31 changes: 31 additions & 0 deletions src/Laravel/Console/Maker/Utils/StateDirectoryManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Laravel\Console\Maker\Utils;

use Illuminate\Filesystem\Filesystem;

final readonly class StateDirectoryManager
{
public function __construct(private Filesystem $filesystem)
{
}

public function ensureStateDirectoryExists(): string
{
$directoryPath = base_path('src/State/');
$this->filesystem->ensureDirectoryExists($directoryPath);

return $directoryPath;
}
}
65 changes: 65 additions & 0 deletions src/Laravel/Console/Maker/Utils/StateProviderGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Laravel\Console\Maker\Utils;

use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Filesystem\Filesystem;

final readonly class StateProviderGenerator
{
public function __construct(private Filesystem $filesystem)
{
}

public function getFilePath(string $directoryPath, string $providerName): string
{
return $directoryPath.$providerName.'.php';
}

public function isFileExists(string $filePath): bool
{
return $this->filesystem->exists($filePath);
}

/**
* @throws FileNotFoundException
*/
public function generate(string $pathLink, string $providerName): void
{
$namespace = 'App\\State';
$template = $this->loadTemplate();

$content = $this->replacePlaceholders($template, [
'{{ namespace }}' => $namespace,
'{{ class_name }}' => $providerName,
]);

$this->filesystem->put($pathLink, $content);
}

/**
* @throws FileNotFoundException
*/
private function loadTemplate(): string
{
$templatePath = \dirname(__DIR__).'/Resources/skeleton/StateProvider.tpl.php';

return $this->filesystem->get($templatePath);
}

private function replacePlaceholders(string $template, array $variables): string
{
return strtr($template, $variables);
}
}
29 changes: 29 additions & 0 deletions src/Laravel/Console/Maker/Utils/SuccessMessageTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Laravel\Console\Maker\Utils;

trait SuccessMessageTrait
{
private function writeSuccessMessage(string $filePath): void
{
$this->newLine();
$this->line(' <bg=green;fg=white> </>');
$this->line(' <bg=green;fg=white> Success! </>');
$this->line(' <bg=green;fg=white> </>');
$this->newLine();
$this->line('<fg=blue>created</>: <fg=white;options=underscore>'.$filePath.'</>');
$this->newLine();
$this->line('Next: Open your new state provider class and start customizing it.');
}
}
Loading
Loading