8000 [AstGenerator] [WIP] New Component, add normalizer generator by joelwurtz · Pull Request #17516 · symfony/symfony · GitHub
[go: up one dir, main page]

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
Closed
Prev Previous commit
Next Next commit
Add hydration of object
  • Loading branch information
joelwurtz committed Aug 5, 2016
commit 365bdb20bad19e85cc5c4083cf5df18bde5a2496
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,17 @@
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 normalization of types */
/** @var AstGeneratorInterface Generator for hydration of types */
protected $typeHydrateAstGenerator;

public function __construct(PropertyInfoExtractorInterface $propertyInfoExtractor, AstGeneratorInterface $typeHydrateAstGenerator)
Expand Down
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));
}
}
129 changes: 129 additions & 0 deletions src/Symfony/Component/AstGenerator/Hydrate/ObjectHydrateGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?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\Arg;
use PhpParser\Node\Name;
use PhpParser\Node\Expr;
use Symfony\Component\AstGenerator\AstGeneratorInterface;
use Symfony\Component\AstGenerator\Exception\MissingContextException;
use Symfony\Component\AstGenerator\UniqueVariableScope;
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;

/**
* Abstract class to generate hydration of object from data
*
* @author Joel Wurtz <joel.wurtz@gmail.com>
*/
abstract class ObjectHydrateGenerator 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 = [])
{
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');
}

$uniqueVariableScope = isset($context['unique_variable_scope']) ? $context['unique_variable_scope'] : new UniqueVariableScope();
$statements = [
new Expr\Assign($context['output'], new Expr\New_(new Name("\\".$object))),
];

foreach ($this->propertyInfoExtractor->getProperties($object, $context) as $property) {
// Only hydrate writable property
Copy link
Contributor

Choose a reason for hiding this comment

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

properties

if (!$this->propertyInfoExtractor->isWritable($object, $property, $context)) {
continue;
}

$output = new Expr\Variable($uniqueVariableScope->getUniqueName('output'));
$input = $this->createInputExpr($context['input'], $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) {
// @TODO Have property info extractor extract the way of writing a property (public or method with method name)
$statements[] = new Expr\MethodCall($context['output'], 'set'.ucfirst($property), [
new Arg($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) {
// @TODO Have property info extractor extract the way of writing a property (public or method with method name)
$statements[] = new Expr\MethodCall($context['output'], 'set'.ucfirst($property), [
new Arg($input)
]);
} else {
$statements[] = new Expr\MethodCall($context['output'], 'set'.ucfirst($property), [
new Arg($output)
]);
}
}

return $statements;
}

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

/**
* Create the input expression for a specific property
*
* @param Expr\Variable $inputVariable Input variable of data
* @param string $property Property to fetch
*
* @return Expr
*/
abstract protected function createInputExpr(Expr\Variable $inputVariable, $property);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?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\Type;

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

/**
* Abstract class to generate collection hydration
*
* @author Joel Wurtz <joel.wurtz@gmail.com>
*/
class CollectionTypeGenerator implements AstGeneratorInterface
{
const COLLECTION_WITH_STDCLASS = 0;
const COLLECTION_WITH_ARRAY = 1;

/**
* CollectionTypeGenerator constructor.
*
* @param AstGeneratorInterface $subValueTypeGenerator Generator for the value of the collection
* @param int|null $fromCollectionType From collection type to generate, array or stdClass, use null
* to have a dynamic choice depending on the type of the collection key (where int will be array and string stdClass)
* @param int|null $toCollectionType To collection type to generate, array or stdClass, use null
* to have a dynamic choice depending on the type of the collection key (where int will be array and string stdClass)
*/
public function __construct(AstGeneratorInterface $subValueTypeGenerator, $fromCollectionType = null, $toCollectionType = null)
{

}

/**
* {@inheritdoc}
*
* @param Type $object A type extracted with PropertyInfo component
*/
public function generate($object, array $context = [])
{
if (!isset($context['input']) || !($context['input'] instanceof Expr)) {
throw new MissingContextException('Input variable not defined or not an Expr in generation context');
}

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

$statements = [
new Expr\Assign($context['output'], $this->createCollectionAssignStatement()),
];

$loopValueVar = new Expr\Variable($context->getUniqueVariableName('value'));
$loopKeyVar = $this->createLoopKeyStatement($context);
}

/**
* {@inheritdoc}
*/
public function supportsGeneration($object)
{
return $object instanceof Type && $object->isCollection();
}

/**
* Create the collection assign statement
*
* @return Expr
*/
protected function createCollectionAssignStatement()
{

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,78 @@

namespace Symfony\Component\AstGenerator\Hydrate\Type;

class TypeGenerator
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Stmt;
use PhpParser\Node\Name;
use Symfony\Component\AstGenerator\AstGeneratorInterface;
use Symfony\Component\AstGenerator\Exception\MissingContextException;
use Symfony\Component\PropertyInfo\Type;

/**
* Generate hydration of simple type.
*
* @author Joel Wurtz <joel.wurtz@gmail.com>
*/
class TypeGenerator implements AstGeneratorInterface
{
protected $supportedTypes = [
Type::BUILTIN_TYPE_BOOL,
Type::BUILTIN_TYPE_FLOAT,
Type::BUILTIN_TYPE_INT,
Type::BUILTIN_TYPE_NULL,
Type::BUILTIN_TYPE_STRING,
];

protected $conditionMapping = [
Type::BUILTIN_TYPE_BOOL => 'is_bool',
Type::BUILTIN_TYPE_FLOAT => 'is_float',
Type::BUILTIN_TYPE_INT => 'is_int',
Type::BUILTIN_TYPE_NULL => 'is_null',
Type::BUILTIN_TYPE_STRING => 'is_string',
];

/**
* {@inheritdoc}
*
* @param Type $object A type extracted with PropertyInfo component
*/
public function generate($object, array $context = [])
{
if (!isset($context['input']) || !($context['input'] instanceof Expr)) {
throw new MissingContextException('Input variable not defined or not an Expr in generation context');
}

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

$assign = [
new Expr\Assign($context['output'], $context['input'])
];

if (isset($context['condition']) && $context['condition']) {
return [new Stmt\If_(
new Expr\FuncCall(
new Name($this->conditionMapping[$object->getBuiltinType()]),
[
new Arg($context['input'])
]
),
[
'stmts' => $assign
]
)];
}

return $assign;
}

/**
* {@inheritdoc}
*/
public function supportsGeneration($object)
{
return $object instanceof Type && in_array($object->getBuiltinType(), $this->supportedTypes);
}
}
Loading
0