No configured handlers in Symfony Messenger - php

I'd like to implement Messenger async handlers and be able to queue some tasks in Redis, but I can't for some reason.
Here is my global config :
PHP 7.3.16
Symfony 4.4.7
Messenger 4.4
Redis 5.0.3
Predis 1.1
I tried to follow this guide :
https://symfony.com/doc/4.4/messenger.html
Everything is a copy/paste from the doc, except that I replaced my controller with a command.
This dispatch command seems to work :
php bin/console app:dispatch-command
^ Symfony\Component\Messenger\Envelope^ {#5465 -stamps: []
-message: App\Message\SmsNotification^ {#5475
-content: "Look! I created a message!" } }
This command returns no configured handlers :
php bin/console debug:messenger
Messenger
=========
This second command returns an error while trying to consume a message
php bin/console messenger:consume async
TypeError {#174
#message: "The first argument must be an instance of "Symfony\Component\Messenger\RoutableMessageBus"."
#code: 0
#file: "./vendor/symfony/messenger/Command/ConsumeMessagesCommand.php"
#line: 54
trace: {
./vendor/symfony/messenger/Command/ConsumeMessagesCommand.php:54 { …}
./var/cache/dev/ContainerM8fc2IB/srcApp_KernelDevDebugContainer.php:3736 {
ContainerM8fc2IB\srcApp_KernelDevDebugContainer->getConsole_Command_MessengerConsumeMessagesService()^
›
› $this->privates['console.command.messenger_consume_messages'] = $instance = new \Symfony\Component\Messenger\Command\ConsumeMessagesCommand('', ($this->privates['messenger.receiver_locator'] ?? ($this->privates['messenger.receiver_locator'] = new \Symfony\Component\DependencyInjection\Argument\ServiceLocator($this->getService, [], []))), ($this->services['event_dispatcher'] ?? $this->getEventDispatcherService()), ($this->privates['monolog.logger.messenger'] ?? $this->getMonolog_Logger_MessengerService()), []);
›
arguments: {
$routableBus: ""
$receiverLocator: Symfony\Component\DependencyInjection\Argument\ServiceLocator {#178 …}
$eventDispatcher: Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher {#188 …}
$logger: Symfony\Bridge\Monolog\Logger {#179 …}
$receiverNames: []
}
}
./vendor/symfony/dependency-injection/Container.php:450 { …}
./vendor/symfony/dependency-injection/Argument/ServiceLocator.php:40 { …}
./vendor/symfony/console/CommandLoader/ContainerCommandLoader.php:45 { …}
./vendor/symfony/console/Application.php:541 { …}
./vendor/symfony/console/Application.php:634 { …}
./vendor/symfony/framework-bundle/Console/Application.php:117 { …}
./vendor/symfony/console/Application.php:235 { …}
./vendor/symfony/framework-bundle/Console/Application.php:83 { …}
./vendor/symfony/console/Application.php:147 { …}
./bin/console:42 { …}
}
}
2020-04-20T20:08:02+02:00 [critical] Uncaught Error: The first argument must be an instance of "Symfony\Component\Messenger\RoutableMessageBus".
Here are some relevant files...
# .env
MESSENGER_TRANSPORT_DSN=redis://127.0.0.1:6379/messages/?auto_setup=true&serializer=1&stream_max_entries=0&dbindex=0
# config/packages/messenger.yaml
framework:
messenger:
transports:
async: '%env(MESSENGER_TRANSPORT_DSN)%'
routing:
'App\Message\SmsNotification': async
# config/services.yaml
parameters:
services:
_defaults:
autowire: true
autoconfigure: true
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
<?php
// src/Message/SmsNotification.php
namespace App\Message;
class SmsNotification
{
private $content;
public function __construct(string $content)
{
$this->content = $content;
}
public function getContent(): string
{
return $this->content;
}
}
<?php
// src/MessageHandler/SmsNotificationHandler.php
namespace App\MessageHandler;
use App\Message\SmsNotification;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
class SmsNotificationHandler implements MessageHandlerInterface
{
public function __invoke(SmsNotification $message)
{
dump('ok!');
echo('handler');
}
}
<?php
// src/Command/DispatchCommand
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use App\Message\SmsNotification;
use Symfony\Component\Messenger\MessageBusInterface;
class DispatchCommand extends Command
{
protected $bus;
protected static $defaultName = 'app:dispatch-command';
public function __construct(MessageBusInterface $bus)
{
$this->bus = $bus;
}
protected function configure()
{
$this
->setDescription('Dispatch test command')
->setHelp('Dispatch test command');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$dispatch = $this->bus->dispatch(new SmsNotification('Look! I created a message!'));
dump($dispatch);
}
Can someone please help me?
Cheers!
Update
I tried to manually route my handlers as explained in the doc :
# config/services.yaml
App\MessageHandler\SmsNotificationHandler:
tags: [messenger.message_handler]
But it changes nothing.
I also checked if my message and message Handler were registered as services, and it is :
php bin/console debug:container App
[70 ] App\Message\SmsNotification
[71 ] App\MessageHandler\SmsNotificationHandler

I still don't know what causes this issue, but I just succeeded to resolve it by installing a whole new Symfony 4.4.7 project and by overwriting it.
I also figured out that swiftmailer was replaced by mailer, and twig-bundle by twig-pack, but only for new projects, without beeing notice by composer for existing installations (even using composer update/upgrade/recipes. It may be the cause of my problems but I'm not sure.
Step 1 : create a new Symfony 4.4.7 project
composer create-project symfony/website-skeleton newProj ^4.4.7
sudo chown -R $USER:www-data
cd /newProj
Step 2 : overwrite with my git project
git init
git remote add origin $url_of_clone_source
git fetch origin
git checkout -b master --track origin/master
Step 3 : install vendors and replace obsolete dependencies
composer install
composer remove symfony/swiftmailer
composer require symfony/mailer
composer remove symfony/twig-bundle
composer require symfony/twig-pack
Step 4 : check messenger
$ php bin/console debug:messenger
Messenger
=========
messenger.bus.default
---------------------
The following messages can be dispatched:
----------------------------------------------------------
App\Message\SmsNotification
handled by App\MessageHandler\SmsNotificationHandler
Symfony\Component\Mailer\Messenger\SendEmailMessage
handled by mailer.messenger.message_handler
----------------------------------------------------------
Here is my actual composer.json file
{
"type": "project",
"license": "proprietary",
"require": {
"php": "7.3.*",
"ext-ctype": "*",
"ext-iconv": "*",
"guzzlehttp/guzzle": "^6.5",
"impulze/intervention-image-bundle": "^1.2",
"laminas/laminas-code": "^3.4",
"laminas/laminas-eventmanager": "^3.2",
"nelmio/api-doc-bundle": "^3.6",
"predis/predis": "^1.1",
"sensio/framework-extra-bundle": "^5.1",
"symfony/asset": "4.4.*",
"symfony/console": "4.4.*",
"symfony/dotenv": "4.4.*",
"symfony/error-handler": "4.4.*",
"symfony/expression-language": "4.4.*",
"symfony/flex": "^1.3.1",
"symfony/form": "4.4.*",
"symfony/framework-bundle": "4.4.*",
"symfony/http-client": "4.4.*",
"symfony/intl": "4.4.*",
"symfony/mailer": "4.4.*",
"symfony/messenger": "4.4.*",
"symfony/monolog-bundle": "^3.1",
"symfony/orm-pack": "*",
"symfony/phpunit-bridge": "^5.0",
"symfony/process": "4.4.*",
"symfony/security-bundle": "4.4.*",
"symfony/serializer-pack": "*",
"symfony/translation": "4.4.*",
"symfony/twig-pack": "^1.0",
"symfony/validator": "4.4.*",
"symfony/web-link": "4.4.*",
"symfony/webpack-encore-bundle": "^1.7",
"symfony/yaml": "4.4.*"
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.3",
"sensiolabs/security-checker": "^6.0",
"symfony/debug-pack": "*",
"symfony/maker-bundle": "^1.0",
"symfony/profiler-pack": "*",
"symfony/test-pack": "*"
},
"config": {
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"paragonie/random_compat": "2.*",
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php72": "*",
"symfony/polyfill-php71": "*",
"symfony/polyfill-php70": "*",
"symfony/polyfill-php56": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd",
"security-checker security:check": "script"
},
"post-install-cmd": [
"#auto-scripts"
],
"post-update-cmd": [
"#auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "4.4.*"
}
}
}

Related

Symfonty 6.1 to 6.2 upgrade: Invalid service id in FileLoader

I have recently been trying to upgrade from Symfony 6.1 to 6.2. In doing so though..something appears to have broken. Does anyone have any clue what changed from 6.1 to 6.2? I have tried looking and continue to do so..but I haven't been able to find any meaningful change that breaks it. The setup docs all show the same formatting for all the available files.
I am on PHP 8.1.11
When I update my composer.json to bring everything up to 6.2, the console throws the following error:
Executing script cache:clear [KO]
[KO]
Script cache:clear returned with error code 1
!!
!! In FileLoader.php line 178:
!!
!! Invalid service id: "MyNamespace\" in /var/www/html/config/services.yaml (whic
!! h is being imported from "/var/www/html/src/Kernel.php").
!!
!!
!! In ContainerBuilder.php line 911:
!!
!! Invalid service id: "MyNamespace\".
!!
!!
!!
Script #auto-scripts was called via post-update-cmd
Nothing has changed, and if I change it all back to 6.1 and reupdate composer..it works just fine.
Below is my services.yaml
services:
# 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
MyNamespace\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
- '../vendor/'
- '../var/'
_instanceof:
MyNamespace\Enum\AbstractEnumType:
tags: ['app.doctrine_enum_type']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
I have downgraded back to 6.1, that works.
I have tried renaming or removing parts of my class..that doesn't work.
Update: Here is a copy of my kernel file:
namespace MyNamespace;
use MyNamespace\Enum\AbstractEnumType;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
public function process(ContainerBuilder $container): void
{
$typesDefinition = [];
if ($container->hasParameter('doctrine.dbal.connection_factory.types')) {
$typesDefinition = $container->getParameter('doctrine.dbal.connection_factory.types');
}
$taggedEnums = $container->findTaggedServiceIds('app.doctrine_enum_type');
foreach ($taggedEnums as $enumType => $definition) {
/** #var $enumType AbstractEnumType */
$typesDefinition[$enumType::NAME] = ['class' => $enumType];
}
$container->setParameter('doctrine.dbal.connection_factory.types', $typesDefinition);
}
}
Update 2: I have attached the code for my abstract enum & composer.json
composer.json
{
"type": "project",
"license": "proprietary",
"minimum-stability": "stable",
"prefer-stable": true,
"require": {
"php": ">=8.1",
"ext-ctype": "*",
"ext-curl": "*",
"ext-iconv": "*",
"aws/aws-sdk-php": "^3.252",
"doctrine/annotations": "^1.0",
"doctrine/doctrine-bundle": "^2.7",
"doctrine/doctrine-migrations-bundle": "^3.2",
"doctrine/orm": "^2.13",
"friendsofsymfony/rest-bundle": "^3.4",
"jms/serializer-bundle": "^4.2",
"monolog/monolog": "^3.2",
"nelmio/cors-bundle": "^2.2",
"phpdocumentor/reflection-docblock": "^5.3",
"phpstan/phpdoc-parser": "^1.9",
"ramsey/uuid": "^4.5",
"stripe/stripe-php": "^9.7.0",
"symfony/amazon-mailer": "6.1.*",
"symfony/apache-pack": "^1.0",
"symfony/console": "6.1.*",
"symfony/dom-crawler": "6.1.*",
"symfony/dotenv": "6.1.*",
"symfony/flex": "^2",
"symfony/framework-bundle": "6.1.*",
"symfony/http-client": "6.1.*",
"symfony/maker-bundle": "^1.47",
"symfony/mime": "6.1.*",
"symfony/monolog-bundle": "^3.8",
"symfony/property-access": "6.1.*",
"symfony/property-info": "6.1.*",
"symfony/proxy-manager-bridge": "6.1.*",
"symfony/runtime": "6.1.*",
"symfony/security-bundle": "6.1.*",
"symfony/serializer": "6.1.*",
"symfony/twig-bundle": "6.1.*",
"symfony/yaml": "6.1.*"
},
"config": {
"allow-plugins": {
"composer/package-versions-deprecated": true,
"symfony/flex": true,
"symfony/runtime": true,
"phpstan/extension-installer": true
},
"optimize-autoloader": true,
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"MyNamespace\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"MyNamespace\\Tests\\": "tests/"
}
},
"replace": {
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php72": "*",
"symfony/polyfill-php73": "*",
"symfony/polyfill-php74": "*",
"symfony/polyfill-php80": "*",
"symfony/polyfill-php81": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"#auto-scripts"
],
"post-update-cmd": [
"#auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "6.1.*"
},
"public-dir": "/"
},
"require-dev": {
"phpstan/extension-installer": "^1.1",
"phpstan/phpstan-symfony": "^1.2",
"phpunit/phpunit": "^9.5",
"symfony/browser-kit": "6.1.*",
"symfony/css-selector": "6.1.*",
"symfony/phpunit-bridge": "^6.2",
"symfony/stopwatch": "6.1.*",
"symfony/web-profiler-bundle": "6.1.*"
}
}
AbstractEnumType.php
namespace MyNamespace\Enum;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\StringType;
abstract class AbstractEnumType extends StringType
{
abstract public static function getEnumClass(): string;
public function getName(): string
{
throw new \Exception('getName should be overwritten by child class');
}
public function convertToPHPValue($value, AbstractPlatform $platform): ?\BackedEnum
{
if($value instanceof \BackedEnum){
return $value;
}
$value = parent::convertToPHPValue($value, $platform);
if($value === null){
return null;
}
// 🔥 https://www.php.net/manual/en/backedenum.tryfrom.php
return $this::getEnumClass()::tryFrom($value);
}
public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string
{
return $value?->value;
}
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform): string
{
return 'TEXT';
}
}

Symfony autowire/autoconfigure not working

I created a symfony 5.3 api.
My plan is to inject the "EntityManager" via "EntityManagerInterface".
Error that comes:
Could not resolve argument $entityManager of "app\controller\createuseraccountcontroller()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?
My services.yaml
parameters:
services:
# 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/'
My CreateUserAccountController.php in src/Controller/:
<?php
declare(strict_types=1);
namespace App\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class CreateUserAccountController
{
private EntityManagerInterface $entityManager;
function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
#[Route('/user/create', name: 'create_user_account')]
public function __invoke(): Response
{
return new Response('hello world');
}
}
My composer.json:
{
"type": "project",
"license": "proprietary",
"minimum-stability": "stable",
"prefer-stable": true,
"require": {
"php": "8.0.*",
"ext-ctype": "*",
"ext-iconv": "*",
"composer/package-versions-deprecated": "1.11.99.2",
"doctrine/doctrine-bundle": "^2.4",
"doctrine/doctrine-migrations-bundle": "^3.1",
"doctrine/orm": "^2.9",
"phpseclib/phpseclib": "^3.0",
"symfony/console": "5.3.*",
"symfony/dependency-injection": "5.3.*",
"symfony/dotenv": "5.3.*",
"symfony/flex": "^1.3.1",
"symfony/framework-bundle": "5.3.*",
"symfony/proxy-manager-bridge": "5.3.*",
"symfony/runtime": "5.3.*",
"symfony/yaml": "5.3.*"
},
"require-dev": {
"symfony/maker-bundle": "^1.31",
"symfony/stopwatch": "5.3.*"
},
"config": {
"optimize-autoloader": true,
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php72": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"#auto-scripts"
],
"post-update-cmd": [
"#auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "5.3.*"
}
}
}
I know that I dont use the Manager, but it doesn´t work for me.
The webserver I use: symfony cli webserver
Has anyone a idea, where the problem is?
This is actually a somewhat interesting edge case.
The bottom line is that autowire is defining your controller service as private. This in turn means the controller resolver is simply new'ing the controller instead of pulling it from the container. Hence the missing argument error messages.
Notice that your controller does not extend AbstractController. If it did then autoconfigure would know that it is a controller and end up making it public. All would be well.
Prior to 5.3, the services.yaml file contained:
App\Controller\:
resource: '../src/Controller/'
tags: ['controller.service_arguments']
Those lines would automatically define anything in the controller directory as a controller. Most of the time they were not needed since most controllers extend AbstractController. Which is why the lines ended up being dropped in 5.3.
So if you really don't want to extend AbstractController then add those lines back in. You can use bin/console debug:container CreateUserAccountController to see what is happening.
Finally, you also have the option of simply manually defining your controller service as public. Something like:
services:
App\Controller\CreateUserAccountController:
public: true
tags: ['controller.service_arguments'] # optional

Argument 1 passed to DoctrineDataCollector::__construct() must be an instance of Doctrine\Common\Persistence\ManagerRegistry

I am developing a Symfony project which somebody else started on and I was happy that I had it up and running. Unfortunatelly after running composer update today, the Symfony page that I have throws an error.
After running composer update the following error was displayed:
Composer update error
Executing script cache:clear [KO]
[KO]
Script cache:clear returned with error code 255
!! Symfony\Component\ErrorHandler\Error\ClassNotFoundError {#132
!! #message: """
!! Attempted to load class "MappingDriverChain" from namespace "Doctrine\Common\Persistence\Mapping\Driver".\n
!! Did you forget a "use" statement for "Doctrine\Persistence\Mapping\Driver\MappingDriverChain"?
!! """
!! #code: 0
!! #file: "./var/cache/dev/ContainerFcUQG2T/App_KernelDevDebugContainer.php"
!! #line: 869
!! trace: {
!! ./var/cache/dev/ContainerFcUQG2T/App_KernelDevDebugContainer.php:869 {
!! ContainerFcUQG2T\App_KernelDevDebugContainer->getDoctrine_Orm_DefaultEntityManagerService($lazyLoad = true)
!! ›
!! › $b = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
!! › $b->addDriver(new \Doctrine\ORM\Mapping\Driver\AnnotationDriver(($this->privates['annotations.cached_reader'] ?? $this->getAnnotations_CachedReaderService()), [0 => (\dirname(__DIR__, 4).'/src/Entity')]), 'App\\Entity');
!! }
!! ./var/cache/dev/ContainerFcUQG2T/App_KernelDevDebugContainer.php:5160 { …}
!! ./var/cache/dev/ContainerFcUQG2T/App_KernelDevDebugContainer.php:5204 { …}
!! ./var/cache/dev/ContainerFcUQG2T/App_KernelDevDebugContainer.php:569 { …}
!! ./vendor/symfony/http-kernel/CacheWarmer/CacheWarmerAggregate.php:87 { …}
!! ./vendor/symfony/http-kernel/Kernel.php:553 { …}
!! ./vendor/symfony/http-kernel/Kernel.php:126 { …}
!! ./vendor/symfony/framework-bundle/Console/Application.php:168 { …}
!! ./vendor/symfony/framework-bundle/Console/Application.php:74 { …}
!! ./vendor/symfony/console/Application.php:140 { …}
!! ./bin/console:42 { …}
!! }
!! }
!! 2020-07-31T08:18:05+00:00 [critical] Uncaught Error: Class 'Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain' not found
!!
After accessing the Symfony page, this TypeError was printed:
TypeError
Argument 1 passed to Doctrine\Bundle\DoctrineBundle\DataCollector\DoctrineDataCollector::__construct() must be an instance of Doctrine\Common\Persistence\ManagerRegistry, instance of Doctrine\Bundle\DoctrineBundle\Registry given, called in /var/www/html/mgo/var/cache/dev/ContainerFcUQG2T/App_KernelDevDebugContainer.php on line 1176
To be honest I have no idea what caused this issue, but I think it has nothing to do with the changes I made in the twig and Symfony php files of the project.
I'll add some files, if there is anything else that I should be looking into, let me know.
/config/packages/doctrine.yaml
doctrine:
dbal:
url: '%env(resolve:DATABASE_URL)%'
# IMPORTANT: You MUST configure your server version,
# either here or in the DATABASE_URL env var (see .env file)
#server_version: '5.7'
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
auto_mapping: true
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
composer.json
{
"name": "project",
"description": "project description",
"type": "path",
"license": "MIT",
"minimum-stability": "dev",
"require": {
"php": "^7.4",
"ext-ctype": "*",
"ext-iconv": "*",
"mgo/mgo-client-php": "2.0.0",
"sensio/framework-extra-bundle": "^5.1",
"symfony/asset": "5.0.*",
"symfony/console": "5.0.*",
"symfony/dotenv": "5.0.*",
"symfony/expression-language": "5.0.*",
"symfony/flex": "^1.3.1",
"symfony/form": "5.0.*",
"symfony/framework-bundle": "5.0.*",
"symfony/http-client": "5.0.*",
"symfony/intl": "5.0.*",
"symfony/mailer": "5.0.*",
"symfony/monolog-bundle": "^3.1",
"symfony/notifier": "5.0.*",
"symfony/orm-pack": "*",
"symfony/process": "5.0.*",
"symfony/security-bundle": "5.0.*",
"symfony/serializer-pack": "*",
"symfony/string": "5.0.*",
"symfony/translation": "5.0.*",
"symfony/twig-pack": "*",
"symfony/validator": "5.0.*",
"symfony/web-link": "5.0.*",
"symfony/yaml": "5.0.*",
"ext-json": "*"
},
"repositories": [
{
"type": "path",
"url": "/home/*user*/mgo-client-php",
"symlink": false
}
],
"require-dev": {
"symfony/debug-pack": "*",
"symfony/maker-bundle": "^1.0",
"symfony/profiler-pack": "*",
"symfony/test-pack": "*",
"mgo-client-php": "2.0.0",
"monolog/monolog": "^1.23"
},
"config": {
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"paragonie/random_compat": "2.*",
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php72": "*",
"symfony/polyfill-php71": "*",
"symfony/polyfill-php70": "*",
"symfony/polyfill-php56": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"#auto-scripts"
],
"post-update-cmd": [
"#auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "5.0.*"
}
}
}
EDIT:
As #Alexandre Tranchant suggested I removed my /var/cache file to get the original error. The error that pops up is the following:
Attempted to load class "MappingDriverChain" from namespace "Doctrine\Common\Persistence\Mapping\Driver".
Did you forget a "use" statement for "Doctrine\Persistence\Mapping\Driver\MappingDriverChain"?
It's correct there is no link with your update on twig files.
As your composer.json file doesn't fix the doctrine version, it upgraded your doctrine package version. In the newest version of Doctrine, the pattern of repository files have change.
There is 2 solutions:
Solution1 (Not tested and not recommended): you fix the doctrine package by adding it in the composer.json. You can have a look on the old composer.lock of your application. This isn't the best solution. (But it's only my opinion)
Solution2: Upgrade your files to be compliant with the new version of doctrine.
I see three major steps:
Update the configuration file by updating recipes.
Update the declaration of repositories (see below)
Update fixtures files. (but I don't see fixtures in your composer files)
So, I guess that you have to upgrade your repositories declaration.
Here is the new pattern of a repository
#src/Repository/Foo.php
use App\Entity\Foo;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\Persistence\ManagerRegistry;
/**
* Some repository coded in the new way.
*
* #method Article|null find($id, $lockMode = null, $lockVersion = null)
* #method Article|null findOneBy(array $criteria, array $orderBy = null)
* #method Article[] findAll()
* #method Article[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ArticleRepository extends ServiceEntityRepository
{
/**
* FooRepository constructor.
*
* #param ManagerRegistry $registry injected by dependency injection
*/
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Foo::class);
}
If you don't use repositories, you have to find where in your code you was using Doctrine\Bundle\DoctrineBundle\Registry and find a way to replace it by the new ManagerRegistry.

Symfony unit testing

Following is my directory structure:
|-vendor
|---bin
|---phpunit
|---autoload.php
|---psr
|---sebastian
|---phar-io
|---composer
|---symfony
|-.htaccess
|-composer.lock
|-includes
|---application_top.php
|-routes
|---routes.php
|-modules
|---Controllers
|----CheckoutGatewayController.php
|-tests
|---Controllers
|----tests_common_includes.php
|-composer.phar
I am trying to run ./vendor/bin/simple-phpunit --bootstrap tests/tests_common_includes.php tests/Controllers/CheckoutGatewayTests.php from my base directory but it gives me error Class 'tests/Controllers/CheckoutGatewayTests' could not be found in 'tests/Controllers/CheckoutGatewayTests.php'.
If I try ./vendor/bin/phpunit --bootstrap tests/tests_common_includes.php tests/Controllers/CheckoutGatewayTests.php then I get the error Unable to guess the Kernel directory. I tried to look up symfony's documentation : it suggests using either -c app option or changing phpunit.dist.xml file. But I have neither of those in my directory. There is no xml file and no app folder.
How can I execute my tests? My test file CheckoutGatewayTests.php looks like this :
<?php
use \Controllers\CheckoutGatewayController;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class CheckoutGatewayTests extends WebTestCase {
public function testChargebackCallback() {
$client = static::createClient();
$client->request('GET', '/post/hello-world');
}
}
Edit: my composer.json file
{
"require": {
"guzzlehttp/guzzle": "~6.0",
"psr/log": "^1.0",
"zircote/swagger-php": "^2.0",
"sentry/sentry": "^1.8",
"aws/aws-sdk-php": "^3.52",
"league/flysystem-aws-s3-v3": "~1.0",
"symfony/routing": "^3.4",
"symfony/http-kernel": "^3.4",
"symfony/dependency-injection": "^3.4",
"symfony/framework-bundle": "^3.4",
"prbdias/mbway-php": "0.1"
},
"require-dev": {
"phpunit/phpunit": "^6"
},
"config": {
"optimize-autoloader": true
},
"autoload": {
"psr-4": {
"": ["modules/", "tests/","routes/"]
}
}
}

Symfony 4 make:entity --regenerate fail with: No entities were found in the "App" namespace

from composer.json
{
"name": "symfony/website-skeleton",
"type": "project",
"license": "MIT",
"description": "A skeleton to start a new Symfony website",
"require": {
"php": "^7.1.3",
"ext-iconv": "*",
"sensio/framework-extra-bundle": "^5.1",
"symfony/apache-pack": "^1.0",
"symfony/asset": "^4.0",
"symfony/console": "^4.0",
"symfony/expression-language": "^4.0",
"symfony/flex": "^1.0",
"symfony/form": "^4.0",
"symfony/framework-bundle": "^4.0",
"symfony/lts": "^4#dev",
"symfony/monolog-bundle": "^3.1",
"symfony/orm-pack": "^1.0",
"symfony/process": "^4.0",
"symfony/security-bundle": "^4.0",
"symfony/serializer-pack": "*",
"symfony/swiftmailer-bundle": "^3.1",
"symfony/translation": "^4.0",
"symfony/twig-bundle": "^4.0",
"symfony/validator": "^4.0",
"symfony/web-link": "^4.0",
"symfony/webpack-encore-pack": "*",
"symfony/yaml": "^4.0"
},
"require-dev": {
"symfony/browser-kit": "^4.0",
"symfony/css-selector": "^4.0",
"symfony/debug-pack": "*",
"symfony/dotenv": "^4.0",
"symfony/maker-bundle": "^1.5",
"symfony/phpunit-bridge": "^4.0",
"symfony/profiler-pack": "*",
"symfony/web-server-bundle": "^4.0"
},
"config": {
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php71": "*",
"symfony/polyfill-php70": "*",
"symfony/polyfill-php56": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install --symlink --relative %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"#auto-scripts"
],
"post-update-cmd": [
"#auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false
}
}
}
from doctrine.yaml:
# /config/packages/doctrine.yaml
doctrine:
dbal:
default_connection: training
connections:
training:
dbname: "training"
driver: "pdo_mysql"
host: "localhost"
port: "3306"
user: "userdb"
password: "XXXXXXXXXX"
charset: UTF8
mapping_types:
bit: boolean
orm:
auto_generate_proxy_classes: "%kernel.debug%"
default_entity_manager: training
entity_managers:
training:
connection: training
auto_mapping: true
the command:
php bin/console doctrine:mapping:import --em=training App\Entity annotation --path=src/Entity
produce into src/Entity the Course.php entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Course
*
* #ORM\Table(name="course", indexes={#ORM\Index(name="id_product_idx_1", columns={"id_product"}), #ORM\Index(name="enabled_idx_1", columns={"enabled"}), #ORM\Index(name="sort_idx_1", columns={"sort"})})
* #ORM\Entity
*/
class Course
{
....
after run into the console:
php bin/console make:entity --regenerate App
this fail with error:
No entities were found in the "App" namespace
same for
php bin/console make:entity --regenerate App\Entity
if i try
php bin/console make:entity --regenerate App\Entity\Course
the output is
Could not find Doctrine metadata for "App\Entity\Course". Is it mapped as an entity?
what i'm doing wrong?
In my case it was because I wrote:
php bin/console make:entity --regenerate App\Entity\Course
instead of (notice double back slashes)
php bin/console make:entity --regenerate App\\Entity\\Course
Look to config/packages/doctrine.yaml
dir: '%kernel.project_dir%/src/Entity'
Thats the problem. Every .orm.yml is searching in that path.
i have the same error and the fix that i find is to adding repositoryClass to all of my entities:
#ORM\Entity(repositoryClass="App\Repository\DefaultRepository")
The final code is like this:
/**
* Key
*
* #ORM\Table(name="`key`")
* #ORM\Entity(repositoryClass="App\Repository\DefaultRepository")
*/
Hope it help to you
Inside app/config/packages/doctrine.yaml
...
doctrine:
...
orm:
default_entity_manager: default
auto_generate_proxy_classes: '%kernel.debug%'
entity_managers:
default:
naming_strategy: doctrine.orm.naming_strategy.underscore
connection: default
#ADD THESE LINES AND CHANGE PATH IF NEEDED
mappings:
App:
type: annotation
dir: '%kernel.project_dir%/src/Entity/'
prefix: 'App\Entity\'
Run php bin/console make:entity --regenerate
Inside your entity classes, make sure the namespace is well written like this: namespace App\Entity

Categories