Skip to content

feat(refactoring): Use dedicated templates for generation #695

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

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
7 changes: 4 additions & 3 deletions generator/src/Commands/GenerateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,18 +83,19 @@ protected function execute(
$modules[$function->getModuleName()] = true;
}

$genDir = FileCreator::getSafeRootDir() . "/generated/$version";
$genDir = Filesystem::outputDir() . "/$version";
$fileCreator = new FileCreator();
$fileCreator->generatePhpFile($res->methods, "$genDir/");
$fileCreator->generateFunctionsList($res->methods, "$genDir/functionsList.php");
$fileCreator->generateRectorFile($res->methods, "$genDir/rector-migrate.php");
}

foreach (\array_keys($modules) as $moduleName) {
$fileCreator->generateVersionSplitters($moduleName, FileCreator::getSafeRootDir() . "/generated/", \array_keys($versions));
$fileCreator->generateVersionSplitters($moduleName, Filesystem::outputDir() . "/", \array_keys($versions));
$fileCreator->createExceptionFile((string) $moduleName);
}
$fileCreator->generateVersionSplitters("functionsList", FileCreator::getSafeRootDir() . "/generated/", \array_keys($versions), true);

$fileCreator->generateVersionSplitters("functionsList", Filesystem::outputDir() . "/", \array_keys($versions), true);

$this->runCsFix($output);

Expand Down
6 changes: 4 additions & 2 deletions generator/src/Generator/ComposerJsonEditor.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Safe\Generator;

use Safe\Templating\Filesystem;

/**
* This class will edit the main composer.json file to add the list of files generated from modules.
*/
Expand All @@ -15,7 +17,7 @@ class ComposerJsonEditor
public static function editComposerFileForGeneration(array $modules): void
{

$composerContent = file_get_contents(FileCreator::getSafeRootDir() . '/composer.json');
$composerContent = file_get_contents(Filesystem::projectRootDir() . '/composer.json');
if ($composerContent === false) {
throw new \RuntimeException('Error while loading composer.json file for edition.');
}
Expand All @@ -24,7 +26,7 @@ public static function editComposerFileForGeneration(array $modules): void
$composerJson['autoload']['files'] = self::editFilesListForGeneration($composerJson['autoload']['files'], $modules);

$newContent = \json_encode($composerJson, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES) . "\n";
\file_put_contents(FileCreator::getSafeRootDir() . '/composer.json', $newContent);
\file_put_contents(Filesystem::projectRootDir() . '/composer.json', $newContent);
}

/**
Expand Down
108 changes: 29 additions & 79 deletions generator/src/Generator/FileCreator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Safe\Generator;

use Safe\Templating\Engine;
use Safe\Templating\Filesystem;
use Safe\XmlDocParser\ErrorType;
use Safe\XmlDocParser\Scanner;
use Safe\XmlDocParser\Method;
Expand All @@ -13,6 +15,12 @@

class FileCreator
{
private Engine $engine;

public function __construct(?Engine $engine = null)
{
$this->engine = $engine ?? new Engine();
}
Comment on lines +18 to +23
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private Engine $engine;
public function __construct(?Engine $engine = null)
{
$this->engine = $engine ?? new Engine();
}
public function __construct(private Engine $engine = new Engine())
{
}

?


/**
* This function generate an improved php lib function in a php file
Expand All @@ -34,26 +42,14 @@ public function generatePhpFile(

foreach ($phpFunctionsByModule as $module => $phpFunctions) {
$lcModule = \lcfirst($module);
if (!is_dir($path)) {
if (!\is_dir($path)) {
\mkdir($path);
}
$stream = \fopen($path.$lcModule.'.php', 'w');
if ($stream === false) {
throw new \RuntimeException('Unable to write to '.$path);
}

// Write file header
\fwrite($stream, "<?php\n
namespace Safe;

use Safe\\Exceptions\\".self::toExceptionName($module). ';');

// Write safe wrappers for non-safe functions
foreach ($phpFunctions as $phpFunction) {
\fwrite($stream, "\n".$phpFunction);
}

\fclose($stream);
Filesystem::dumpFile($path . $lcModule . '.php', $this->engine->generate('Module.php.tpl', [
'{{exceptionName}}' => self::toExceptionName($module),
'{{functions}}' => \implode(PHP_EOL, $phpFunctions),
]));
}
}

Expand Down Expand Up @@ -107,18 +103,9 @@ private function getFunctionsNameList(array $functions): array
*/
public function generateFunctionsList(array $functions, string $path): void
{
$functionNames = $this->getFunctionsNameList($functions);
$stream = fopen($path, 'w');
if ($stream === false) {
throw new \RuntimeException('Unable to write to '.$path);
}
fwrite($stream, "<?php\n
return [\n");
foreach ($functionNames as $functionName) {
fwrite($stream, ' '.\var_export($functionName, true).",\n");
}
fwrite($stream, "];\n");
fclose($stream);
Filesystem::dumpFile($path, $this->engine->generate('FunctionList.php.tpl', [
'{{functionNames}}' => \implode(PHP_EOL, \array_map(static fn(string $name): string => \sprintf('\'%s\',', $name), $this->getFunctionsNameList($functions))),
]));
}

/**
Expand All @@ -128,66 +115,29 @@ public function generateFunctionsList(array $functions, string $path): void
*/
public function generateRectorFile(array $functions, string $path): void
{
$functionNames = $this->getFunctionsNameList($functions);

$stream = fopen($path, 'w');

if ($stream === false) {
throw new \RuntimeException('Unable to write to '.$path);
}

$header = <<<'TXT'
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Renaming\Rector\FuncCall\RenameFunctionRector;

// This file configures rector/rector to replace all PHP functions with their equivalent "safe" functions.
return static function (RectorConfig $rectorConfig): void {
$rectorConfig->ruleWithConfiguration(
RenameFunctionRector::class,
[
TXT;

fwrite($stream, $header);

foreach ($functionNames as $functionName) {
fwrite($stream, " '$functionName' => 'Safe\\$functionName',\n");
}

fwrite($stream, " ]\n );\n};\n");
fclose($stream);
Filesystem::dumpFile($path, $this->engine->generate('RectorConfig.php.tpl', [
'{{functionNames}}' => \implode(PHP_EOL, \array_map(static fn(string $name): string => \sprintf('\'%1$s\' => \'Safe\\%1$s\',', $name), $this->getFunctionsNameList($functions))),
]));
}

public function createExceptionFile(string $moduleName): void
{
$exceptionName = self::toExceptionName($moduleName);
if (!file_exists(FileCreator::getSafeRootDir() . '/lib/Exceptions/'.$exceptionName.'.php')) {
\file_put_contents(
FileCreator::getSafeRootDir() . '/generated/Exceptions/'.$exceptionName.'.php',
<<<EOF
<?php
namespace Safe\Exceptions;

class {$exceptionName} extends \ErrorException implements SafeExceptionInterface
{
public static function createFromPhpError(): self
{
\$error = error_get_last();
return new self(\$error['message'] ?? 'An error occurred', 0, \$error['type'] ?? 1);
}
}

EOF
);
}
Filesystem::dumpFile(Filesystem::outputDir() . '/Exceptions/'.$exceptionName.'.php', $this->engine->generate('Exception.php.tpl', [
'{{exceptionName}}' => $exceptionName,
]));
}

public static function getSafeRootDir(): string
{
return __DIR__ . '/../../..';
$path = realpath(__DIR__ . '/../../..');

if (false === $path) {
throw new \RuntimeException('Unable to locate root directory');
}

return $path;
}

/**
Expand Down
5 changes: 3 additions & 2 deletions generator/src/PhpStanFunctions/PhpStanFunctionMapReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Safe\PhpStanFunctions;

use Safe\Generator\FileCreator;
use Safe\Templating\Filesystem;

class PhpStanFunctionMapReader
{
Expand All @@ -20,8 +21,8 @@ class PhpStanFunctionMapReader

public function __construct()
{
$this->functionMap = require 'phar://' . FileCreator::getSafeRootDir() . '/generator/vendor/phpstan/phpstan/phpstan.phar/resources/functionMap.php';
$this->customFunctionMap = require FileCreator::getSafeRootDir() . '/generator/config/CustomPhpStanFunctionMap.php';
$this->functionMap = require 'phar://' . Filesystem::generatorDir() . '/vendor/phpstan/phpstan/phpstan.phar/resources/functionMap.php';
$this->customFunctionMap = require Filesystem::generatorDir() . '/config/CustomPhpStanFunctionMap.php';
}

public function getFunction(string $functionName): ?PhpStanFunction
Expand Down
61 changes: 61 additions & 0 deletions generator/src/Templating/Engine.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

declare(strict_types=1);

namespace Safe\Templating;

use Safe\Templating\Exception\InvalidPlaceholderException;
use Safe\Templating\Exception\TemplateNotFoundException;
use Safe\Templating\Exception\TemplatingException;
use Safe\Templating\Exception\UnreadableTemplateException;
use Symfony\Component\Finder\Finder;

final class Engine
{
/**
* @var string[] $templates
*/
private array $templates;

public function __construct()
{
$finder = Finder::create()->files()->name('*.php.tpl')->in(self::basePath());
$this->templates = array_map(fn(\SplFileInfo $file) => str_replace(self::basePath() . '/', '', $file->getRealPath()), \iterator_to_array($finder->getIterator()));
}

/**
* @param array<string, string> $context
*
* @throws TemplatingException
*/
public function generate(string $template, array $context = []): string
{
if (!$this->hasTemplate($template)) {
throw new TemplateNotFoundException(\sprintf('Template "%s" not found.', $template));
}

if (false === $content = file_get_contents(self::basePath() . '/' . $template)) {
throw new UnreadableTemplateException(\sprintf('Could not read template "%s".', $template));
}

foreach ($context as $placeholder => $replacement) {
if (!\is_string($replacement)) {
throw new InvalidPlaceholderException(\sprintf('Placeholder "%s" must be a string.', $placeholder));
}

$content = str_replace($placeholder, $replacement, $content);
}

return $content;
}

private function hasTemplate(string $name): bool
{
return 0 < \count(\array_filter($this->templates, static fn(string $template) => $template === $name));
}

private static function basePath(): string
{
return Filesystem::generatorDir().'/templates';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace Safe\Templating\Exception;

final class InvalidPlaceholderException extends TemplatingException
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace Safe\Templating\Exception;

final class TemplateNotFoundException extends TemplatingException
{
}
7 changes: 7 additions & 0 deletions generator/src/Templating/Exception/TemplatingException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Safe\Templating\Exception;

abstract class TemplatingException extends \InvalidArgumentException
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace Safe\Templating\Exception;

final class UnreadableTemplateException extends TemplatingException
{
}
42 changes: 42 additions & 0 deletions generator/src/Templating/Filesystem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

declare(strict_types=1);

namespace Safe\Templating;

final class Filesystem
{
private function __construct()
{
}

public static function projectRootDir(): string
{
$path = realpath(__DIR__ . '/../../..');

if (false === $path) {
throw new \RuntimeException('Unable to locate root directory');
}

return $path;
}

public static function generatorDir(): string
{
return \sprintf(self::projectRootDir().'/generator');
}

public static function outputDir(): string
{
return \sprintf(self::projectRootDir().'/generated');
}

public static function dumpFile(string $targetPath, string $content): void
{
$result = file_put_contents($targetPath, $content);

if (false === $result) {
throw new \RuntimeException(\sprintf('Could not write to "%s".', $targetPath));
}
}
}
3 changes: 2 additions & 1 deletion generator/src/XmlDocParser/DocPage.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Safe\Generator\FileCreator;

use Safe\Templating\Filesystem;
use function explode;
use function strpos;

Expand Down Expand Up @@ -61,7 +62,7 @@ public function getErrorType(): ErrorType
// This minimizes 'false positives', where text such as "returns false when ..." could be matched outside
// the function's dedicated Return Values section.
$returnDocs = $this->extractSection('returnvalues', $file);
$detectErrorType = require FileCreator::getSafeRootDir() . '/generator/config/detectErrorType.php';
$detectErrorType = require Filesystem::generatorDir() . '/config/detectErrorType.php';
return $detectErrorType($returnDocs);
}

Expand Down
Loading
Loading