Symfony 6.2 app not working as soon as a Command name is defined - symfony

docker-compose.yml
version: "3"
services:
nginx:
image: nginx:1.23.3
ports:
- "8084:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
php:
build: .
volumes:
- ./api:/var/www/html/
nginx.conf
events {}
http {
server {
root /var/www/html/public;
location / {
try_files $uri /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_pass php:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
}
I installed Symfony Console "symfony/console": "^6.2".
composer.json
{
"require": {
"symfony/runtime": "^6.2",
"symfony/http-kernel": "^6.2",
"symfony/framework-bundle": "^6.2",
"symfony/dotenv": "^6.2",
"doctrine/doctrine-bundle": "^2.8"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"symfony/console": "^6.2"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"config": {
"allow-plugins": {
"symfony/runtime": true
}
}
}
I added a src/cli.php
<?php
require __DIR__.'/../vendor/autoload.php';
use Symfony\Component\Console\Application;
$application = new Application();
$application->add(new \App\Commands\ExtractAuthorPortraitsCommand());
$application->run();
I added a command
<?php declare(strict_types=1);
namespace App\Commands;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ExtractAuthorPortraitsCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
return Command::SUCCESS;
}
}
As soon as I add a name to the command
#[AsCommand(name: 'app:extract-author-portraits')]
class ExtractAuthorPortraitsCommand extends Command
a request to the Symfony app (http://localhost:8084) then gives me an empty response.
And the PHP log shows Console Tool stuff which does not come in the log when Command has no name.
Console Tool
Usage:
command [options] [arguments]
Options:
-h, --help Display help for the given command. When no command is given display help for the list command
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi|--no-ansi Force (or disable --no-ansi) ANSI output
-n, --no-interaction Do not ask any interactive question
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands:
completion Dump the shell completion script
help Display help for a command
list List commands
app
app:extract-author-portraits
172.21.0.3 - 18/Jan/2023:07:28:25 +0000 "GET /index.php" 200
Any ideas?

Related

ERROR Class "User" doesn't exist; please enter an existing full class name. (Symfony)

I'm a noob and my english is very bad but I will try to explain my problem.
I started a new side-project to train in Symfony.
I install multiple composer like : profiler, maker, orm, template...
The first problem :
The metadata storage is not up to date, please run the sync-metadata-storage command to fix this issue.
I solved it with changed the serverVersion into .env.local by : ?serverVersion=10.4.11-MariaDB
The second problem is when I make a Class User with command lign :
php bin/console make:entity User
it's ok but when I want make:auth or make:registrationForm he ask me enter the User class, what I do, and I have always the same error:
[ERROR] Class "User" doesn't exist; please enter an existing full class name.
My command lign looks like:
updated: src/Entity/User.php
Add another property? Enter the property name (or press <return> to stop adding fields):
>
Success!
Next: When you're ready, create a migration with php bin/console make:migration
frede#DESKTOP-M7PFMDG /c/xampp/htdocs/side_project/01-rpg_builder (registration)
λ php bin/console make:migration
Success!
Next: Review the new migration "migrations/Version20200625073423.php"
Then: Run the migration with php bin/console doctrine:migrations:migrate
See https://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html
frede#DESKTOP-M7PFMDG /c/xampp/htdocs/side_project/01-rpg_builder (registration)
λ php bin/console doctrine:migrations:migrate
WARNING! You are about to execute a database migration that could result in schema changes and data loss. Are you sure you wish to continue? (yes/no) [yes]:
>
[notice] Migrating up to DoctrineMigrations\Version20200625073423
[notice] finished in 91.2ms, used 18M memory, 1 migrations executed, 1 sql queries
frede#DESKTOP-M7PFMDG /c/xampp/htdocs/side_project/01-rpg_builder (registration)
λ php bin/console make:auth
What style of authentication do you want? [Empty authenticator]:
[0] Empty authenticator
[1] Login form authenticator
> 1
1
The class name of the authenticator to create (e.g. AppCustomAuthenticator):
> AppAuthenticator
Choose a name for the controller class (e.g. SecurityController) [SecurityController]:
>
Enter the User class that you want to authenticate (e.g. App\Entity\User) []:
> User
[ERROR] Class "User" doesn't exist; please enter an existing full class name.
I have never had this kind of problem before. I think it's since update doctrine-migrations-bundle "2.1.2" to "3.0.1"
composer.json:
{
"type": "project",
"license": "proprietary",
"require": {
"php": "^7.2.5",
"ext-ctype": "*",
"ext-iconv": "*",
"sensio/framework-extra-bundle": "^5.5",
"symfony/asset": "5.1.*",
"symfony/console": "5.1.*",
"symfony/dotenv": "5.1.*",
"symfony/flex": "^1.8",
"symfony/framework-bundle": "5.1.*",
"symfony/orm-pack": "^1.0",
"symfony/profiler-pack": "^1.0",
"symfony/security-bundle": "5.1.*",
"symfony/twig-pack": "^1.0",
"symfony/validator": "5.1.*",
"symfony/yaml": "5.1.*"
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.3",
"symfony/maker-bundle": "^1.19"
},
"config": {
"optimize-autoloader": true,
"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.1.*"
}
}
}
doctrine_migrations.yaml:
doctrine_migrations:
migrations_paths:
# namespace is arbitrary but should be different from App\Migrations
# as migrations classes should NOT be autoloaded
'DoctrineMigrations': '%kernel.project_dir%/migrations'
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
thank you very much for reading me.
Obviously I wrong create my entity User.
I make:entity User instead of make:user

autoconfigure not tagging commands with symfony dependency-injection

I have a cli project that I am using Symfony's Dependency Injection and Console components. I am not using a Kernel, controllers, etc.
When using autoconfigure: true, the service doesn't get the console.command tag it is supposed to.
My composer.json:
{
"require": {
"php": "^7.4",
"monolog/monolog": "^2.0",
"symfony/console": "^5.0",
"symfony/dependency-injection": "^5.0",
"symfony/config": "^5.0",
"symfony/yaml": "^5.0"
},
"autoload": {
"psr-4": {"Mudder\\": "src/"}
}
}
./config/services.yaml:
services:
_defaults:
autowire: true
autoconfigure: true
Mudder\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
public: true
./src/Mudder/Command/HelloWorld.php:
<?php
namespace Mudder\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class HelloWorld extends Command
{
protected static string $defaultName = 'test';
protected function configure()
{
$this->setDescription('Foo');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('Hello, world.');
return 0;
}
}
Finally, ./test.php (the cli entrypoint):
<?php
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
$containerBuilder = new ContainerBuilder();
$loader = new YamlFileLoader($containerBuilder, new FileLocator(__DIR__ . '/config'));
$loader->load('services.yaml');
$containerBuilder->compile();
print_r($containerBuilder->getDefinition(\Mudder\Command\HelloWorld::class)->getTags());
Output from the print_r() is an empty array "Array()"
The container itself does know nothing about a Command.
If you want to auto configure your commands, you have to call
$containerBuiler->registerForAutoconfiguration(Command::class)->addTag('console.command');
or load the FrameworkExtension (from symfony FrameworkBundle)
Your command should end with Command. Rename it to HelloWorldCommand.

Doctrine annotations are not loaded during execution of Behat context

I use Symfony 2.8 and Behat 3.3. I have standard FeatureContext class in project_root/features/bootstrap directory. Before scenario execution I want purge DB like that:
/**
* #BeforeScenario
*/
public function beforeScenario()
{
// use Doctrine\Common\DataFixtures\Purger\ORMPurger
$purger = new ORMPurger($this->em);
$purger->purge();
}
But when I execute test I receive error:
The annotation "#Doctrine\ORM\Mapping\Entity" in class XXX does not
exist, or could not be auto-loaded.
My behat.yml is:
default:
suites:
default:
contexts:
- FeatureContext:
em: '#doctrine.orm.entity_manager'
extensions:
Behat\Symfony2Extension:
kernel:
bootstrap: "vendor/autoload.php"
env: "test"
debug: "true"
composer.json autoload section:
"autoload": {
"psr-4": {
"": "src/"
},
"classmap": [
"app/AppKernel.php",
"app/AppCache.php"
]
}
If remove line bootstrap: "vendor/autoload.php" from behat.yml, everything will work as needed.

Cannot load custom bundle in Sylius?

I want to create my own bundles in Sylius. I created in the directory src and named App like that
src
Sylius
.......
App
Bundle
ShopBundle
AppShopBundle.php
In this file, I wrote very simple:
namespace App\Bundle\ShopBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AppShopBundle extends Bundle
{
}
And I registered this bundle in AppKernel.php
$bundles = array(
new App\Bundle\ShopBundle\AppShopBundle()
);
But when I run the site, I have an exception. I don't understand the problem here, anyone can help me ?
ClassNotFoundException in AppKernel.php line 28:
Attempted to load class "AppShopBundle" from namespace "App\Bundle\ShopBundle".
Did you forget a "use" statement for "App\Bundle\ShopBundle\AppShopBundle"?
You should edit composer.json file to autoload your new bundle
"autoload": {
"psr-0": { "": "src/" }
}
Then run composer dump-autoload in terminal
Tuan's approach worked for me. In my case my composer.json autoload equals:
"autoload": {
"psr-0": { "Sylius\\": "src/", "App\\": "src/" }
},
and then you'll want to clear cache after running 'composer dump-autoload'
php app/console cache:clear --env=dev
While Tuan's answer will work, it uses psr-0. Adding an updated answer for psr-4 support.
Change your composer.json's autoload configuration to load the whole source directory like so:
"autoload": {
"psr-4": {
"": "src/"
}
}

Testing a symfony 2.1 project using behat and mink

I'm trying to use Behat and Mink to test a symfony 2.1 project.
My FeatureContext.php:
<?php
use Behat\Behat\Context\ClosuredContextInterface,
Behat\Behat\Context\BehatContext,
Behat\Behat\Exception\PendingException,
Behat\Behat\Context\Step;
use Behat\Gherkin\Node\PyStringNode,
Behat\Gherkin\Node\TableNode;
use Behat\MinkExtension\Context\MinkContext;
//
// Require 3rd-party libraries here:
//
// require_once 'PHPUnit/Autoload.php';
// require_once 'PHPUnit/Framework/Assert/Functions.php';
//
/**
* Features context.
*/
class FeatureContext extends Behat\MinkExtension\Context\MinkContext {
/**
* Initializes context.
* Every scenario gets it's own context object.
*
* #param array $parameters context parameters (set them up through behat.yml)
*/
public function __construct(array $parameters)
{
// Initialize your context here
}
//
// Place your definition and hook methods here:
//
// /**
// * #Given /^I have done something with "([^"]*)"$/
// */
// public function iHaveDoneSomethingWith($argument)
// {
// doSomethingWith($argument);
// }
//
}
composer.json
"behat/behat": ">=2.2.2",
"behat/mink": ">=1.3.2",
"behat/symfony2-extension": "*",
"behat/mink-extension": "*",
"behat/mink-browserkit-driver": "*",
"behat/mink-selenium-driver": "*"
app/config/behat.yml
default:
extensions:
Behat\Symfony2Extension\Extension:
mink_driver: true
kernel:
env: test
debug: true
Behat\MinkExtension\Extension:
base_url: 'http://localhost:8080/app_test.php/'
default_session: symfony2
javascript_session: selenium
selenium:
host: 127.0.0.1
port: 4444
When I do ./bin/behat I get:
Feature: Login
In order to login
As a user
I need to be able to validate the username and password
Scenario: Link to login page # features/login.feature:7
PHP Fatal error: Call to a member function getSession() on a non-object in vendor/behat/mink-extension/src/Behat/MinkExtension/Context/RawMinkContext.php on line 81
Fatal error: Call to a member function getSession() on a non-object in vendor/behat/mink-extension/src/Behat/MinkExtension/Context/RawMinkContext.php on line 81
Any idea?
v.
Your behat.yml should not be located in app/config/behat.yml , but in your/project/root/behat.yml
Thanks for #Stuart and #spiritoo answers here.
Firstly, move the behat.yml from /config to project root.
Secondly, content for the behat.yml:
default:
suites:
my_suite:
contexts:
- FeatureContext
extensions:
Behat\Symfony2Extension: ~
Behat\MinkExtension:
base_url: http://en.wikipedia.org
goutte: ~
sessions:
default:
symfony2: ~
Finally, in project root, run:
vendor/bin/behat features/{YOUR TEST FILE HERE}
My composer.json file:
"require-dev": {
"behat/behat": "^3.3",
"behat/mink": "^1.7",
"behat/mink-extension": "^2.2",
"behat/mink-browserkit-driver": "^1.3",
"behat/mink-goutte-driver": "^1.2",
"behat/symfony2-extension": "^2.1",
"behat/mink-selenium2-driver": "^1.3"
}

Resources