From a9e244e1dabbb2695bd9f75b09f9e98403c583ce Mon Sep 17 00:00:00 2001 From: Rustam Date: Mon, 10 Oct 2022 22:54:00 +0500 Subject: [PATCH 1/8] Remove `yiisoft/view` dependency & minor refactoring --- composer.json | 3 +- config/params.php | 5 +- config/routes.php | 40 ++++ src/CodeFile.php | 21 +- src/Component/DiffRendererHtmlInline.php | 2 +- src/Controller/DefaultController.php | 218 ++++++------------ src/Generator/AbstractGenerator.php | 40 ++-- .../Controller/default/controller.php | 12 +- src/Generator/Controller/default/view.php | 4 +- src/Generator/Controller/form.php | 12 - src/GeneratorInterface.php | 2 + src/Gii.php | 5 +- src/GiiInterface.php | 7 +- src/Request/GeneratorRequest.php | 29 +++ 14 files changed, 202 insertions(+), 198 deletions(-) delete mode 100644 src/Generator/Controller/form.php create mode 100644 src/Request/GeneratorRequest.php diff --git a/composer.json b/composer.json index 15dfd8f73..ddafe7f94 100644 --- a/composer.json +++ b/composer.json @@ -23,11 +23,12 @@ "phpspec/php-diff": "^1.1.0", "yiisoft/aliases": "^2.0", "yiisoft/arrays": "^2.1", + "yiisoft/data-response": "^1.0", "yiisoft/http": "^1.2", "yiisoft/json": "^1.0", + "yiisoft/request-model": "dev-master", "yiisoft/strings": "^2.1", "yiisoft/validator": "^3.0@dev", - "yiisoft/view": "^6.0", "yiisoft/yii-console": "^1.3" }, "require-dev": { diff --git a/config/params.php b/config/params.php index 4384ebc3d..3749aaff0 100644 --- a/config/params.php +++ b/config/params.php @@ -10,10 +10,9 @@ 'gii/controller' => ControllerCommand::class, ], ], - 'yiisoft/aliases' => [ - '@yii-gii' => dirname(__DIR__), - ], 'yiisoft/yii-gii' => [ + 'enabled' => true, + 'allowedIPs' => ['127.0.0.1', '::1'], 'generators' => [ 'controller' => \Yiisoft\Yii\Gii\Generator\Controller\Generator::class, ], diff --git a/config/routes.php b/config/routes.php index 43548eb4c..ed550b189 100644 --- a/config/routes.php +++ b/config/routes.php @@ -6,5 +6,45 @@ * @var array $params */ +use Psr\Http\Message\ResponseFactoryInterface; +use Yiisoft\DataResponse\Middleware\FormatDataResponseAsJson; +use Yiisoft\Router\Group; +use Yiisoft\Router\Route; +use Yiisoft\Validator\ValidatorInterface; +use Yiisoft\Yii\Debug\Api\Middleware\ResponseDataWrapper; +use Yiisoft\Yii\Gii\Controller\DefaultController; +use Yiisoft\Yii\Middleware\IpFilter; + +if (!(bool)($params['yiisoft/yii-enabled']['enabled'] ?? false)) { + return []; +} + return [ + Group::create('/gii/api') + ->middleware( + static function (ResponseFactoryInterface $responseFactory, ValidatorInterface $validator) use ($params) { + return new IpFilter( + validator: $validator, + responseFactory: $responseFactory, + ipRanges: $params['yiisoft/yii-gii']['allowedIPs'] + ); + } + ) + ->middleware(FormatDataResponseAsJson::class) + ->middleware(ResponseDataWrapper::class) + ->namePrefix('gii/api/') + ->routes( + Route::get('/{generator}') + ->action([DefaultController::class, 'get']) + ->name('generator'), + Route::post('/{generator}/preview') + ->action([DefaultController::class, 'preview']) + ->name('preview'), + Route::post('/{generator}/generate') + ->action([DefaultController::class, 'generate']) + ->name('generate'), + Route::post('/{generator}/diff') + ->action([DefaultController::class, 'diff']) + ->name('diff') + ), ]; diff --git a/src/CodeFile.php b/src/CodeFile.php index def41d0cd..5ba613b2d 100644 --- a/src/CodeFile.php +++ b/src/CodeFile.php @@ -34,6 +34,12 @@ final class CodeFile * The new code file and the existing one are identical. */ public const OP_SKIP = 2; + public const OPERATIONS = [ + self::OP_CREATE => 'Create', + self::OP_OVERWRITE => 'Overwrite', + self::OP_SKIP => 'Skip' + ]; + /** * @var string an ID that uniquely identifies this code file. */ @@ -140,7 +146,7 @@ public function getType(): string /** * Returns preview or false if it cannot be rendered */ - public function preview(): bool|string + public function preview(): false|string { if (($pos = strrpos($this->path, '.')) !== false) { $type = substr($this->path, $pos + 1); @@ -153,7 +159,12 @@ public function preview(): bool|string } if (!in_array($type, ['jpg', 'gif', 'png', 'exe'])) { - return nl2br(Html::encode($this->content)); + $content = htmlspecialchars( + $this->content, + ENT_NOQUOTES | ENT_SUBSTITUTE | ENT_HTML5, + 'UTF-8' + ); + return nl2br($content); } return false; @@ -162,7 +173,7 @@ public function preview(): bool|string /** * Returns diff or false if it cannot be calculated */ - public function diff(): bool|string + public function diff(): false|string { $type = strtolower($this->getType()); if (in_array($type, ['jpg', 'gif', 'png', 'exe'])) { @@ -195,9 +206,7 @@ private function renderDiff(mixed $lines1, mixed $lines2): string } $renderer = new DiffRendererHtmlInline(); - $diff = new Diff($lines1, $lines2); - - return $diff->render($renderer); + return (new Diff($lines1, $lines2))->render($renderer); } public function getId(): string diff --git a/src/Component/DiffRendererHtmlInline.php b/src/Component/DiffRendererHtmlInline.php index 074e86d06..d32218e9c 100644 --- a/src/Component/DiffRendererHtmlInline.php +++ b/src/Component/DiffRendererHtmlInline.php @@ -11,7 +11,7 @@ * * @psalm-suppress PropertyNotSetInConstructor */ -class DiffRendererHtmlInline extends Diff_Renderer_Html_Array +final class DiffRendererHtmlInline extends Diff_Renderer_Html_Array { /** * Render a and return diff with changes between the two sequences diff --git a/src/Controller/DefaultController.php b/src/Controller/DefaultController.php index 708f0da9b..9a0de86bd 100644 --- a/src/Controller/DefaultController.php +++ b/src/Controller/DefaultController.php @@ -4,180 +4,104 @@ namespace Yiisoft\Yii\Gii\Controller; -use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\ServerRequestInterface; -use Yiisoft\Aliases\Aliases; +use Yiisoft\DataResponse\DataResponseFactoryInterface; use Yiisoft\Http\Status; -use Yiisoft\View\ViewContextInterface; -use Yiisoft\View\WebView; +use Yiisoft\RequestModel\Attribute\Query; +use Yiisoft\Yii\Gii\CodeFile; use Yiisoft\Yii\Gii\Generator\AbstractGenerator; -use Yiisoft\Yii\Gii\GeneratorInterface; -use Yiisoft\Yii\Gii\GiiInterface; +use Yiisoft\Yii\Gii\Request\GeneratorRequest; -class DefaultController implements ViewContextInterface +final class DefaultController { - private string $layout; - - public function __construct( - private ResponseFactoryInterface $responseFactory, - private GiiInterface $gii, - private WebView $view, - private Aliases $aliases, - ) { - $this->layout = $aliases->get('@yii-gii/views') . '/layout/generator'; - } - - public function index(): string + public function __construct(private DataResponseFactoryInterface $responseFactory) { - $this->layout = 'main'; - - return $this->render('index'); } - public function view(ServerRequestInterface $request): string + public function get(GeneratorRequest $request): ResponseInterface { - $id = $request->getAttribute('id'); /** @var AbstractGenerator $generator */ - $generator = $this->loadGenerator($id, $request); - $params = ['generator' => $generator, 'id' => $id]; - - $preview = $request->getAttribute('preview'); - $generate = $request->getAttribute('generate'); - $answers = $request->getAttribute('answers'); + $generator = $request->getGenerator(); + $params = [ + 'name' => $generator->getName(), + 'description' => $generator->getDescription(), + 'template' => $generator->getTemplate(), + 'templatePath' => $generator->getTemplatePath(), + 'templates' => $generator->getTemplates(), + 'directory' => $generator->getDirectory(), + ]; + + return $this->responseFactory->createResponse($params); + } - if ($preview !== null || $generate !== null) { - if ($generator->validate()->isValid()) { - $generator->saveStickyAttributes(); - $files = $generator->generate(); - if ($generate !== null && !empty($answers)) { - $results = []; - $params['hasError'] = !$generator->save($files, (array)$answers, $results); - $params['results'] = $results; - } else { - $params['files'] = $files; - $params['answers'] = $answers; - } - } + public function generate(GeneratorRequest $request): ResponseInterface + { + $generator = $request->getGenerator(); + $answers = $request->getAnswers(); + $validationResult = $generator->validate(); + if ($validationResult->isValid()) { + $generator->saveStickyAttributes(); + $files = $generator->generate(); + $params = []; + $results = []; + $params['hasError'] = !$generator->save($files, (array)$answers, $results); + $params['results'] = $results; + return $this->responseFactory->createResponse($params); } - return $this->render('view', $params); + return $this->responseFactory->createResponse( + ['errors' => $validationResult->getErrorMessagesIndexedByAttribute()], + Status::UNPROCESSABLE_ENTITY + ); } - public function preview(ServerRequestInterface $request): ResponseInterface|string + public function preview(GeneratorRequest $request, #[Query('file')] ?string $file = null): ResponseInterface { - $id = $request->getAttribute('id'); - $file = $request->getAttribute('file'); - $generator = $this->loadGenerator($id, $request); - if ($generator->validate()->isValid()) { - foreach ($generator->generate() as $f) { - if ($f->getId() === $file) { - $content = $f->preview(); - if ($content !== false) { - return '
' . $content . '
'; + $generator = $request->getGenerator(); + $validationResult = $generator->validate(); + if ($validationResult->isValid()) { + $files = $generator->generate(); + if ($file !== null) { + foreach ($files as $generatedFile) { + if ($generatedFile->getId() === $file) { + $content = $generatedFile->preview(); + if ($content !== false) { + return $this->responseFactory->createResponse(['content' => $content]); + } + return $this->responseFactory->createResponse( + ['content' => 'Preview is not available for this file type.'] + ); } - - return '
Preview is not available for this file type.
'; } + return $this->responseFactory->createResponse(['message' => "Code file not found: $file"], + Status::UNPROCESSABLE_ENTITY); } + return $this->responseFactory->createResponse(['files' => $files, 'operations' => CodeFile::OPERATIONS]); } - $response = $this->responseFactory->createResponse(Status::UNPROCESSABLE_ENTITY); - $response->getBody()->write("Code file not found: $file"); - return $response; + return $this->responseFactory->createResponse( + ['errors' => $validationResult->getErrorMessagesIndexedByAttribute()], + Status::UNPROCESSABLE_ENTITY + ); } - public function diff(ServerRequestInterface $request): ResponseInterface|string + public function diff(GeneratorRequest $request, #[Query('file')] string $file): ResponseInterface { - $id = $request->getAttribute('id'); - $file = $request->getAttribute('file'); - $generator = $this->loadGenerator($id, $request); - if ($generator->validate()->isValid()) { - foreach ($generator->generate() as $f) { - if ($f->getId() === $file) { - return $this->render( - 'diff', - [ - 'diff' => $f->diff(), - ] - ); + $generator = $request->getGenerator(); + $validationResult = $generator->validate(); + if ($validationResult->isValid()) { + foreach ($generator->generate() as $generatedFile) { + if ($generatedFile->getId() === $file) { + return $this->responseFactory->createResponse(['diff' => $generatedFile->diff()]); } } + return $this->responseFactory->createResponse(['message' => "Code file not found: $file"], + Status::UNPROCESSABLE_ENTITY); } - $response = $this->responseFactory->createResponse(Status::UNPROCESSABLE_ENTITY); - $response->getBody()->write("Code file not found: $file"); - return $response; - } - - /** - * Runs an action defined in the generator. - * Given an action named "xyz", the method "actionXyz()" in the generator will be called. - * If the method does not exist, a 400 HTTP exception will be thrown. - * - * @return mixed the result of the action. - */ - public function action(ServerRequestInterface $request) - { - $id = $request->getAttribute('id'); - $action = $request->getAttribute('action'); - /** @var AbstractGenerator $generator */ - $generator = $this->loadGenerator($id, $request); - if (method_exists($generator, $action)) { - return $generator->$action(); - } - - $response = $this->responseFactory->createResponse(Status::UNPROCESSABLE_ENTITY); - $response->getBody()->write("Unknown generator action: {$action}"); - return $response; - } - - protected function loadGenerator(string $id, ServerRequestInterface $request): GeneratorInterface - { - /** @var AbstractGenerator $generator */ - $generator = $this->gii->getGenerator($id); - $generator->loadStickyAttributes(); - $generator->load((array)$request->getParsedBody()); - - return $generator; - } - - private function render(string $view, array $parameters = []): string - { - $content = $this->view->withContext($this)->render($view, $parameters); - return $this->renderContent($content); - } - - private function renderContent(string $content): string - { - $layout = $this->findLayoutFile($this->layout); - if ($layout !== null) { - return $this->view->withContext($this)->renderFile( - $layout, - [ - 'content' => $content, - ] - ); - } - - return $content; - } - - public function getViewPath(): string - { - return $this->aliases->get('@yii-gii/views') . '/default'; - } - - private function findLayoutFile(?string $file): ?string - { - if ($file === null) { - return null; - } - - if (pathinfo($file, PATHINFO_EXTENSION) !== '') { - return $file; - } - - return $file . '.' . $this->view->getDefaultExtension(); + return $this->responseFactory->createResponse( + ['errors' => $validationResult->getErrorMessagesIndexedByAttribute()], + Status::UNPROCESSABLE_ENTITY + ); } } diff --git a/src/Generator/AbstractGenerator.php b/src/Generator/AbstractGenerator.php index 90ea6d1ab..ad0a40203 100644 --- a/src/Generator/AbstractGenerator.php +++ b/src/Generator/AbstractGenerator.php @@ -20,9 +20,6 @@ use Yiisoft\Validator\RuleInterface; use Yiisoft\Validator\ValidationContext; use Yiisoft\Validator\ValidatorInterface; -use Yiisoft\View\Exception\ViewNotFoundException; -use Yiisoft\View\View; -use Yiisoft\View\ViewContextInterface; use Yiisoft\Yii\Gii\CodeFile; use Yiisoft\Yii\Gii\Exception\InvalidConfigException; use Yiisoft\Yii\Gii\GeneratorInterface; @@ -41,7 +38,7 @@ * - {@see GeneratorInterface::generate()}: generates the code based on the current user input and the specified code * template files. This is the place where main code generation code resides. */ -abstract class AbstractGenerator implements GeneratorInterface, DataSetInterface, ViewContextInterface +abstract class AbstractGenerator implements GeneratorInterface, DataSetInterface { private array $errors = []; /** @@ -58,7 +55,6 @@ abstract class AbstractGenerator implements GeneratorInterface, DataSetInterface public function __construct( protected Aliases $aliases, - protected View $view, protected ValidatorInterface $validator, ) { } @@ -212,7 +208,7 @@ public function loadStickyAttributes(): void $stickyAttributes = $this->stickyAttributes(); $path = $this->getStickyDataFile(); if (is_file($path)) { - $result = Json::decode(file_get_contents($path), true); + $result = Json::decode(file_get_contents($path)); if (is_array($result)) { foreach ($stickyAttributes as $name) { $method = 'set' . $name; @@ -304,11 +300,6 @@ public function save(array $files, array $answers, array &$results): bool return !$hasError; } - public function getViewPath(): string - { - return $this->aliases->get($this->getTemplatePath()); - } - /** * @throws ReflectionException * @throws InvalidConfigException @@ -337,15 +328,34 @@ public function getTemplatePath(): string * @param array $params list of parameters to be passed to the template file. * * @throws Throwable - * @throws ViewNotFoundException * * @return string the generated code */ public function render(string $template, array $params = []): string { - $params['generator'] = $this; - - return $this->view->withContext($this)->render($template, $params); + $file = sprintf("%s/%s.php", $this->aliases->get($this->getTemplatePath()), $template); + + $renderer = function (): void { + extract(array: func_get_arg(1), flags: EXTR_OVERWRITE); + /** @psalm-suppress UnresolvableInclude */ + require func_get_arg(0); + }; + + $obInitialLevel = ob_get_level(); + ob_start(); + ob_implicit_flush(false); + try { + /** @psalm-suppress PossiblyInvalidFunctionCall */ + $renderer->bindTo($this)($file, $params); + return ob_get_clean(); + } catch (Throwable $e) { + while (ob_get_level() > $obInitialLevel) { + if (!@ob_end_clean()) { + ob_clean(); + } + } + throw $e; + } } /** diff --git a/src/Generator/Controller/default/controller.php b/src/Generator/Controller/default/controller.php index 7e9420bd3..b0c1ab3f2 100644 --- a/src/Generator/Controller/default/controller.php +++ b/src/Generator/Controller/default/controller.php @@ -6,12 +6,12 @@ use Yiisoft\Strings\StringHelper; -/* @var $generator Yiisoft\Yii\Gii\Generator\Controller\Generator */ +/* @var $this Yiisoft\Yii\Gii\Generator\Controller\Generator */ $classDefinitionParts = []; -$classDefinitionParts[] = StringHelper::baseName($generator->getControllerClass()); -if ($generator->getBaseClass() !== null) { - $classDefinitionParts[] = 'extends \\' . trim($generator->getBaseClass(), '\\'); +$classDefinitionParts[] = StringHelper::baseName($this->getControllerClass()); +if ($this->getBaseClass() !== null) { + $classDefinitionParts[] = 'extends \\' . trim($this->getBaseClass(), '\\'); } $classDefinition = implode(' ', $classDefinitionParts) . PHP_EOL; @@ -21,7 +21,7 @@ declare(strict_types=1); -namespace getControllerNamespace() ?>; +namespace getControllerNamespace() ?>; use Yiisoft\Yii\View\ViewRenderer; @@ -31,7 +31,7 @@ public function __construct(private ViewRenderer $viewRenderer) { $this->viewRenderer = $viewRenderer->withController($this); } -getActionIDs() as $action) : ?> +getActionIDs() as $action) : ?> public function () { diff --git a/src/Generator/Controller/default/view.php b/src/Generator/Controller/default/view.php index e863dc7ee..6703d291a 100644 --- a/src/Generator/Controller/default/view.php +++ b/src/Generator/Controller/default/view.php @@ -4,7 +4,7 @@ * This is the template for generating an action view file. */ -/* @var $generator Yiisoft\Yii\Gii\Generator\Controller\Generator */ +/* @var $this Yiisoft\Yii\Gii\Generator\Controller\Generator */ /* @var $action string the action ID */ echo "' ?> -

getControllerID() . '/' . $action ?>

+

getControllerID() . '/' . $action ?>

You may change the content of this page by modifying diff --git a/src/Generator/Controller/form.php b/src/Generator/Controller/form.php deleted file mode 100644 index 62b79d636..000000000 --- a/src/Generator/Controller/form.php +++ /dev/null @@ -1,12 +0,0 @@ -field($generator, 'controllerClass'); -echo $form->field($generator, 'actions'); -echo $form->field($generator, 'viewsPath'); -echo $form->field($generator, 'baseClass'); diff --git a/src/GeneratorInterface.php b/src/GeneratorInterface.php index 7ee3d9e49..f5f569348 100644 --- a/src/GeneratorInterface.php +++ b/src/GeneratorInterface.php @@ -18,6 +18,8 @@ public function getName(): string; */ public function getDescription(): string; + public function getTemplatePath(): string; + /** * Generates the code based on the current user input and the specified code template files. * This is the main method that child classes should implement. diff --git a/src/Gii.php b/src/Gii.php index b20391f0f..522b44998 100644 --- a/src/Gii.php +++ b/src/Gii.php @@ -17,14 +17,11 @@ public function __construct(private array $generators, private ContainerInterfac { } - public function addGenerator(string $name, $generator): void + public function addGenerator(string $name, mixed $generator): void { $this->generators[$name] = $generator; } - /** - * @throws GeneratorNotFoundException - */ public function getGenerator(string $name): GeneratorInterface { if (!isset($this->generators[$name])) { diff --git a/src/GiiInterface.php b/src/GiiInterface.php index 8992a8aaa..409449fe3 100644 --- a/src/GiiInterface.php +++ b/src/GiiInterface.php @@ -4,13 +4,18 @@ namespace Yiisoft\Yii\Gii; +use Yiisoft\Yii\Gii\Exception\GeneratorNotFoundException; + interface GiiInterface { /** * @param string $name * @param mixed $generator */ - public function addGenerator(string $name, $generator): void; + public function addGenerator(string $name, mixed $generator): void; + /** + * @throws GeneratorNotFoundException + */ public function getGenerator(string $name): GeneratorInterface; } diff --git a/src/Request/GeneratorRequest.php b/src/Request/GeneratorRequest.php new file mode 100644 index 000000000..f02f719a5 --- /dev/null +++ b/src/Request/GeneratorRequest.php @@ -0,0 +1,29 @@ +gii->getGenerator($this->getAttributeValue('router.generator')); + + $generator->loadStickyAttributes(); + $generator->load((array)$this->getAttributeValue('body')); + + return $generator; + } + + public function getAnswers(): ?array + { + return $this->getAttributeValue('body.answers'); + } +} From a2dd9de5308ec841679791587009e8ad29f365ea Mon Sep 17 00:00:00 2001 From: StyleCI Bot Date: Mon, 10 Oct 2022 17:54:23 +0000 Subject: [PATCH 2/8] Apply fixes from StyleCI --- src/CodeFile.php | 3 +-- src/Controller/DefaultController.php | 12 ++++++++---- src/Generator/AbstractGenerator.php | 2 +- src/Request/GeneratorRequest.php | 2 ++ 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/CodeFile.php b/src/CodeFile.php index 5ba613b2d..b9eb1f1ea 100644 --- a/src/CodeFile.php +++ b/src/CodeFile.php @@ -6,7 +6,6 @@ use Diff; use RuntimeException; -use Yiisoft\Html\Html; use Yiisoft\Yii\Gii\Component\DiffRendererHtmlInline; /** @@ -37,7 +36,7 @@ final class CodeFile public const OPERATIONS = [ self::OP_CREATE => 'Create', self::OP_OVERWRITE => 'Overwrite', - self::OP_SKIP => 'Skip' + self::OP_SKIP => 'Skip', ]; /** diff --git a/src/Controller/DefaultController.php b/src/Controller/DefaultController.php index 9a0de86bd..a8fd5a854 100644 --- a/src/Controller/DefaultController.php +++ b/src/Controller/DefaultController.php @@ -73,8 +73,10 @@ public function preview(GeneratorRequest $request, #[Query('file')] ?string $fil ); } } - return $this->responseFactory->createResponse(['message' => "Code file not found: $file"], - Status::UNPROCESSABLE_ENTITY); + return $this->responseFactory->createResponse( + ['message' => "Code file not found: $file"], + Status::UNPROCESSABLE_ENTITY + ); } return $this->responseFactory->createResponse(['files' => $files, 'operations' => CodeFile::OPERATIONS]); } @@ -95,8 +97,10 @@ public function diff(GeneratorRequest $request, #[Query('file')] string $file): return $this->responseFactory->createResponse(['diff' => $generatedFile->diff()]); } } - return $this->responseFactory->createResponse(['message' => "Code file not found: $file"], - Status::UNPROCESSABLE_ENTITY); + return $this->responseFactory->createResponse( + ['message' => "Code file not found: $file"], + Status::UNPROCESSABLE_ENTITY + ); } return $this->responseFactory->createResponse( diff --git a/src/Generator/AbstractGenerator.php b/src/Generator/AbstractGenerator.php index ad0a40203..546c477bf 100644 --- a/src/Generator/AbstractGenerator.php +++ b/src/Generator/AbstractGenerator.php @@ -333,7 +333,7 @@ public function getTemplatePath(): string */ public function render(string $template, array $params = []): string { - $file = sprintf("%s/%s.php", $this->aliases->get($this->getTemplatePath()), $template); + $file = sprintf('%s/%s.php', $this->aliases->get($this->getTemplatePath()), $template); $renderer = function (): void { extract(array: func_get_arg(1), flags: EXTR_OVERWRITE); diff --git a/src/Request/GeneratorRequest.php b/src/Request/GeneratorRequest.php index f02f719a5..4d099b6bd 100644 --- a/src/Request/GeneratorRequest.php +++ b/src/Request/GeneratorRequest.php @@ -1,5 +1,7 @@ Date: Mon, 10 Oct 2022 22:57:13 +0500 Subject: [PATCH 3/8] Fix psalm config --- psalm.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/psalm.xml b/psalm.xml index c76ebf5b8..81eb3520c 100644 --- a/psalm.xml +++ b/psalm.xml @@ -10,7 +10,6 @@ - From d8cc7238cccb62f4134ba7938944733b62030411 Mon Sep 17 00:00:00 2001 From: Rustam Date: Tue, 11 Oct 2022 16:49:12 +0500 Subject: [PATCH 4/8] Fix typo in routes config --- config/routes.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/routes.php b/config/routes.php index ed550b189..40bf34674 100644 --- a/config/routes.php +++ b/config/routes.php @@ -15,7 +15,7 @@ use Yiisoft\Yii\Gii\Controller\DefaultController; use Yiisoft\Yii\Middleware\IpFilter; -if (!(bool)($params['yiisoft/yii-enabled']['enabled'] ?? false)) { +if (!(bool)($params['yiisoft/yii-gii']['enabled'] ?? false)) { return []; } From 35d51ea0e0e0c48f088c0877d4943c460fa0ff12 Mon Sep 17 00:00:00 2001 From: Rustam Date: Thu, 13 Oct 2022 10:20:57 +0500 Subject: [PATCH 5/8] Fix psalm issues --- src/Controller/DefaultController.php | 3 +++ src/Generator/AbstractGenerator.php | 2 +- src/Request/GeneratorRequest.php | 2 ++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Controller/DefaultController.php b/src/Controller/DefaultController.php index a8fd5a854..f0e9312c0 100644 --- a/src/Controller/DefaultController.php +++ b/src/Controller/DefaultController.php @@ -36,6 +36,7 @@ public function get(GeneratorRequest $request): ResponseInterface public function generate(GeneratorRequest $request): ResponseInterface { + /** @var AbstractGenerator $generator */ $generator = $request->getGenerator(); $answers = $request->getAnswers(); $validationResult = $generator->validate(); @@ -57,6 +58,7 @@ public function generate(GeneratorRequest $request): ResponseInterface public function preview(GeneratorRequest $request, #[Query('file')] ?string $file = null): ResponseInterface { + /** @var AbstractGenerator $generator */ $generator = $request->getGenerator(); $validationResult = $generator->validate(); if ($validationResult->isValid()) { @@ -89,6 +91,7 @@ public function preview(GeneratorRequest $request, #[Query('file')] ?string $fil public function diff(GeneratorRequest $request, #[Query('file')] string $file): ResponseInterface { + /** @var AbstractGenerator $generator */ $generator = $request->getGenerator(); $validationResult = $generator->validate(); if ($validationResult->isValid()) { diff --git a/src/Generator/AbstractGenerator.php b/src/Generator/AbstractGenerator.php index 546c477bf..82df21f07 100644 --- a/src/Generator/AbstractGenerator.php +++ b/src/Generator/AbstractGenerator.php @@ -336,7 +336,7 @@ public function render(string $template, array $params = []): string $file = sprintf('%s/%s.php', $this->aliases->get($this->getTemplatePath()), $template); $renderer = function (): void { - extract(array: func_get_arg(1), flags: EXTR_OVERWRITE); + extract(func_get_arg(1)); /** @psalm-suppress UnresolvableInclude */ require func_get_arg(0); }; diff --git a/src/Request/GeneratorRequest.php b/src/Request/GeneratorRequest.php index 4d099b6bd..c991b14ef 100644 --- a/src/Request/GeneratorRequest.php +++ b/src/Request/GeneratorRequest.php @@ -5,6 +5,7 @@ namespace Yiisoft\Yii\Gii\Request; use Yiisoft\RequestModel\RequestModel; +use Yiisoft\Yii\Gii\Generator\AbstractGenerator; use Yiisoft\Yii\Gii\GeneratorInterface; use Yiisoft\Yii\Gii\GiiInterface; @@ -16,6 +17,7 @@ public function __construct(private GiiInterface $gii) public function getGenerator(): GeneratorInterface { + /** @var AbstractGenerator $generator */ $generator = $this->gii->getGenerator($this->getAttributeValue('router.generator')); $generator->loadStickyAttributes(); From 3a3343a38422f9a4f4662c22592ef10974ad796d Mon Sep 17 00:00:00 2001 From: Rustam Date: Thu, 13 Oct 2022 10:35:07 +0500 Subject: [PATCH 6/8] Fixes --- composer.json | 4 +++- config/routes.php | 2 -- src/CodeFile.php | 7 +++++-- src/Controller/DefaultController.php | 2 +- src/Generator/AbstractGenerator.php | 16 ---------------- 5 files changed, 9 insertions(+), 22 deletions(-) diff --git a/composer.json b/composer.json index ddafe7f94..fb2685a1c 100644 --- a/composer.json +++ b/composer.json @@ -27,9 +27,11 @@ "yiisoft/http": "^1.2", "yiisoft/json": "^1.0", "yiisoft/request-model": "dev-master", + "yiisoft/router": "^1.2", "yiisoft/strings": "^2.1", "yiisoft/validator": "^3.0@dev", - "yiisoft/yii-console": "^1.3" + "yiisoft/yii-console": "^1.3", + "yiisoft/yii-middleware": "dev-master" }, "require-dev": { "nyholm/psr7": "^1.5", diff --git a/config/routes.php b/config/routes.php index 40bf34674..9ac0faf88 100644 --- a/config/routes.php +++ b/config/routes.php @@ -11,7 +11,6 @@ use Yiisoft\Router\Group; use Yiisoft\Router\Route; use Yiisoft\Validator\ValidatorInterface; -use Yiisoft\Yii\Debug\Api\Middleware\ResponseDataWrapper; use Yiisoft\Yii\Gii\Controller\DefaultController; use Yiisoft\Yii\Middleware\IpFilter; @@ -31,7 +30,6 @@ static function (ResponseFactoryInterface $responseFactory, ValidatorInterface $ } ) ->middleware(FormatDataResponseAsJson::class) - ->middleware(ResponseDataWrapper::class) ->namePrefix('gii/api/') ->routes( Route::get('/{generator}') diff --git a/src/CodeFile.php b/src/CodeFile.php index b9eb1f1ea..3a93fc460 100644 --- a/src/CodeFile.php +++ b/src/CodeFile.php @@ -33,7 +33,10 @@ final class CodeFile * The new code file and the existing one are identical. */ public const OP_SKIP = 2; - public const OPERATIONS = [ + /** + * Operations map to be performed. + */ + public const OPERATIONS_MAP = [ self::OP_CREATE => 'Create', self::OP_OVERWRITE => 'Overwrite', self::OP_SKIP => 'Skip', @@ -48,7 +51,7 @@ final class CodeFile */ private string $path; /** - * @var int the operation to be performed. This can be [[OP_CREATE]], [[OP_OVERWRITE]] or [[OP_SKIP]]. + * @var int the operation to be performed. This can be {@see OP_CREATE}, {@see OP_OVERWRITE} or {@see OP_SKIP}. */ private int $operation = self::OP_CREATE; /** diff --git a/src/Controller/DefaultController.php b/src/Controller/DefaultController.php index f0e9312c0..7bd1b0264 100644 --- a/src/Controller/DefaultController.php +++ b/src/Controller/DefaultController.php @@ -80,7 +80,7 @@ public function preview(GeneratorRequest $request, #[Query('file')] ?string $fil Status::UNPROCESSABLE_ENTITY ); } - return $this->responseFactory->createResponse(['files' => $files, 'operations' => CodeFile::OPERATIONS]); + return $this->responseFactory->createResponse(['files' => $files, 'operations' => CodeFile::OPERATIONS_MAP]); } return $this->responseFactory->createResponse( diff --git a/src/Generator/AbstractGenerator.php b/src/Generator/AbstractGenerator.php index 82df21f07..a426037ec 100644 --- a/src/Generator/AbstractGenerator.php +++ b/src/Generator/AbstractGenerator.php @@ -131,22 +131,6 @@ public function successMessage(): string return 'The code has been generated successfully.'; } - /** - * Returns the view file for the input form of the generator. - * The default implementation will return the "form.php" file under the directory - * that contains the generator class file. - * - * @throws ReflectionException - * - * @return string the view file for the input form of the generator. - */ - public function formView(): string - { - $class = new ReflectionClass($this); - - return dirname($class->getFileName()) . '/form.php'; - } - /** * Returns the root path to the default code template files. * The default implementation will return the "templates" subdirectory of the From 4f13ee9ca0babe52ad38855e270d81c155c783b6 Mon Sep 17 00:00:00 2001 From: Rustam Date: Thu, 13 Oct 2022 10:37:49 +0500 Subject: [PATCH 7/8] Fix deps --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index fb2685a1c..47e5e9066 100644 --- a/composer.json +++ b/composer.json @@ -43,7 +43,8 @@ "yiisoft/di": "^1.1", "yiisoft/event-dispatcher": "^1.0", "yiisoft/files": "^2.0", - "yiisoft/log": "^2.0" + "yiisoft/log": "^2.0", + "yiisoft/router-fastroute": "^1.0" }, "autoload": { "psr-4": { From e9f619a91db8f6d21bba20ee81e9135c0e697710 Mon Sep 17 00:00:00 2001 From: Rustam Date: Fri, 14 Oct 2022 16:33:19 +0500 Subject: [PATCH 8/8] Adjust code --- src/Controller/DefaultController.php | 43 +++++++++++++--------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/src/Controller/DefaultController.php b/src/Controller/DefaultController.php index 7bd1b0264..c7870f648 100644 --- a/src/Controller/DefaultController.php +++ b/src/Controller/DefaultController.php @@ -61,32 +61,29 @@ public function preview(GeneratorRequest $request, #[Query('file')] ?string $fil /** @var AbstractGenerator $generator */ $generator = $request->getGenerator(); $validationResult = $generator->validate(); - if ($validationResult->isValid()) { - $files = $generator->generate(); - if ($file !== null) { - foreach ($files as $generatedFile) { - if ($generatedFile->getId() === $file) { - $content = $generatedFile->preview(); - if ($content !== false) { - return $this->responseFactory->createResponse(['content' => $content]); - } - return $this->responseFactory->createResponse( - ['content' => 'Preview is not available for this file type.'] - ); - } + if (!$validationResult->isValid()) { + return $this->responseFactory->createResponse( + ['errors' => $validationResult->getErrorMessagesIndexedByAttribute()], + Status::UNPROCESSABLE_ENTITY + ); + } + + $files = $generator->generate(); + if ($file !== null) { + foreach ($files as $generatedFile) { + if ($generatedFile->getId() === $file) { + $content = $generatedFile->preview(); + return $this->responseFactory->createResponse( + ['content' => $content ?: 'Preview is not available for this file type.'] + ); } - return $this->responseFactory->createResponse( - ['message' => "Code file not found: $file"], - Status::UNPROCESSABLE_ENTITY - ); } - return $this->responseFactory->createResponse(['files' => $files, 'operations' => CodeFile::OPERATIONS_MAP]); + return $this->responseFactory->createResponse( + ['message' => "Code file not found: $file"], + Status::UNPROCESSABLE_ENTITY + ); } - - return $this->responseFactory->createResponse( - ['errors' => $validationResult->getErrorMessagesIndexedByAttribute()], - Status::UNPROCESSABLE_ENTITY - ); + return $this->responseFactory->createResponse(['files' => $files, 'operations' => CodeFile::OPERATIONS_MAP]); } public function diff(GeneratorRequest $request, #[Query('file')] string $file): ResponseInterface