JMS Serializer Config - symfony

I am using this in config.yml:
# JMSSerializer Configuration
jms_serializer:
#parameters:
#jms_serializer.camel_case_naming_strategy.class: JMS\Serializer\Naming\IdenticalPropertyNamingStrategy
metadata:
cache: file
debug: "%kernel.debug%"
file_cache:
dir: "%kernel.cache_dir%/serializer"
auto_detection: true
directories:
AppBundle:
namespace_prefix: "AppBundle"
path: "%kernel.root_dir%/config/serializer/AppBundle"
And this in Entity.Category.yml:
AppBundle\Entity\Category:
exclusion_policy: ALL
But when i try to send request, i receive this error:
Expected metadata for class AppBundle\Entity\Category to be defined
in /var/www/test/app/config/serializer/AppBundle/Entity.Category.yml.
How can I solve this issue?

You forgot about TAB at 2 line.

It looks like you are getting an incorrect path to your project files with %kernel.root_dir%. Make sure that /var/www/test/app is the correct path to your project. Check your PHP __DIR__ constant and try replacing `%kernel.root_dir% with what that says as well as what you think the path should be.
Also, instead of defining your exclusion policy in a config file you should just be able to annotate your entity like so and expose things as needed:
use JMS\Serializer\Annotation as JMS;
/**
* Class ExampleEntity
*
* #JMS\ExclusionPolicy("all")
* #ORM\Entity()
*/
class ExampleEntity
{
}
JMS annotations are found here.

Related

Symfony service FileUploader not autowiring

I've followed the Symfony 5.2 tutorial to add a FileUploader as a service (https://symfony.com/doc/current/controller/upload_file.html).
So this is my service.yaml
parameters:
targetDirectory: '%kernel.project_dir%/public/uploads/'
previews_video: '%kernel.project_dir%/public/uploads/previews'
brochures_directory: '%kernel.project_dir%/public/uploads/brochures'
services:
App\Service\FileUploader:
arguments:
$targetDirectory: '%previews_video%'
And this is my FileUploader.php
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\String\Slugger\SluggerInterface;
class FileUploader
{
private $targetDirectory;
private $slugger;
public function __construct($targetDirectory, SluggerInterface $slugger)
{
$this->targetDirectory = $targetDirectory;
$this->slugger = $slugger;
}
public function upload(UploadedFile $file)
{
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = $this->slugger->slug($originalFilename);
$fileName = $safeFilename.'-'.uniqid().'.'.$file->guessExtension();
try {
$file->move($this->getTargetDirectory(), $fileName);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
return $fileName;
}
public function getTargetDirectory()
{
return $this->targetDirectory;
}
}
But I'm having this common error :
Cannot resolve argument $fileUploader of "App\Controller\VideoController::edit()": Cannot autowire service "App\Service\FileUploader": argument "$targetDirectory" of method "__construct()" has no type-hint, you should configure its value explicitly.
Called by this controller :
/**
* #Route("/{id}/edit", name="video_edit", methods={"GET","POST"})
* #param Request $request
* #param Video $video
* #param FileUploader $fileUploader
* #return Response
*/
public function edit(Request $request, Video $video, FileUploader $fileUploader): Response
{...}
How do I fix this ? I trying by remove the string type, adding the string type, removing the $ from the targetDirectory parameters in services.yaml... Struggling with that for hours now...
Take a look at my working services.yaml. I've changed the namespace
App\Service
to
App\Services
And I also added the service declaration at the end of the file.
Looks like the order of the lines in services matter. First, I've added the declaration at the top of the services part, but the autowiring is declared after, guess the error was here...
# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
previews_directory: '%kernel.project_dir%/public/uploads/previews'
services:
#i've added my service here at first...
app.menu_builder:
class: App\Menu\MenuBuilder
arguments: ["#knp_menu.factory"]
tags:
- { name: knp_menu.menu_builder, method: createMainMenu, alias: main }
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
- '../src/Tests/'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller/'
tags: ['controller.service_arguments']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
App\Services\FileUploader:
arguments:
$targetDirectory: '%previews_directory%'
You should have autowiring configuration added to your services file:
parameters:
targetDirectory: '%kernel.project_dir%/public/uploads/'
previews_video: '%kernel.project_dir%/public/uploads/previews'
brochures_directory: '%kernel.project_dir%/public/uploads/brochures'
services:
# To add:
_defaults:
autowire: true
autoconfigure: true
# You service
App\Service\FileUploader:
arguments:
$targetDirectory: '%previews_video%'
Add a type-hint string for $targetDirectory in the contructor
public function __construct(string $targetDirectory, SluggerInterface $slugger)
{
$this->targetDirectory = $targetDirectory;
$this->slugger = $slugger;
}
I had the same issue.
It was related to the indentation of that specific service. I wasn't getting any indentation error but also the auto wiring wasn't working.
What i did was to add 4 spaces as indentation
App\Service\FileUploader:
arguments:
$targetDirectory: '%TEAM_LOGO_DIRECTORY%'
Yes I got the problem too and I managed to solve it by replacing indentation by spaces in the services.yaml file, I added all of these properties at the same root and then I did that and it works for me:
services:
App\Services\FileUploader: #(added 4 spaces, NOT 1 tab)
arguments: #(added 8 spaces, NOT 2 tabs)
$targetDirectory: '%cats_directory%' #(added 12 spaces, NOT 3 tabs)
If you struggle you (and other people who got this problem) can try this solution. I don't guarantee it will work 100%.

Kayue\WordpressBundle with Symfony 4.4.1: The class XXX was not found in the chain configured namespaces App\Entity

I'm trying to work with kayue/KayueWordpressBundle installed with composer as composer require kayue/kayue-wordpress-bundle in my Symfony 4.4.1 project but I'm unable to.
This is what I'm trying to do:
<?php
namespace App\Service\WordPress;
use Doctrine\ORM\EntityManagerInterface;
use Kayue\WordpressBundle\Entity\Post;
class PostCollection
{
protected $postRepository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->postRepository = $entityManager->getRepository(Post::class);
}
}
The error I get:
The class 'Kayue\WordpressBundle\Entity\Post' was not found in the chain configured namespaces App\Entity
At first I blamed my dual-database configuration (Symfony is on a different DB from Wordpress) but then I put the DBs together and the issue persists:
doctrine:
dbal:
url: '%env(resolve:DATABASE_URL)%'
# Only needed for MySQL (ignored otherwise)
charset: utf8mb4
default_table_options:
collate: utf8mb4_unicode_ci
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
I've been fiddling for the past 2hrs, but now I'm fresh out of ideas. I wonder if ANYONE actually got this to work with Symfony 4.
Thanks!
Edit: other tries:
Direct post injection:
use Kayue\WordpressBundle\Entity\Post;
public function index(Post $post){}
Result:
Cannot autowire argument $post of "App\Controller\IndexController::index()": it references class "Kayue\WordpressBundle\Entity\Post" but no such service exists.
As per documentation: outdated Symfony 2 way
$repo = $this->get('kayue_wordpress')->getManager()->getRepository('KayueWordpressBundle:Post');
Result:
Service "kayue_wordpress" not found: even though it exists in the app's container, the container inside "App\Controller\IndexController" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session" and "twig" services. Try using dependency injection instead.
The "best way" to do this would actually be:
public function index(EntityManagerInterface $entityManager)
{
$entityManager->getRepository('KayueWordpressBundle:Post');
}
Result:
The class 'Kayue\WordpressBundle\Entity\Post' was not found in the chain configured namespaces App\Entity
Although you found a solution to this, there is a chain of issues I would like to explain.
The error
The class 'Kayue\WordpressBundle\Entity\Post' was not found in the chain configured namespaces App\Entity
means that in the entity manager provided, whose config is defined at:
orm:
...
mappings:
App:
...
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
the entity type Kayue\WordpressBundle\Entity\Post was not found.
Usually this type of error is solved by:
include the path Kayue\WordpressBundle\Entity in the entity manager or
use another entity manager which includes this path
In your case the default entity manager is autowired, based on the service alias of Doctrine\ORM\EntityManagerInterface as explained here. The alias is defined in the doctrine bundle `s config which points to the default doctrine entity manager.
You want to use Kayue\WordpressBundle `s entity manager, not the default one.
Solution
To solve this you can
1) Bind Arguments By type, as you find out, creating an alias of Kayue\WordpressBundle\Wordpress\ManagerRegistry to the service kayue_wordpress, as:
services:
# pass this service for any ManagerRegistry type-hint for any
# service that's defined in this file
Kayue\WordpressBundle\Wordpress\ManagerRegistry: '#kayue_wordpress'
or
2) use Binding Arguments by Name, in this case the "$wpManagerRegistry", as:
services:
# default configuration for services in *this* file
_defaults:
...
bind:
$wpManagerRegistry: '#kayue_wordpress'
and then
public function index($wpManagerRegistry)
{
$postRepository = $wpManagerRegistry->getManager()->getRepository('KayueWordpressBundle:Post');
so that any argument with name "$wpManagerRegistry" is autowired to this service.
References
The Symfony 3.3 DI Container Changes Explained (autowiring, _defaults, etc)
My collegue found a solution. You must configure the autowire like this:
// config/packages/kayue_wordpress.yaml
services:
Kayue\WordpressBundle\Wordpress\ManagerRegistry: '#kayue_wordpress'
After that, you can autowire:
use Kayue\WordpressBundle\Wordpress\ManagerRegistry;
public function __construct(ManagerRegistry $wpManagerRegistry)
{
$this->wpPostRepository = $wpManagerRegistry->getManager()->getRepository('KayueWordpressBundle:Post');
}
public function getPosts()
{
$post = $this->wpPostRepository->findOneBy(array(
'slug' => 'hello-world',
'type' => 'post',
'status' => 'publish',
));
}

How to define schema when I want to use annotations with overblog graphql?

I want to use annotations with overblog graphql in symfony. When i create a provider with an query I get an error about the schema.
error: At least one schema should be declare
I don`t know how to config the schema in the config file. Normally I use yaml as type.
When I use the defaults its using CoreQuery whats pointing to the yaml config file. I don`t know how to change this for using annotations in php. When I remove the schema from definitions i get the same error.
What do I need to change to use annotation with overblog graphql bundle?
/config/packages/graphql.yaml
overblog_graphql:
definitions:
schema:
default:
query: CoreQuery
# mutation: CoreMutation
show_debug_info: '%kernel.debug%'
mappings:
auto_discover: false
types:
- type: annotation
dir: "%kernel.project_dir%/src/GraphQL"
suffix: ~
/src/Graphql/Types/SensorProviders.php
namespace App\Graphql\Types;
use Overblog\GraphQLBundle\Annotation as GQL;
/**
* #GQL\Provider
*/
class SensorProviders {
/**
* #GQL\Query(type="[Sensor]", name="sensors")
*/
public function getSensors() {
return [];
}
}
/src/Graphql/Types/Sensor.php
namespace App\Graphql\Types;
use Overblog\GraphQLBundle\Annotation as GQL;
/**
* #GQL\Type
*/
class Sensor
{
/**
* #GQL\Field(type="Integer!")
*/
public $id;
}
I had the same issues, but after hours of debugging, i figured it out:
With your graphql.yaml you would need following additional file:
/src/Graphql/Types/CoreQuery.php:
namespace App\Graphql\Types;
use Overblog\GraphQLBundle\Annotation as GQL;
/**
* #GQL\Type
*/
class CoreQuery
{
}
Basically you need to define an empty root type and all annotated queries get automatically added.
Same for mutations.

sf 2.6 A2LiX entityTranslation doesn't found

I just want to make a multilingual application site so I red and saw translatable and other bundle.
I use translatable and a2lix... so I read the doc but when I try to use a2lix, I get this error message :
Class c2c\AppBundle\Entity\PeriodTranslation does not exist 500 Internal Server Error - ReflectionException
I set my entityTranslation in a subfolder like so Entity>Translation>MyEntityTranslation
Is there a way to say to a2lix... that it should look inside my sub-folder ?
Thank you for your help.
Entity
namespace c2c\AppBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Translatable\Translatable;
/**
* Period
*
* #ORM\Table(name="Periods")
* #ORM\Entity(repositoryClass="c2c\AppBundle\Entity\PeriodRepository")
* #Gedmo\TranslationEntity(class="c2c\AppBundle\Entity\Translation\PeriodTranslation")
*/
class Period implements Translatable
...
Entity Translation
namespace c2c\AppBundle\Entity\Translation;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Translatable\Entity\MappedSuperclass\AbstractTranslation;
/**
* PeriodTranslation is used fo
*
* #author blucas
*/
/**
* #ORM\Table(name="ext_translations_period", indexes={
* #ORM\Index(name="period_translation_idx", columns={"locale", "object_class", "field", "foreign_key"})
* })
* #ORM\Entity(repositoryClass="Gedmo\Translatable\Entity\Repository\TranslationRepository")
*/
class PeriodTranslation extends AbstractTranslation
{
/**
* All required columns are mapped through inherited superclass
*/
}
Config
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
mappings:
gedmo_translatable:
type: annotation
prefix: Gedmo\Translatable\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity"
alias: GedmoTranslatable
is_bundle: false
...
# Soft Doctrine extendions
stof_doctrine_extensions:
default_locale: en_US
# Only used if you activated the Uploadable extension
# uploadable:
# Default file path: This is one of the three ways you can configure the path for the Uploadable extension
# default_file_path: %kernel.root_dir%/../web/uploads
# Mime type guesser class: Optional. By default, we provide an adapter for the one present in the HttpFoundation component of Symfony
# mime_type_guesser_class: Stof\DoctrineExtensionsBundle\Uploadable\MimeTypeGuesserAdapter
# Default file info class implementing FileInfoInterface: Optional. By default we provide a class which is prepared to receive an UploadedFile instance.
# default_file_info_class: Stof\DoctrineExtensionsBundle\Uploadable\UploadedFileInfo
orm:
default:
# sluggable: true
translatable: true
...
# Give a way to translate form
a2lix_translation_form:
locale_provider: default
locales: [en,fr,nl]
default_locale: en
required_locales: [en]
manager_registry: doctrine
templating: "A2lixTranslationFormBundle::default.html.twig"
The error is thrown becous the newest version of a2lix is not compatible with the stable version of Gedmo
check this answer https://stackoverflow.com/a/22018321/2160958
If you want to use Gedmo strategy you will have to downgrade your "a2lix/translation-form-bundle" to "1.*#dev" if you want to use the newest version of "a2lix/translation-form-bundle" you will have to use
wip2.4 Gedmo version, with is unstable yet.
check this https://github.com/a2lix/TranslationFormBundle/blob/master/UPGRADE-2.0.md

Configuring the Translatable Doctrine2 extension with Symfony2 using YAML

In a nutshell
I'm writing a Symfony2 / Doctrine2 app and have installed and configured the Translatable extension provided by StofDoctrineExtensionsBundle using YAML, however no additional translation table(s) are generated and the following exception is thrown when attempting to work with entities that have translatable properties:
No mapping file found named '/var/www/my-project/vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity/Translation.orm.yml' for class 'Gedmo\Translatable\Entity\Translation'.
In more detail
I'm trying to get the Translatable extension working in my Symfony2 / Doctrine2 application that is provided by the StofDoctrineExtensionsBundle, however most of the available documentation I can find mainly targets the usage of annotations for configuration, but I'm going with YAML because that's how I have configured everything else.
My configuration
I have added the following to my composer.json file and have ran the composer update command: "stof/doctrine-extensions-bundle": "dev-master" and the bundle is registered in my app/AppKernel.php file.
My app/config/config.yml file has the following configuration:
doctrine:
orm:
auto_generate_proxy_classes: %kernel.debug%
auto_mapping: true
mappings:
gedmo_translatable:
type: yml
prefix: Gedmo\Translatable\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity"
alias: GedmoTranslatable
is_bundle: false
stof_doctrine_extensions:
default_locale: en_GB
translation_fallback: true
orm:
default:
timestampable: true
translatable: true
I have then defined an entity in YAML:
Foo\ContentBundle\Entity\Article:
type: entity
repositoryClass: Foo\ContentBundle\Repository\ArticleRepository
table: article
gedmo:
translation:
locale: locale
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
name:
type: string
length: 64
gedmo:
- translatable
content:
type: text
gedmo:
- translatable
# ... #
oneToMany:
# ... #
I have then ran the console command php app/console doctrine:generate:entities FooContentBundle to generate the entity classes, and have manually added the locale property and setter:
class Article
{
/* ... */
private $locale;
public function setTranslatableLocale($locale)
{
$this->locale = $locale;
}
/* ... */
}
After running php app/console doctrine:schema:update --force, my article table is created along with its associations, but nothing relating to translations (I'm assuming a table is supposed to be created for this...)
Then, when working with an entity that is translatable, I'm getting the exception:
No mapping file found named '/var/www/my-project/vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity/Translation.orm.yml' for class 'Gedmo\Translatable\Entity\Translation'.
The YAML file that the exception is referencing does not exist in the path that it's looking for it within, neither could I find it anywhere else.
Does anyone have any ideas as to where I'm going wrong?
Update: After further investigation...
Running php app/console doctrine:mapping:info displays all of my entities and nothing relating to translations, however, if I update the gedmo_translatable: part of my app/config/config.yml file and change type: yml to type: annotation then run the command again, I get the following listed:
[OK] Gedmo\Translatable\Entity\MappedSuperclass\AbstractTranslation
[OK] Gedmo\Translatable\Entity\Translation
[OK] Gedmo\Translatable\Entity\MappedSuperclass\AbstractPersonalTranslation
At which point, I can update my schema, and I have a new ext_translations table. However, nothing is being inserted into it when working with my entities, presumably because it's now expecting configuration by annotation rather than YAML, changing my config back to type: yml starts throwing the exception again, as expected.
After trying things that the documentation suggests will not work, i.e. mixing both annotation and YAML configurations in the same bundle, it would appear I have things working. The whole thing feels like a bug or an incomplete implementation, however I may be doing something incorrectly. Here's what's working...
Setting the following in app/config/config.yml: doctrine.orm.mappings.gedmo_translatable.type: annotation
Setting the translatable configuration in my YAML schema definition as outlined in my original question, as well as as an annotation in my class file:
/* ... */
use Gedmo\Mapping\Annotation as Gedmo;
/* ... */
class Article
{
/* ... */
/**
* #Gedmo\Translatable
* #var string $name
*/
private $name;
/**
* #Gedmo\Locale
*/
private $locale;
public function setTranslatableLocale($locale)
{
$this->locale = $locale;
}
/* ... */
}
After doing this, the additional table is created and translations are being inserted into it when persisting the entity.

Resources