TemplateGuesser: prepare for version decoupling, v5

This commit is contained in:
TomasVotruba 2018-01-17 12:58:13 +01:00
parent ba6c9ec8a9
commit f1e46801c0

View File

@ -4,20 +4,35 @@ namespace Rector\NodeAnalyzer\Contrib\Symfony;
use Nette\Utils\Strings;
use PhpParser\Node\Stmt\ClassMethod;
use Rector\Exception\ShouldNotHappenException;
use Rector\Node\Attribute;
/**
* Mimics https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/072c00c52b947e88a1e619e9ff426cee6c8c482b/Templating/TemplateGuesser.php
* only without Symfony dependency
*/
final class TemplateGuesser
{
public function resolveFromClassMethodNode(ClassMethod $classMethodNode): string
public function resolveFromClassMethodNode(ClassMethod $classMethodNode, int $version = 5): string
{
$namespace = (string) $classMethodNode->getAttribute(Attribute::NAMESPACE_NAME);
$class = (string) $classMethodNode->getAttribute(Attribute::CLASS_NAME);
$method = $classMethodNode->name->toString();
if ($version === 5) {
$templateName = $this->resolveForVersion5($namespace, $class, $method);
} else {
throw new ShouldNotHappenException(sprintf(
'Version %d is not supported in %s. Add it.',
$version,
self::class
));
}
return $templateName . '.html.twig';
}
/**
* Mimics https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/v3.0.0/Templating/TemplateGuesser.php
*/
private function resolveForVersion5(string $namespace, string $class, string $method): string
{
// AppBundle\SomeNamespace\ => AppBundle
// App\OtherBundle\SomeNamespace\ => OtherBundle
$templateName = Strings::match($namespace, '/(?<bundle>[A-Za-z]*Bundle)/')['bundle'] ?? '';
@ -30,9 +45,6 @@ final class TemplateGuesser
// indexAction => index
$templateName .= Strings::match($method, '/(?<method>[A-Za-z]*)Action$/')['method'] ?? '';
// suffix
$templateName .= '.html.twig';
return $templateName;
}
}