Skip to content

Instantly share code, notes, and snippets.

@RobinDev
Last active November 1, 2023 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobinDev/7266009271b7379219eed2f1a1857c87 to your computer and use it in GitHub Desktop.
Save RobinDev/7266009271b7379219eed2f1a1857c87 to your computer and use it in GitHub Desktop.
From Twig to Plates
find . -type f -name "*.php" -exec sed -i '1i\
<?php\
\
use My\\App\\Service\\PlatesTemplate;\
\
/**\
* @var PlatesTemplate $this\
*/\
\
?>' {} \;
<?php
include 'vendor/autoload.php';
use My\App\Service\PlatesExtension;
$extensionsList = [
PlatesExtension::class
];
class GenerateDocBlockForPlatesTemplate
{
public function run($extensionClassName)
{
$reflectionClass = new ReflectionClass($extensionClassName);
$methods = $reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC);
$phpDoc = '';
foreach ($methods as $method) {
if (in_array($method->getName(), ['__construct', 'register'])) {
continue;
}
$paramStrings = [];
foreach ($method->getParameters() as $parameter) {
$paramString = $this->formatType($parameter->getType()).' $'.$parameter->getName();
if ($parameter->isDefaultValueAvailable()) {
$defaultValue = $parameter->getDefaultValue();
$paramString .= ' = '.str_replace(chr(10), '', var_export($defaultValue, true));
}
$paramStrings[] = $paramString;
}
$returnType = $this->formatType($method->getReturnType());
$phpDoc .= ' * @method '.('' === $returnType ? '' : $returnType.' ').$method->getName().'('.implode(', ', $paramStrings).')';
$phpDoc .= ' // LINK '.$reflectionClass->getFileName().':'.$method->getStartLine();
$phpDoc .= "\n";
}
return $phpDoc;
}
private function formatType(ReflectionType $returnType): string
{
if (null === $returnType) {
return '';
}
if ($returnType instanceof ReflectionNamedType) {
return false === $returnType?->isBuiltin() ?
(($returnType->allowsNull() ? '?' : '').'\\'.$returnType->getName())
: $returnType;
}
if ($returnType instanceof ReflectionUnionType) {
$toReturn = [];
foreach ($returnType->getTypes() as $type) {
$toReturn[] = $this->formatType($type);
}
return implode('|', $toReturn);
}
dd($returnType);
throw new Exception();
}
}
$output = '<?php
namespace App\Service;
use League\Plates\Template\Template;
/**
* Generated by php script/GenerateDocBlockForPlatesTemplates.php
';
foreach ($extensionsList as $className) {
$output .= (new GenerateDocBlockForPlatesTemplate())->run($className);
}
$output .= ' */
class PlatesTemplate extends Template
{
}';
file_put_contents('src/Service/PlatesTemplate.php', $output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment