Sylius\Component\Core\Model\Product::getMainTaxon() returns proxy insead of Taxoninterface - sylius

getMainTaxon() returns Proxy instead of TaxonInterface
I am doing migration from sylius 1.1 to sylius 1.5. Everything works fine except this error. I have no idea what should i do with this error.
My _sylius.yaml contains these entries:
sylius_product:
resources:
product:
classes:
repository: App\Repository\ProductRepository
model: App\Entity\Product
controller: App\Controller\ProductController
translation:
classes:
model: App\Entity\ProductTranslation
sylius_taxonomy:
resources:
taxon:
classes:
repository: App\Repository\TaxonRepository
model: App\Entity\Taxon
My doctrine.yaml looks like this:
doctrine:
dbal:
driver: 'pdo_mysql'
server_version: '5.7'
charset: UTF8
url: '%env(resolve:DATABASE_URL)%'
orm:
auto_generate_proxy_classes: '%kernel.debug%'
auto_mapping: true
mappings:
App:
is_bundle: false
type: yml
dir: '%kernel.project_dir%/config/doctrine'
prefix: 'App\Entity'
alias: App
Full error looks like this
Return value of Sylius\Component\Core\Model\Product::getMainTaxon() must be an instance of Sylius\Component\Core\Model\TaxonInterface or null, instance of Proxies__CG__\App\Entity\Taxon returned
Do you know what can cause this error and how to manage it?

finally I managed to solve this issue. Maybe it will help someone who migrates an application from legacy sylius.
In the past, I extended the Taxon entity and my Taxon.php looked like this
use Sylius\Component\Taxonomy\Model\Taxon as BaseTaxon;
class Taxon extends BaseTaxon {
The issue was I should have extended Sylius\Component\Core\Model\Taxon class so my entity file now looks like this
use Sylius\Component\Core\Model\Taxon as BaseTaxon;
class Taxon extends BaseTaxon {

Related

Swagger OpenApi 3.0 Jaxrs: Usage of oneOf results in InvalidDefinitionException: Cannot construct instance

I have the following swagger.yaml that uses the oneOf keyword.
openapi: 3.0.0
info:
version: 0.0.1
title: Polymorphism example
description: ''
paths:
/animal:
post:
summary: Create a new animal
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Animal'
responses:
'201':
description: Created
components:
schemas:
Animal:
type: object
properties:
name:
type: string
props:
oneOf:
- $ref: '#/components/schemas/Fish'
- $ref: '#/components/schemas/Dog'
Fish:
type: object
properties:
depth:
type: integer
Dog:
type: object
properties:
country:
type: string
If used the latest Swagger codegen tools (3.0.22) to create a server stub for JAX-RS Jersey.
I am trying to post the following example object:
{
"name":"Foo",
"props":{
"country":"Bar"
}
}
But this results in the following exception:
javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `io.swagger.model.OneOfAnimalProps` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 30] (through reference chain: io.swagger.model.Animal["props"])
at org.glassfish.jersey.servlet.WebComponent.serviceImpl (WebComponent.java:432)
at org.glassfish.jersey.servlet.WebComponent.service (WebComponent.java:370)
at org.glassfish.jersey.servlet.ServletContainer.service (ServletContainer.java:389)
at org.glassfish.jersey.servlet.ServletContainer.service (ServletContainer.java:342)
at org.glassfish.jersey.servlet.ServletContainer.service (ServletContainer.java:229)
at org.eclipse.jetty.servlet.ServletHolder.handle (ServletHolder.java:808)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1669)
at io.swagger.api.ApiOriginFilter.doFilter (ApiOriginFilter.java:15)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1652)
at org.eclipse.jetty.servlet.ServletHandler.doHandle (ServletHandler.java:585)
at org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle (SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle (SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle (ContextHandler.java:1127)
at org.eclipse.jetty.servlet.ServletHandler.doScope (ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope (SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope (ContextHandler.java:1061)
at org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle (ContextHandlerCollection.java:215)
at org.eclipse.jetty.server.handler.HandlerCollection.handle (HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle (HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle (Server.java:497)
at org.eclipse.jetty.server.HttpChannel.handle (HttpChannel.java:310)
at org.eclipse.jetty.server.HttpConnection.onFillable (HttpConnection.java:257)
at org.eclipse.jetty.io.AbstractConnection$2.run (AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob (QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run (QueuedThreadPool.java:555)
at java.lang.Thread.run (Thread.java:748)
Does this error relate to a bug in the JAX-RS codegen part?
Is there any way to fix this on server stub side?

Symfony 3.3 - Entity Manager injection into services with multiple database?

I have recently added a new database to my Symfony 3.3 application.
Then my services with injected entity manager are no longer working and return the following error:
Cannot autowire service "RouterBundle\Utils\RoutersUtils": argument
"$em" of method "__construct()" references class
"Doctrine\ORM\EntityManager" but no such service exists. Try changing
the type-hint to one of its parents: interface
"Doctrine\ORM\EntityManagerInterface", or interface
"Doctrine\Common\Persistence\ObjectManager".
So my config.yml file is now like :
# Doctrine Configuration
doctrine:
dbal:
default_connection: router
connections:
router:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_router_name%'
user: '%database_router_user%'
password: '%database_router_password%'
charset: utf8mb4
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
row_format: DYNAMIC
app:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_app_name%'
user: '%database_app_user%'
password: '%database_app_password%'
charset: utf8mb4
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
orm:
default_entity_manager: router
entity_managers:
router:
connection: router
mappings:
RouterBundle: ~
dql:
string_functions:
# Match agains should have the path to the Sha1 class created in the previous step
SHA1: RouterBundle\Extensions\Doctrine\Sha1
app:
connection: app
mappings:
AppBundle: ~
One of my service like :
<?php
namespace RouterBundle\Utils;
use Doctrine\ORM\EntityManager;
class RoutersUtils
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
...
and my services.yml ( I tried to add this arguments but doesn't work)
...
RouterBundle\Utils:
public: true
arguments:
- '#doctrine.dbal.router_connection'
...
Any idea how to inject the correct Entity Manager?
Can I also inject entity manager by default using the "default_entity_manager: router" parameters in teh config file ?
Thanks for the help !
Pierre
You cannot autowiring by using the EntityManagerInterface if you have many managers. You will have to pick the right manager in your service definition for each service.
RouterBundle\Utils:
$em: '#your_entity_manager_service'
PS : You should consider upgrading to sf3.4 as 3.3 is not maintenaited anymore. It also comes with local binding, which will be really useful for what you want to do.
See:
https://symfony.com/blog/new-in-symfony-3-4-local-service-binding

Symfony 4 one entity, two entity Manager

Hello everyone, I'm trying to have 2 entityManagers for one entity in Symfony4 but I have some trouble to do this.
When I persist an entity it works,(For example if have two entity Mananagers : Customer and Default ,when I use Customer or Default to persist) but when I want to use Repository, The first entity Managare in doctrine.yaml is always used.
I have to do this because I have 2 databases. One in internet and one inside my intranet that i have created and I search to do is that when the user click one button for example. It update the database on internet.
config/packages/doctrine.yaml
doctrine:
dbal:
default_connection: default
connections:
default:
driver: pdo_mysql
host: **************
port: 3306
dbname: intranetDb
user: **********
password: *****
charset: UTF8
customer:
driver: pdo_mysql
host: internetDb
port: 3306
dbname: *********
user: *********
password: *********
charset: UTF8
orm:
default_entity_manager: default
entity_managers:
default:
connection: default
auto_mapping: false
mappings:
Main:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: Main
customer:
connection: customer
auto_mapping: false
mappings:
Customer:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: Main
MyController.php
..
$drug = $this->getDoctrine()->getRepository(Drug::class,'customer')->findAll() ;
..
This code always give me the data inside of default and if I put customer first inside of orm the customer is always given.
Some help will be welcome because I have this problem in few days and I have no Idea to solve this(It's probably because of symfony version that I didn't found solution inside forum).
Thank you.(And sorry for my bad English)
You can get the repository from an entity manager, instead of getting it from the ManagerRegistry returned by getDoctrine().
Example:
[...]
$this->getDoctrine()->getManager('manager_name')->getRepository('class_name');
[...]

Symfony - No Extension Is Able To Load The Configuration (Subscriber/Event Listening) (REST API Exception Handling with JSON output)

Purpose
Hello, I am fairly new to Symfony and am trying to create an exception/error handling functionality for our Web API.
Requirements
When a user makes an invalid request to our API, we want to return a simple JSON object that looks something like the following:
{"errorCode": 1234567, "errorMessage": "Parameter 1 is invalid. String expected"}
In addition to API-specific errors, we also want to hook into the built-in exception-handling in Symfony and re-use that, but instead of returning an HTML error page (which is what happens by default), we want to return a JSON object like:
{"errorCode": 404, "errorMessage": "Not found"}
Current Approach
Obviously, we want this to be implemented in the most efficient way, so after doing some research, I found what I think is a great approach which I can then adapt to our specific needs. Here is the tutorial I followed:
https://knpuniversity.com/screencast/symfony-rest2
I ended up buying this course in order to get access to the full code. The issue is that it was written for Symfony 2, but we are running Symfony 3.3, so some things are outdated and I have not been able to get the example running yet.
Code
So, I have posted some of the relevant code below. (I obviously cannot post the whole code, but have posted what are hopefully the relevant portions of the publicly-available code).
services.yml (Their version, Symfony 2 Style)
api_exception_subscriber:
class: AppBundle\EventListener\ApiExceptionSubscriber
arguments: []
tags:
- { name: kernel.event_subscriber }
services.yml (my full file with all comments removed)
This includes a modified version of what they have above (hopefully this is the correct Symfony 3.3 way of doing things).
NOTE: Anything that was part of the private code which I cannot show, I have replaced with the word "something".
parameters:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
AppBundle\:
resource: '../../src/AppBundle/*'
exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller'
public: true
tags: ['controller.service_arguments']
AppBundle\EventListener\ApiExceptionSubscriber:
arguments:
- ['%something.something%']
tags:
- {name: 'kernel.event_subscriber'}
routing.yml (relevant section of their file)
app_api:
resource: "#AppBundle/Controller/Api"
type: annotation
defaults:
_format: json
routing.yml (my full file) - NOTE: I had to add the "_format: json" directly to the "app" section here rather than "app_api" because in our REST API, all of our URLs are at the root level, and do NOT have to be prefixed with "api" like http://localhost/api/someMethod/someMethodParameter as in the tutorial's code
app:
resource: '#AppBundle/Controller/'
type: annotation
defaults: {_format:json}
yml_route:
path: /yml-route
defaults:
_controller: AppBundle:Default:yml
awesome_route:
path: /awesome-route/{ic}
defaults:
_controller: AppBundle:Rest:awesomeRoute
src/AppBundle/RestController.php (edited to show just the basic structure)
<?php
namespace AppBundle\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\HttpFoundation\Request;
class RestController extends Controller {
public function doSomething($id)
{
// Code to populate $result with data from database is here
return new JsonResponse($result);
}
// This file contains many different functions similar to doSomething() which retrieve the request for the API caller.
// For example, doSomething() can be accessed via http://localhost/app_dev.php/doSomething/123
}
src/AppBundle/Api/ApiProblem.php (edited to show just the basic structure)
namespace AppBundle\Api;
use Symfony\Component\HttpFoundation\Response;
class ApiProblem
{
// Code relevant to this class is in here
}
src/AppBundle/Api/ApiProblemException.php (edited to show just the basic structure)
<?php
namespace AppBundle\Api;
use Symfony\Component\HttpKernel\Exception\HttpException;
class ApiProblemException extends HttpException
{
private $apiProblem;
public function __construct($severalParametersWhichICannotListHereBecauseCodeIsPrivate) {
// Does some stuff and then calls the parent:__construct
// Includes a getter for $apiProblem
}
}
src/AppBundle/EventListener/ApiExceptionSubscriber.php (edited to show just the basic structure)
<?php
namespace AppBundle\EventListener;
use AppBundle\Api\ApiProblem;
use AppBundle\Api\ApiProblemException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\KernelEvents;
class ApiExceptionSubscriber implements EventSubscriberInterface
{
// Code relevant to this subscriber is here
}
The Issue
I'm getting the following error when I try to run any type of command from the command-line bin/console:
C:\htdocs\projects\myproject>php bin/console debug:container
PHP Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: T
here is no extension able to load the configuration for "AppBundle\EventListener\ApiExceptionSubscribe
r" (in C:\htdocs\projects\myproject\app/config\services.yml). Looked for namespace "AppBundle\EventListe
ner\ApiExceptionSubscriber", found "framework", "security", "twig", "monolog", "swiftmailer", "doctrin
e", "sensio_framework_extra", "demontpx_parsedown", "doctrine_cache", "doctrine_migrations", "debug",
"web_profiler", "sensio_distribution", "web_server" in C:\htdocs\projects\myproject\vendor\symfony\symfo
ny\src\Symfony\Component\DependencyInjection\Loader\YamlFileLoader.php:644
Stack trace:
#0 C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Loader\
YamlFileLoader.php(614): Symfony\Component\DependencyInjection\Loader\YamlFileLoader->validate(Array,
'C:\\htdocs\\proje...')
#1 C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Loader\
YamlFileLoad in C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\Config\Loader\
FileLoader.php on line 179
Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: There
is no extension able to load the configuration for "AppBundle\EventListener\ApiExceptionSubscriber" (i
n C:\htdocs\projects\myproject\app/config\services.yml). Looked for namespace "AppBundle\EventListener\A
piExceptionSubscriber", found "framework", "security", "twig", "monolog", "swiftmailer", "doctrine", "
sensio_framework_extra", "demontpx_parsedown", "doctrine_cache", "doctrine_migrations", "debug", "web_
profiler", "sensio_distribution", "web_server" in C:\htdocs\projects\myproject\vendor\symfony\symfony\sr
c\Symfony\Component\Config\Loader\FileLoader.php on line 179
Symfony\Component\Config\Exception\FileLoaderLoadException: There is no extension able to load the con
figuration for "AppBundle\EventListener\ApiExceptionSubscriber" (in C:\htdoc
fig\services.yml). Looked for namespace "AppBundle\EventListener\ApiExceptio
work", "security", "twig", "monolog", "swiftmailer", "doctrine", "sensio_fra
arsedown", "doctrine_cache", "doctrine_migrations", "debug", "web_profiler",
eb_server" in C:\htdocs\projects\myproject\app/config\services.yml (which is b
ocs\projects\myproject\app/config\config.yml"). in C:\htdocs\projects\myproject\
\Symfony\Component\Config\Loader\FileLoader.php on line 179
Call Stack:
1.4353 6149416 1. Symfony\Component\Debug\ErrorHandler->handleExcep
myproject\vendor\symfony\symfony\src\Symfony\Component\Debug\ErrorHandler.php:
What I've Tried
I've been debugging this for the last several days and have read many related discussions on Stack Overflow. I'm fairly new to services, subscribers, and dependency injection and I've tried editing both the routes.yml and services.yml numerous times. I was also getting some circular reference exceptions before but think I've fixed those now. I was hoping someone could please provide me with some direction and hopefully help me turn this into a working example on Symfony 3.3 that I can learn from. If you need any additional detail, please let me know.
From what I've learned, autowiring/autoconfiguring of services in Symfony 3.3 seems to be new and I think that may be impacting things but I'm not sure. I did try turning both of those settings off in services.yml though but with no luck.

Symfony2 hold behavior when extending DefaultAuthenticationSuccessHandler

I want to be able to login in my app via the usual login form and using AJAX directly sending the user/password to the login_check path.
The idea is when user access via AJAX return Response with code 200 or 400 depending if the login success or fails.
Looking at other threads I finally decide to extend the default handlers DefaultAuthenticationSuccessHandler and DefaultAuthenticationFailureHandler to achieve this, export as services and specify in the success_handler property in my secure area.
File service.yml
services:
authentication.success_handler:
class: %mycustom.authentication.success_handler.class%
arguments: ['#security.http_utils', {} ]
public: false
tags:
- { name: 'monolog.logger', channel: 'security' }
authentication.failure_handler:
class: %mycustom.authentication.failure_handler.class%
arguments: ['#http_kernel', '#security.http_utils', {}, '#logger' ]
public: false
tags:
- { name: 'monolog.logger', channel: 'security' }
File security.yml
secured_meems_area:
pattern: ^/somrurl/
form_login:
login_path: /somrurl/login
check_path: /somrurl/api/login_check
success_handler: authentication.success_handler
failure_handler: authentication.failure_handler
require_previous_session: false
All this seems to work, except the behaviour of my extendend handler isn't like the original one. In the default implementation used by Symfony if you access a page/A and you are not logged on, Symfony redirects to the login page and after it you are redirected again to page/A. But this not occurs with my extended handler.
To solve it, I can specify a default_target_path when registering the handler as a service, but I want to understand why it doesn't follow the "normal" behavior.
Any ideas out there.
Thanks in advance.
SOLUTION !!!
After looking and test I found a solution here Symfony2 extending DefaultAuthenticationSuccessHandler
The idea is override the default symfony success/failure handlers instead of define my own and apply in the security.yml file.
File security.yml
secured_meems_area:
pattern: ^/somrurl/
form_login:
login_path: /somrurl/login
check_path: /somrurl/api/login_check
#
# DON'T USE !!!
#
# success_handler: authentication.success_handler
# failure_handler: authentication.failure_handler
#
require_previous_session: false
File service.yml. (NOTE the security. in the service name)
services:
security.authentication.success_handler:
class: %mycustom.authentication.success_handler.class%
arguments: ['#security.http_utils', {} ]
public: false
tags:
- { name: 'monolog.logger', channel: 'security' }
security.authentication.failure_handler:
class: %mycustom.authentication.failure_handler.class%
arguments: ['#http_kernel', '#security.http_utils', {}, '#logger' ]
public: false
tags:
- { name: 'monolog.logger', channel: 'security' }
This way we are overriden the default implementation with our own and don't need to specify the handlers in the security area.