Skip to content

[AstGenerator] [WIP] New Component, add normalizer generator #17516

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

Closed
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@
"egulias/email-validator": "~1.2,>=1.2.8|~2.0",
"symfony/polyfill-apcu": "~1.1",
"symfony/security-acl": "~2.8|~3.0",
"phpdocumentor/reflection-docblock": "^3.0"
"phpdocumentor/reflection-docblock": "^3.0",
"nikic/PHP-Parser": "~2.0"
},
"conflict": {
"phpdocumentor/reflection-docblock": "<3.0",
Expand Down
3 changes: 3 additions & 0 deletions src/Symfony/Component/AstGenerator/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
66 changes: 66 additions & 0 deletions src/Symfony/Component/AstGenerator/AstGeneratorChain.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\AstGenerator;

/**
* Generator delegating the generation to a chain of generators.
*
* @author Joel Wurtz <joel.wurtz@gmail.com>
*/
class AstGeneratorChain implements AstGeneratorInterface
{
/** @var AstGeneratorInterface[] A list of generators */
protected $generators;

/** @var bool Whether the generation must return as soon as possible or use all generators, default to false */
protected $returnOnFirst;

public function __construct(array $generators = array(), $returnOnFirst = false)
{
$this->generators = $generators;
$this->returnOnFirst = $returnOnFirst;
}

/**
* {@inheritdoc}
*/
public function generate($object, array $context = array())
{
$nodes = array();

foreach ($this->generators as $generator) {
if ($generator instanceof AstGeneratorInterface && $generator->supportsGeneration($object)) {
Copy link
Member

Choose a reason for hiding this comment

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

The $generator instanceof AstGeneratorInterface test should be moved in the constructor to avoid doing it at every call to generate()

$nodes = array_merge($nodes, $generator->generate($object, $context));

if ($this->returnOnFirst) {
return $nodes;
}
}
}

return $nodes;
}

/**
* {@inheritdoc}
*/
public function supportsGeneration($object)
{
foreach ($this->generators as $generator) {
if ($generator instanceof AstGeneratorInterface && $generator->supportsGeneration($object)) {
return true;
}
}

return false;
}
}
39 changes: 39 additions & 0 deletions src/Symfony/Component/AstGenerator/AstGeneratorInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\AstGenerator;

/**
* An AstGeneratorInterface is a contract to transform an object into an AST.
*
* @author Joel Wurtz <joel.wurtz@gmail.com>
*/
interface AstGeneratorInterface
{
/**
* Generate an object into an AST given a specific context.
*
* @param mixed $object Object to generate AST from
* @param array $context Context for the generator
*
* @return \PhpParser\Node[] An array of statements (AST Node)
*/
public function generate($object, array $context = array());

/**
* Check whether the given object is supported for generation by this generator.
*
* @param mixed $object Object to generate AST from
*
* @return bool
*/
public function supportsGeneration($object);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Symfony\Component\AstGenerator\Exception;

class MissingContextException extends \RuntimeException
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\AstGenerator\Hydrate;

use PhpParser\Node\Expr;
use PhpParser\Node\Scalar;

/**
* Create AST Statement to normalize a Class into a stdClassObject.
*
* @author Joel Wurtz <joel.wurtz@gmail.com>
*/
class ArrayHydrateGenerator extends HydrateFromObjectGenerator
{
/**
* {@inheritdoc}
*/
protected function getAssignStatement($dataVariable)
{
return new Expr\Assign($dataVariable, new Expr\Array_());
}

/**
* {@inheritdoc}
*/
protected function getSubAssignVariableStatement($dataVariable, $property)
{
return new Expr\ArrayDimFetch($dataVariable, new Scalar\String_($property));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\AstGenerator\Hydrate;

use PhpParser\Node\Name;
use PhpParser\Node\Expr;
use Symfony\Component\AstGenerator\AstGeneratorInterface;
use Symfony\Component\AstGenerator\Exception\MissingContextException;
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;

/**
* Abstract class to generate hydration of data from object
*
* @author Joel Wurtz <joel.wurtz@gmail.com>
*/
abstract class HydrateFromObjectGenerator implements AstGeneratorInterface
{
/** @var PropertyInfoExtractorInterface Extract list of properties from a class */
protected $propertyInfoExtractor;

/** @var AstGeneratorInterface Generator for hydration of types */
protected $typeHydrateAstGenerator;

public function __construct(PropertyInfoExtractorInterface $propertyInfoExtractor, AstGeneratorInterface $typeHydrateAstGenerator)
{
$this->propertyInfoExtractor = $propertyInfoExtractor;
$this->typeHydrateAstGenerator = $typeHydrateAstGenerator;
}

/**
* {@inheritdoc}
*/
public function generate($object, array $context = array())
{
if (!isset($context['input']) || !($context['input'] instanceof Expr\Variable)) {
throw new MissingContextException('Input variable not defined or not a Expr\Variable in generation context');
}

if (!isset($context['output']) || !($context['output'] instanceof Expr\Variable)) {
throw new MissingContextException('Output variable not defined or not a Expr\Variable in generation context');
}

$statements = array($this->getAssignStatement($context['output']));

foreach ($this->propertyInfoExtractor->getProperties($object, $context) as $property) {
// Only normalize readable property
if (!$this->propertyInfoExtractor->isReadable($object, $property, $context)) {
continue;
}

// @TODO Have property info extractor extract the way of reading a property (public or method with method name)
$input = new Expr\MethodCall($context['input'], 'get'.ucfirst($property));
$output = $this->getSubAssignVariableStatement($context['output'], $property);
$types = $this->propertyInfoExtractor->getTypes($object, $property, $context);

// If no type can be extracted, directly assign output to input
if (null === $types || count($types) == 0) {
Copy link
Contributor

Choose a reason for hiding this comment

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

0 === count($type)

$statements[] = new Expr\Assign($output, $input);

continue;
}

// If there is multiple types, we need to know which one we must normalize
$conditionNeeded = (boolean) (count($types) > 1);
$noAssignment = true;

foreach ($types as $type) {
if (!$this->typeHydrateAstGenerator->supportsGeneration($type)) {
continue;
}

$noAssignment = false;
$statements = array_merge($statements, $this->typeHydrateAstGenerator->generate($type, array_merge($context, [
'input' => $input,
'output' => $output,
'condition' => $conditionNeeded,
])));
}

// If nothing has been assigned, we directly put input into output
if ($noAssignment) {
$statements[] = new Expr\Assign($output, $input);
}
}

return $statements;
}

/**
* {@inheritdoc}
*/
public function supportsGeneration($object)
{
return is_string($object) && class_exists($object);
}

/**
* Create the assign statement.
*
* @param Expr\Variable $dataVariable Variable to use
*
* @return Expr\Assign An assignment for the variable
*/
abstract protected function getAssignStatement($dataVariable);

/**
* Create the sub assign variable statement.
*
* @param Expr\Variable $dataVariable Variable to use
* @param string $property Property name for object or array dimension
*
* @return Expr\ArrayDimFetch|Expr\PropertyFetch
*/
abstract protected function getSubAssignVariableStatement($dataVariable, $property);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\AstGenerator\Hydrate;

use PhpParser\Node\Expr;
use PhpParser\Node\Scalar;

class ObjectHydrateFromArrayGenerator extends ObjectHydrateGenerator
{
/**
* {@inheritdoc}
*/
protected function createInputExpr(Expr\Variable $inputVariable, $property)
{
return new Expr\ArrayDimFetch($inputVariable, new Scalar\String_($property));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\AstGenerator\Hydrate;

use PhpParser\Node\Expr;

class ObjectHydrateFromStdClassGenerator extends ObjectHydrateGenerator
{
/**
* {@inheritdoc}
*/
protected function createInputExpr(Expr\Variable $inputVariable, $property)
{
return new Expr\PropertyFetch($inputVariable, sprintf("{'%s'}", $property));
}
}
Loading