GET result empty when using transformer with api platform and symfony - symfony

I'm using api platform in symfony (4) and without using a transformer (or rather: without using the output property) I'm getting the correct result.
However as I need to transform a logo (add a path) I need to integrate a transformer. As a result the response is empty.
ApiResource definition in Entity:
/**
*
* #ApiResource(
* collectionOperations = {
* "get"
* },
* normalizationContext={"groups" = {"frontend:read"}},
* itemOperations={
"get"
* },
* order={"name"="ASC"},
* paginationEnabled=false,
* output=EntityApiOutput::class
* )
*/
EntityApiOutput:
class EntityApiOutput
{
public $id;
}
EntityApiOutputDataTransformer:
class EntityApiOutputDataTransformer implements DataTransformerInterface
{
/**
* {#inheritdoc}
*/
public function transform($object, string $to, array $context = [])
{
$eao = new EntityApiOutput();
$eao->id = 3;
return $eao;
}
public function supportsTransformation($data, string $to, array $context = []): bool
{
return EntityApiOutput::class === $to && $data instanceof Entity;
}
}
entry in services.yaml:
App\DataTransformer\EntityApiOutputDataTransformer:
tags:
- { name: api_platform.data_transformer }
I simplified the transformer for reading purposes.
Putting a
dump($eao)
exit;
into the transform method confirms that the transformer is called and the EntityApiOutput object is filled.

Mhm unfortunately the api platform doc forgets to mention to also put the group into the output class:
class EntityApiOutput
{
/*
*
* #Groups({"frontend:read"})
*/
public $id;
}
That's how it should look like.

Related

FOSHttpCacheBundle cache invalidation with Symfony built-in reverse proxy doesn't work

I'm trying to do a hard thing: implementing cache invalidation with Symfony 4.4.13 using FOSHttpCacheBundle 2.9.0 and built-in Symfony reverse proxy.
Unfortunately, I can't use other caching solution (like Varnish or Nginx) because my hosting service doesn't offer them. So, the Symfony built-in reverse proxy is the only solution I have.
I've installed and configured FOSHttpCacheBundle (following the documentation). Also created a CacheKernel class and modified Kernel to use it (following Symfony official documentation, FOSHttpCache documentation and FOSHttpCacheBundle documentation).
After few tests (with my browser), the HTTP caching works and GET responses are cached (seen in browser network analyzer). But, when I update a resource with PUT/PATCH/POST, the GET responses still come from the cache and are unchanged until the expiration. My deduction is the invalidation doesn't work.
Have I do something wrong? Can you help me to troubleshoot?
See my code and configuration below.
config/packages/fos_http_cache.yaml
fos_http_cache:
cache_control:
rules:
-
match:
path: ^/
headers:
cache_control:
public: true
max_age: 15
s_maxage: 30
etag: "strong"
cache_manager:
enabled: true
invalidation:
enabled: true
proxy_client:
symfony:
tags_header: My-Cache-Tags
tags_method: TAGPURGE
header_length: 1234
purge_method: PURGE
use_kernel_dispatcher: true
src/CacheKernel.php
<?php
namespace App;
use FOS\HttpCache\SymfonyCache\CacheInvalidation;
use FOS\HttpCache\SymfonyCache\CustomTtlListener;
use FOS\HttpCache\SymfonyCache\DebugListener;
use FOS\HttpCache\SymfonyCache\EventDispatchingHttpCache;
use FOS\HttpCache\SymfonyCache\PurgeListener;
use FOS\HttpCache\SymfonyCache\RefreshListener;
use FOS\HttpCache\SymfonyCache\UserContextListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class CacheKernel extends HttpCache implements CacheInvalidation
{
use EventDispatchingHttpCache;
// Overwrite constructor to register event listeners for FOSHttpCache.
public function __construct(HttpKernelInterface $kernel, SurrogateInterface $surrogate = null, array $options = [])
{
parent::__construct($kernel, new Store($kernel->getCacheDir()), $surrogate, $options);
$this->addSubscriber(new CustomTtlListener());
$this->addSubscriber(new PurgeListener());
$this->addSubscriber(new RefreshListener());
$this->addSubscriber(new UserContextListener());
if (isset($options['debug']) && $options['debug'])
$this->addSubscriber(new DebugListener());
}
// Made public to allow event listeners to do refresh operations.
public function fetch(Request $request, $catch = false)
{
return parent::fetch($request, $catch);
}
}
src/Kernel.php
<?php
namespace App;
use FOS\HttpCache\SymfonyCache\HttpCacheAware;
use FOS\HttpCache\SymfonyCache\HttpCacheProvider;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
class Kernel extends BaseKernel implements HttpCacheProvider
{
use MicroKernelTrait;
use HttpCacheAware;
private const CONFIG_EXTS = '.{php,xml,yaml,yml}';
public function __construct(string $environment, bool $debug)
{
parent::__construct($environment, $debug);
$this->setHttpCache(new CacheKernel($this));
}
...
public/index.php
<?php
use App\Kernel;
use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\HttpFoundation\Request;
require dirname(__DIR__).'/config/bootstrap.php';
...
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$kernel = $kernel->getHttpCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
One of mine controller, src/Controller/SectionController.php (NOTE: routes are defined in YAML files)
<?php
namespace App\Controller;
use App\Entity\Section;
use App\Entity\SectionCollection;
use App\Form\SectionType;
use FOS\HttpCacheBundle\Configuration\InvalidateRoute;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class SectionController extends AbstractFOSRestController
{
/**
* List all sections.
*
* #Rest\View
* #param Request $request the request object
* #return array
*
* Route: get_sections
*/
public function getSectionsAction(Request $request)
{
return new SectionCollection($this->getDoctrine()->getRepository(Section::class)->findAll());
}
/**
* Get a single section.
*
* #Rest\View
* #param Request $request the request object
* #param int $id the section id
* #return array
* #throws NotFoundHttpException when section not exist
*
* Route: get_section
*/
public function getSectionAction(Request $request, $id)
{
if (!$section = $this->getDoctrine()->getRepository(Section::class)->find($id))
throw $this->createNotFoundException('Section does not exist.');
return array('section' => $section);
}
/**
* Get friends of the section's user.
*
* #Rest\View
* #return array
*
* Route: get_friendlysections
*/
public function getFriendlysectionsAction()
{
return $this->get('security.token_storage')->getToken()->getUser()->getSection()->getMyFriends();
}
private function processForm(Request $request, Section $section)
{
$em = $this->getDoctrine()->getManager();
$statusCode = $em->contains($section) ? Response::HTTP_NO_CONTENT : Response::HTTP_CREATED;
$form = $this->createForm(SectionType::class, $section, array('method' => $request->getMethod()));
// If PATCH method, don't clear missing data.
$form->submit($request->request->get($form->getName()), $request->getMethod() === 'PATCH' ? false : true);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($section);
$em->flush();
$response = new Response();
$response->setStatusCode($statusCode);
// set the 'Location' header only when creating new resources
if ($statusCode === Response::HTTP_CREATED) {
$response->headers->set('Location',
$this->generateUrl(
'get_section', array('id' => $section->getId()),
true // absolute
)
);
}
return $response;
}
return View::create($form, Response::HTTP_BAD_REQUEST);
}
/**
*
* Creates a new section from the submitted data.
*
* #Rest\View
* #return FormTypeInterface[]
*
* #InvalidateRoute("get_friendlysections")
* #InvalidateRoute("get_sections")
*
* Route: post_section
*/
public function postSectionsAction(Request $request)
{
return $this->processForm($request, new Section());
}
/**
* Update existing section from the submitted data.
*
* #Rest\View
* #param int $id the section id
* #return FormTypeInterface[]
* #throws NotFoundHttpException when section not exist
*
* #InvalidateRoute("get_friendlysections")
* #InvalidateRoute("get_sections")
* #InvalidateRoute("get_section", params={"id" = {"expression"="id"}})")
*
* Route: put_section
*/
public function putSectionsAction(Request $request, $id)
{
if (!$section = $this->getDoctrine()->getRepository(Section::class)->find($id))
throw $this->createNotFoundException('Section does not exist.');
return $this->processForm($request, $section);
}
/**
* Partially update existing section from the submitted data.
*
* #Rest\View
* #param int $id the section id
* #return FormTypeInterface[]
* #throws NotFoundHttpException when section not exist
*
* #InvalidateRoute("get_friendlysections")
* #InvalidateRoute("get_sections")
* #InvalidateRoute("get_section", params={"id" = {"expression"="id"}})")
*
* Route: patch_section
*/
public function patchSectionsAction(Request $request, $id)
{
return $this->putSectionsAction($request, $id);
}
/**
* Remove a section.
*
* #Rest\View(statusCode=204)
* #param int $id the section id
* #return View
*
* #InvalidateRoute("get_friendlysections")
* #InvalidateRoute("get_sections")
* #InvalidateRoute("get_section", params={"id" = {"expression"="id"}})")
*
* Route: delete_section
*/
public function deleteSectionsAction($id)
{
$em = $this->getDoctrine()->getManager();
if ($section = $this->getDoctrine()->getRepository(Section::class)->find($id)) {
$em->remove($section);
$em->flush();
}
}
}
After searching few days, I found the solution by myself.
In CacheKernel, I extend Symfony\Component\HttpKernel\HttpCache\HttpCache as described in FOSHttpCache documentation. But, the class must extend Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache instead as described in Symfony documentation. By consequences, the constructor change too.
To be honest, I don't know the difference between these two classes but you must use the second one if you want to have a built-in functional reverse proxy. It works now for me.
I put here the final code of src/CacheKernel.php:
<?php
namespace App;
use FOS\HttpCache\SymfonyCache\CacheInvalidation;
use FOS\HttpCache\SymfonyCache\CustomTtlListener;
use FOS\HttpCache\SymfonyCache\DebugListener;
use FOS\HttpCache\SymfonyCache\EventDispatchingHttpCache;
use FOS\HttpCache\SymfonyCache\PurgeListener;
use FOS\HttpCache\SymfonyCache\RefreshListener;
use FOS\HttpCache\SymfonyCache\UserContextListener;
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class CacheKernel extends HttpCache implements CacheInvalidation
{
use EventDispatchingHttpCache;
/**
* Overwrite constructor to register event listeners for FOSHttpCache.
*/
public function __construct(HttpKernelInterface $kernel)
{
parent::__construct($kernel, $kernel->getCacheDir());
$this->addSubscriber(new CustomTtlListener());
$this->addSubscriber(new PurgeListener());
$this->addSubscriber(new RefreshListener());
$this->addSubscriber(new UserContextListener());
if (isset($options['debug']) && $options['debug'])
$this->addSubscriber(new DebugListener());
}
/**
* Made public to allow event listeners to do refresh operations.
*
* {#inheritDoc}
*/
public function fetch(Request $request, $catch = false)
{
return parent::fetch($request, $catch);
}
}
The rest of the code don't change.
Hope it helps. See you.

Symfony Api Platform return data not converted to hydra response

I use API platform in my application, I create my custom Paginator of API platform but the response is not converted to hydra response :
code repository:
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator as Paginator;
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
public function findByExampleField($page, $items)
{
$firstResult = ($page - 1) * $items;
$queryBuilder = $this->createQueryBuilder('c')
->orderBy('c.id', 'ASC');
$query = $queryBuilder->getQuery()
->setFirstResult($firstResult)
->setMaxResults($items);
$dp = new DoctrinePaginator($query);
$po = new Paginator($dp);
return $po;
}
with this code, the response is normale data and not hydra response
Based on the comment section, since you want to extend a GET collection operation, I think creating a custom paginator is not a good approach:
creating a custom paginator is not mentionned as a way to extend Api-Platform,
the use of customized queries is achieved by the extension system.
Example with the extension system:
(Note the operation name)
// src/Entity/Data.php
namespace App\Entity;
/**
* #ApiResource(
* collectionOperations = {
* "get_only_status_true" = {
* "method" = "get"
* }
* }
* )
* #ORM\Entity(repositoryClass=DataRepository::class)
*/
class Data
{
/**
* #var int
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var boolean
* #ORM\Column(type="boolean")
*/
private $status;
// getter and setters there
}
// src/Doctrine/DataExtensions.php
namespace App\Doctrine;
class DataExtension implements QueryCollectionExtensionInterface
{
public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator,
string $resourceClass, string $operationName = null)
{
if ($resourceClass === Data::class && $operationName === 'get_only_status_true') {
$data = $queryBuilder->getRootAliases()[0];
$queryBuilder->andWhere("$data.status = 1");
}
}
}

symfony many normalizers for one entity

I have several user roles with access to orders and controllers for each of them. Are there ways to change the normalizer for one entity, for example...
in this action i need to get the normalizer for the courier:
## CourierController
/**
* #Rest\Get()
*/
public function orders()
{
$serializer = $this->get('serializer');
$orders = $this->getDoctrine()
->getRepository(Order::class)
->findBy(['courier' => $this->getUser()->getCourierAccount()]);
$data = $serializer->normalize($orders); // <--------- 1) how to choose the right normalizer?
return $this->json($data);
}
But in this i need for something like 'ClientOrderNormalizer'
## ClientController
/**
* #Rest\Get()
*/
public function orders()
{
$serializer = $this->get('serializer');
$orders = $this->getDoctrine()
->getRepository(Order::class)
->findBy(['client' => $this->getUser()->getClientAccount()]);
$data = $serializer->normalize($orders); // <--------- 2) how to choose the right normalizer?
return $this->json($data);
}
1) Using Serialization Groups Annotations -> look here
2) Create custom DTO then serialize this object for a response.
Example of how to create custom DTO.
final class SignInResponse implements ResponseInterface
{
/**
* #var string
*
* #SWG\Property(type="string", description="Token.")
*/
private string $token;
public function __construct(UserSession $userSession)
{
$this->token = $userSession->getToken();
}
/**
* Get Token
*
* #return string
*/
public function getToken(): string
{
return $this->token;
}
}

Drupal 8.x + GraphQL Module Custom Type/Field Plugin Receiving Error "fields must be an object with field names as keys"

I am attempting to create a module which defines it's own custom Type and associated Field plugins.
When installed, GraphQLi reports the following error in the console:
Uncaught Error: CustomTypeInterface fields must be an object with field names as keys or a function which returns such an object.
Drupal 8.61. I have tried on both GraphQL 3.0-RC2 and 3.x-Dev. Any help would be much appreciated. Thanks.
My code is as follows:
/graphql_custom.info.yml
name: GraphQL Custom Type Example
type: module
description: ''
package: GraphQL
core: 8.x
dependencies:
- graphql_core
/src/CustomObject.php
namespace Drupal\graphql_custom;
class CustomObject {
protected $data;
function __construct(String $data) {
$this->data = $data;
}
function getData() {
return $this->data;
}
}
/src/Plugin/GraphQL/Fields/CustomField.php
<?php
namespace Drupal\graphql_custom\Plugin\GraphQL\Fields;
use Drupal\graphql_custom\CustomObject;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\graphql\GraphQL\Execution\ResolveContext;
use Drupal\graphql\Plugin\GraphQL\Fields\FieldPluginBase;
use GraphQL\Type\Definition\ResolveInfo;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Created Custom Object with argument as data.
*
* #GraphQLField(
* id = "custom_field",
* secure = true,
* name = "customfield",
* type = "CustomType",
* nullable = true,
* arguments = {
* "argument" = "String!"
* }
* )
*/
class CustomField extends FieldPluginBase implements ContainerFactoryPluginInterface {
/**
* {#inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition
);
}
/**
* {#inheritdoc}
*/
protected function isLanguageAwareField() {
return FALSE;
}
/**
* {#inheritdoc}
*/
public function resolve($value, array $args, ResolveContext $context, ResolveInfo $info) {
return parent::resolve($value, $args, $context, $info);
}
/**
* {#inheritdoc}
*/
public function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
$arg = $args['argument'];
$object = new CustomObject($arg);
yield $object;
}
}
/src/Plugin/GraphQL/Fields/CustomFieldData.php
<?php
namespace Drupal\graphql_custom\Plugin\GraphQL\Fields;
use Drupal\graphql_custom\CustomObject;
use Drupal\graphql\Plugin\GraphQL\Fields\FieldPluginBase;
use Drupal\graphql\GraphQL\Execution\ResolveContext;
use GraphQL\Type\Definition\ResolveInfo;
/**
* Custom Type Data Field
*
* #GraphQLField(
* id = "custom_field_data",
* secure = true,
* name = "data",
* type = "String",
* parents = {"CustomType"}
* )
*/
class CustomFieldData extends FieldPluginBase {
/**
* {#inheritdoc}
*/
protected function resolveValues($value, array $args, $context, $info) {
if ($value instanceOf CustomObject) {
yield (string) $value->getData();
} else {
yield (string) "Empty";
}
}
}
/src/Plugin/GraphQL/Interfaces/CustomTypeInterface.php
<?php
namespace Drupal\graphql_custom\Plugin\GraphQL\Interfaces;
use Drupal\graphql_custom\CustomObject;
use Drupal\graphql\Annotation\GraphQLInterface;
use Drupal\graphql\Plugin\GraphQL\Interfaces\InterfacePluginBase;
/**
* Interface for Custom Type.
*
* For simplicity reasons, this example does not utilize dependency injection.
*
* #GraphQLInterface(
* id = "custom_type_interface",
* name = "CustomTypeInterface"
* )
*/
class CustomTypeInterface extends InterfacePluginBase {
/**
* {#inheritdoc}
*/
public function resolveType($object) {
if ($object instanceof CustomObject) {
$schemaManager = \Drupal::service('graphql_core.schema_manager');
return $schemaManager->findByName('CustomType', [
GRAPHQL_CORE_TYPE_PLUGIN,
]);
}
}
}
/src/Plugin/GraphQL/Types/CustomType.php
<?php
namespace Drupal\graphql_custom\Plugin\GraphQL\Types;
use Drupal\graphql_custom\CustomObject;
use Drupal\graphql\Plugin\GraphQL\Types\TypePluginBase;
use Drupal\graphql\GraphQL\Execution\ResolveContext;
use GraphQL\Type\Definition\ResolveInfo;
/**
* GraphQL Custom Type.
*
* #GraphQLType(
* id = "custom_type",
* name = "CustomType",
* interfaces = {"CustomTypeInterface"}
* )
*/
class CustomType extends TypePluginBase {
/**
* {#inheritdoc}
*/
public function applies($object, ResolveContext $context, ResolveInfo $info) {
return $object instanceof CustomObject;
}
}
With your fields you should use interface reference in parents instead of type:
parents = {"CustomTypeInterface"}
Another way is to remove interface and use direct type reference as mentioned in your example.

Symfony The annotation does not exist, or could not be auto-loaded - Symfony Validation with Doctrine

We have a legacy app which is not based on symfony. Doctrine is in use and now we would like to add validation to the models. Seems that the Annotations never get autoloaded, even when "use" statements are in use.
[Semantical Error] The annotation "#Symfony\Component\Validator\Constraints\NotBlank" in property Test\Stackoverflow\User::$Username does not exist, or could not be auto-loaded.
Wrote a small demo application to showcase the problem and how we create the entity manager and validation instance.
composer.json:
{
"require": {
"symfony/validator" : "~3.1"
, "doctrine/orm" : "~2.6.1"
}
}
index.php
require_once ('vendor/autoload.php');
// Load Entities, would normally be done over composer since they reside in a package
require_once('test/User.php');
require_once('MyAnnotationTestApp.php');
// create test app
$app = new MyAnnotationsTestApp();
$app->initEntityManager('localhost', 'annotation_test', 'root', 'mysql', 3306);
if(key_exists('test', $_GET)){
// Create entity and validate it
$entity = new \Test\Stackoverflow\User();
$entity->setUsername('StackoverflowUser');
if($app->testAnnotationWithoutLoading($entity)){
print "Seems the validation was working without preloading the asserts\n<br>";
}
if($app->testAnnotationWithLoading($entity)){
print "Seems the validation was working because we loaded the required class ourself.\n<br>";
}
print "\n<br><br>The question is why the required annotation classes never get autoloaded?";
}else{
// Load the validator class otherwise the annotation throws an exception
$notBlankValidator = new \Symfony\Component\Validator\Constraints\NotBlank();
print "We have cerated the tables but also had to load the validator class ourself.\n<br>\n<br>";
// create tables and
$app->updateDatabaseSchema();
print sprintf('Now lets run the test', $_SERVER['REQUEST_URI']);
}
Doctrine user Entity
<?php
namespace Test\Stackoverflow;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity()
* #ORM\Table(name="users")
*
*/
class User{
/**
* #ORM\Id
* #ORM\Column(name="Id",type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $Id;
public function getId(){
return $this->Id;
}
/**
* #ORM\Column(type="text", length=80, nullable=false)
* #Assert\NotBlank()
*/
protected $Username;
/**
* #return string
*/
public function getUsername()
{
return $this->Username;
}
/**
* #param string $Username
*/
public function setUsername($Username)
{
$this->Username = $Username;
}
}
Demo App with doctrine/validator initialisation:
<?php
final class MyAnnotationsTestApp {
/**
* #var \Doctrine\ORM\EntityManager
*/
private $entityManager;
/**
* #param string $host
* #param string $database
* #param string $username
* #param string $password
* #param integer $port
* #param array $options
* #return \Doctrine\ORM\EntityManager
*/
public function initEntityManager($host, $database, $username, $password, $port, array $options=null){
if($this->entityManager){
return $this->entityManager;
}
$connectionString = sprintf('mysql://%3$s:%4$s#%1$s/%2$s', $host, $database, $username, $password, $port);
$isDevMode = true;
$dbParams = array(
'url' => $connectionString
, 'driver' => 'pdo_mysql'
, 'driverOptions' => array(
1002 => "SET NAMES utf8mb4"
)
);
$cacheDriver = null;
$config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array(), $isDevMode, '.cache/', $cacheDriver, false);
if($cacheDriver){
$config->setMetadataCacheImpl($cacheDriver);
$config->setQueryCacheImpl($cacheDriver);
$config->setResultCacheImpl($cacheDriver);
}
$this->entityManager = \Doctrine\ORM\EntityManager::create($dbParams, $config);
return $this->entityManager;
}
/**
* #return \Doctrine\ORM\EntityManager
*/
public function getEntityManager(){
return $this->entityManager;
}
public function updateDatabaseSchema(){
$metaData = array();
$usedEntities = array(
'Test\Stackoverflow\User'
);
foreach($usedEntities as $entity){
$metaData[] = $this->entityManager->getClassMetadata($entity);
}
$tool = new \Doctrine\ORM\Tools\SchemaTool($this->entityManager);
$tool->updateSchema($metaData);
$this->generateProxies($metaData);
}
/**
* Generate all the proxy classes for orm in the correct directory.
* Proxy dir can be configured over application configuration
*
*
* #throws \Exception
*/
final public function generateProxies($metaData)
{
$em = $this->getEntityManager();
$destPath = $em->getConfiguration()->getProxyDir();
if (!is_dir($destPath)) {
mkdir($destPath, 0777, true);
}
$destPath = realpath($destPath);
if (!file_exists($destPath)) {
throw new \Exception("Proxy destination directory could not be created " . $em->getConfiguration()->getProxyDir());
}
if (!is_writable($destPath)) {
throw new \Exception(
sprintf("Proxies destination directory '<info>%s</info>' does not have write permissions.", $destPath)
);
}
if (count($metaData)) {
// Generating Proxies
$em->getProxyFactory()->generateProxyClasses($metaData, $destPath);
}
}
/**
* #var \Symfony\Component\Validator\Validator\ValidatorInterface
*/
protected $validator;
/**
* #return \Symfony\Component\Validator\Validator\ValidatorInterface
*/
final protected function getValidator(){
if($this->validator){
return $this->validator;
}
$this->validator = \Symfony\Component\Validator\Validation::createValidatorBuilder()
->enableAnnotationMapping()
->getValidator();
return $this->validator;
}
/**
* #param \Test\Stackoverflow\User $entity
* #return bool
*/
final public function testAnnotationWithoutLoading(\Test\Stackoverflow\User $entity){
try {
print "test to validate the entity without preloading the Assert classes\n<br>";
$this->getValidator()->validate($entity);
return true;
} catch(\Exception $e){
print "<strong>Does not work since the Asserts classes never get loaded: </strong> Exception-message: ".$e->getMessage()."\n<br>";
return false;
}
}
/**
* #param \Test\Stackoverflow\User $entity
* #return bool
*/
final public function testAnnotationWithLoading(\Test\Stackoverflow\User $entity){
// Here we force the autoloader to require the class
$notBlankValidator = new \Symfony\Component\Validator\Constraints\NotBlank();
try {
print "Loaded the validator manually, will test of it fails now\n<br>";
$this->getValidator()->validate($entity);
return true;
} catch(\Exception $e){
print "<strong>Was not working: </strong> Exception-message: ".$e->getMessage()."\n<br>";
print sprintf("<strong>Even when we autoload the class it is not working. Type of assert: %s</strong>\n<br>", get_class($notBlankValidator));
return false;
}
}
}
If you are using the Symfony Standard Edition, you must update your
autoload.php file by adding the following code [1]
How are these annotations loaded? From looking at the code you could
guess that the ORM Mapping, Assert Validation and the fully qualified
annotation can just be loaded using the defined PHP autoloaders. This
is not the case however: For error handling reasons every check for
class existence inside the AnnotationReader sets the second parameter
$autoload of class_exists($name, $autoload) to false. To work
flawlessly the AnnotationReader requires silent autoloaders which many
autoloaders are not. Silent autoloading is NOT part of the PSR-0
specification for autoloading. [2]
// at the top of the file
use Doctrine\Common\Annotations\AnnotationRegistry;
// at the end of the file
AnnotationRegistry::registerLoader(function($class) use ($loader) {
$loader->loadClass($class);
return class_exists($class, false);
});
[1] https://symfony.com/blog/symfony2-2-0-rc4-released
[2] https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/annotations.html

Resources