Symfony 4 and fos user bundle not working - symfony

I'm new to Symfony. I've installed version 4 and fos user bundle 2.0. I want to override the default registration type and i added my own validations on fields but they are not considered. I tried to use validation on entity and it doesn't work.
Here is my json is here:
{
"type": "project",
"license": "proprietary",
"require": {
"php": "^7.1.3",
"ext-ctype": "*",
"ext-iconv": "*",
"cayetanosoriano/hashids-bundle": "^1.1",
"friendsofsymfony/user-bundle": "~2.0",
"gregwar/image-bundle": "^3.0",
"hashids/hashids": "~1.0",
"nexmo/client": "^2.0",
"odolbeau/phone-number-bundle": "^1.3",
"passwordlib/passwordlib": "^1.0#beta",
"sensio/framework-extra-bundle": "^5.5",
"symfony/asset": "4.4.*",
"symfony/console": "4.4.*",
"symfony/dotenv": "4.4.*",
"symfony/flex": "^1.3.1",
"symfony/form": "4.4.*",
"symfony/framework-bundle": "4.4.*",
"symfony/intl": "4.4.*",
"symfony/mailer": "4.4.*",
"symfony/messenger": "4.4.*",
"symfony/monolog-bundle": "^3.5",
"symfony/options-resolver": "4.4.*",
"symfony/security-bundle": "4.4.*",
"symfony/security-core": "4.4.*",
"symfony/security-csrf": "4.4.*",
"symfony/security-guard": "4.4.*",
"symfony/security-http": "4.4.*",
"symfony/translation": "4.4.*",
"symfony/twig-bundle": "4.4.*",
"symfony/twig-pack": "^1.0",
"symfony/yaml": "4.4.*",
"twig/cssinliner-extra": "^3.0",
"twig/extensions": "^1.5",
"twig/inky-extra": "^3.0"
},
"require-dev": {
"symfony/phpunit-bridge": "^5.0",
"symfony/profiler-pack": "^1.0"
},
"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-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": "4.4.*"
}
}
}
My config file
fos_user:
db_driver: orm # other valid values are 'mongodb' and 'couchdb'
firewall_name: main
user_class: App\Entity\User\User
from_email:
address: "contact#flyout0.com"
sender_name: "Josaphat Imani"
service:
mailer: fos_user.mailer.twig_swift
# user_manager: custom_user_manager
# class: App\Repository\User\UserRepository
# arguments: ['#fos_user.util.password_updater', '#fos_user.util.canonical_fields_updater', '#doctrine.orm.entity_manager', sApp\Entity\User\User]
registration:
# confirmation:
# enabled: true
# from_email:
# address: "contact#flyout0.com"
# sender_name: "Josaphat Imani"
form:
type: App\Form\Type\User\RegistrationType
name: app_user_registration
My registration form
class RegistrationType extends AbstractType
{
protected $countryRepository;
protected $realCountry;
protected $currentCountry;
public function __construct(CountryRepository $m, SessionInterface $session)
{
$this->countryRepository = $m;
$this->realCountry = $session->get('realCity')->getCountry();
$this->currentCountry = $session->get('city')->getCountry();
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('names', TextType::class, [
'constraints' => [
new Assert\Length([
'min' => 3,
'max' => 255,
'minMessage' => 'invalid.names',
'maxMessage' => 'invalid.names'
]),
new ValidName(),
],
'invalid_message' => 'invalid.value',
])
->remove('email')
->add('username', TextType::class, array(
'invalid_message' => 'invalid.username',
'constraints' => [
new Assert\NotBlank(),
new ValidNewUsername()
],
))
->add('plainPassword', PasswordType::class, array(
'invalid_message' => 'invalid.value',
'constraints' => [
new Assert\Length([
'min' => 6,
'minMessage' => 'password.too.low',
'max' => 72,
'maxMessage' => 'password.too.long',
]),
]
))
->addEventSubscriber(new RegistrationSubscriber());
}
public function getParent()
{
return RegistrationFormType::class;
}
public function getBlockPrefix()
{
return 'app_user_registration';
}
}
My entity
<?php
namespace App\Entity\User;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Home\Image;
use Doctrine\ORM\Mapping\AttributeOverrides;
use Doctrine\ORM\Mapping\AttributeOverride;
use libphonenumber\PhoneNumber;
use Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber as AssertPhoneNumber;
use App\Validator\Constraints\User\ValidName;
use App\Validator\Constraints\User\ValidNewUsername;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Constraints as Assert;
use App\Validator\Constraints\User as UserAssert;
/**
* #ORM\Entity(repositoryClass="App\Repository\User\UserRepository")
* #ORM\Table(name="Fos_User")
* #AttributeOverrides({
* #AttributeOverride(name="username",
* column=#ORM\Column(
* name="username",
* type="string",
* length=255,
* unique=false,
* nullable=true
* )
* )
* })
* #UniqueEntity(fields="email", message="email.used")
* #UniqueEntity(fields="telNumber", message="tel.number.used")
* #Assert\Callback(methods={"validateNames"})
*/
class User extends BaseUser
{
/**
* #var int
*
* #ORM\Id
* #ORM\Column(name="id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="names", type="string", length=255)
* #UserAssert\ValidName
* #Assert\Length({"in"="50"})
* #Assert\Choice(
* choices = { "male", "female" },
* message = "Choose a valid gender."
* )
*/
protected $names;
/**
* #var string
*
* #ORM\Column(name="birthday", type="date", nullable=true)
*/
protected $birthday;
public function __construct()
{
parent::__construct();
// your own logic
$this->roles = array('ROLE_USER');
}
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
}
And i'm receiving errors after registration on this repository
<?php
namespace App\Repository\User;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function findUserByUsernameOrEmail($usernameOrEmail)
{
if (filter_var($usernameOrEmail, FILTER_VALIDATE_EMAIL)) {
return $this->findUserBy(array(
'emailCanonical' => $this->canonicalizeEmail($usernameOrEmail)
));
}
return $this->createQueryBuilder('user_manager')
->where('user_m.phone_number = :phone_number')
->setParameter(':phone_number', $usernameOrEmail)
->getQuery()
->getOneOrNullResult();
}
}
I need your help please because i've read the symfony documentation and other answers in this site but nothing worked.

Related

symfony6 install KnpMenuBundle

I want to install KnpMenuBundle into an empty Symfony project (--webapp project).
I make steps from KnpMenuBundle documentation but it does not work.
configuration
symfony 6.1.7
KnpMenuBundle downloaded: 3.2
Here are my different files:
composer.json
{
"type": "project",
"license": "proprietary",
"minimum-stability": "stable",
"prefer-stable": true,
"require": {
"php": ">=8.1",
"ext-ctype": "*",
"ext-iconv": "*",
"doctrine/annotations": "^1.0",
"doctrine/doctrine-bundle": "^2.7",
"doctrine/doctrine-migrations-bundle": "^3.2",
"doctrine/orm": "^2.13",
"knplabs/knp-menu-bundle": "^3.2",
"phpdocumentor/reflection-docblock": "^5.3",
"phpstan/phpdoc-parser": "^1.13",
"sensio/framework-extra-bundle": "^6.1",
"symfony/asset": "6.1.*",
"symfony/console": "6.1.*",
"symfony/doctrine-messenger": "6.1.*",
"symfony/dotenv": "6.1.*",
"symfony/expression-language": "6.1.*",
"symfony/flex": "^2",
"symfony/form": "6.1.*",
"symfony/framework-bundle": "6.1.*",
"symfony/http-client": "6.1.*",
"symfony/intl": "6.1.*",
"symfony/mailer": "6.1.*",
"symfony/mime": "6.1.*",
"symfony/monolog-bundle": "^3.0",
"symfony/notifier": "6.1.*",
"symfony/process": "6.1.*",
"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/string": "6.1.*",
"symfony/translation": "6.1.*",
"symfony/twig-bundle": "6.1.*",
"symfony/validator": "6.1.*",
"symfony/web-link": "6.1.*",
"symfony/yaml": "6.1.*",
"twig/extra-bundle": "^2.12|^3.0",
"twig/twig": "^2.12|^3.0"
},
"config": {
"allow-plugins": {
"composer/package-versions-deprecated": true,
"symfony/flex": true,
"symfony/runtime": true
},
"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": "*",
"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.*"
}
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"symfony/browser-kit": "6.1.*",
"symfony/css-selector": "6.1.*",
"symfony/debug-bundle": "6.1.*",
"symfony/maker-bundle": "^1.0",
"symfony/phpunit-bridge": "^6.1",
"symfony/stopwatch": "6.1.*",
"symfony/web-profiler-bundle": "6.1.*"
}
}
config.bundles.php
<?php
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
Twig\Extra\TwigExtraBundle\TwigExtraBundle::class => ['all' => true],
Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
Knp\Bundle\MenuBundle\KnpMenuBundle::class => ['all' => true],
];
config/packages/knp_menu.yaml
# config/packages/knp_menu.yaml
knp_menu:
# use "twig: false" to disable the Twig extension and the TwigRenderer
twig:
template: KnpMenuBundle::menu.html.twig
# if true, enables the helper for PHP templates
templating: false
# the renderer to use, list is also available by default
default_renderer: twig
src/Menu/Builder.php
<?php
// src/Menu/Builder.php
namespace App\Menu;
use App\Entity\Blog;
use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
final class Builder implements ContainerAwareInterface
{
use ContainerAwareTrait;
public function mainMenu(FactoryInterface $factory, array $options): ItemInterface
{
$menu = $factory->createItem('root');
$menu->addChild('Home', ['route' => 'homepage']);
// access services from the container!
$em = $this->container->get('doctrine')->getManager();
// findMostRecent and Blog are just imaginary examples
$blog = $em->getRepository(Blog::class)->findMostRecent();
$menu->addChild('Latest Blog Post', [
'route' => 'blog_show',
'routeParameters' => ['id' => $blog->getId()]
]);
// create another menu item
$menu->addChild('About Me', ['route' => 'about']);
// you can also add sub levels to your menus as follows
$menu['About Me']->addChild('Edit profile', ['route' => 'edit_profile']);
// ... add more children
return $menu;
}
}
src/Controller/IndexController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class IndexController extends AbstractController
{
#[Route('/', name: 'app_index')]
public function index(): Response
{
return $this->render('index/index.html.twig', [
'controller_name' => 'IndexController',
]);
}
}
templates/index/index.html.twig
{% extends 'base.html.twig' %}
{% block title %}Hello IndexController!{% endblock %}
{% block body %}
<style>
.example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
.example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>
<div class="example-wrapper">
<h1>Hello {{ controller_name }}! ✅</h1>
This friendly message is coming from:
<ul>
<li>Your controller at <code>src/Controller/IndexController.php</code></li>
<li>Your template at <code>templates/index/index.html.twig</code></li>
</ul>
</div>
{{ knp_menu_render('App:Builder:mainMenu') }}
{% endblock %}
NOTES:
when I install KnpMenuBundle, config/packages/knp_menu.yaml did not exist, I had to create it and paste inside the code.
src/Menu folder did not exist, I had to create it with Builder.php inside and paste the code.
when I added {{ knp_menu_render('App:Builder:mainMenu') }} into my templates/index/index.html.twig, I got the error:
An exception has been thrown during the rendering of a template
("Bundle "App" does not exist or it is not enabled. Maybe you
forgot to add it in the "registerBundles()" method of your
"App\Kernel.php" file?").
If you have any ideas, clues, or anything else, I'm listening because I don't know where the mistake is.
I am using method b: a menu builder as a service without any problems.
Look at the documentation page. So I recommend you do the same way.

After Update from SF4.4 to 5.4, generateUrl error : "Some mandatory parameters are missing" for route with optional parameters

Since I updated Symfony 4.4 to symfony 5.4, i have a last problem to resolve.
Methode "generateURl()" in controller, and "path()" in twig template return an exception for route with optional param that i dont specify for generateURl method in controller or path methode in twig:
Some mandatory parameters are missing ("optionalvarname") to generate a URL for
route "the_route".
Otherwise routes themselves work well. I can connect on its without specifie the defaut param.
Everythings worked well in symfony 4.4
But in Symfony 5.4 I can't omit to specify optional param for this two methods.
Exemple with an "action" optional parameters :
/**
* #Route("/{id}/edit/{action}", name="tenant_vente_edit", methods={"GET","POST"})
*/
public function edit(
Request $request, Vente $vente,string $action="update",Panier $panier,
MouvementRepository $mouvementRepository,VenteUtils $venteUtils): Response
{
.....
$this->generateUrl('tenant_vente_edit',['id'=>$vente->getId()])
I omited "action" optional param and this generate exception : Some mandatory parameters are missing ("action") to generate a URL for route "tenant_vente_edit".
But the route itslef works...when there is no action parameter in url.
To "generateUrl()" and "path()" works omiting optionals parameters i have to add the defaut value "?update" in the comment :
/**
* #Route("/{id}/edit/{action?update}", name="tenant_vente_edit", methods={"GET","POST"})
*/
public function edit(
Request $request, Vente $vente,string $action="update",Panier $panier,
MouvementRepository $mouvementRepository,VenteUtils $venteUtils): Response
{
In this case i have no error for "generateUrl()" method and "path()" method.
Would you know why i have this behviour ? I don't want to go back on all my route...I have a lot..
Thank you very much for your help and sorry for my english....
My new composer.json for update to 5.4
{
"type": "project",
"license": "proprietary",
"require": {
"php": ">=8.1.0",
"ext-ctype": "*",
"ext-iconv": "*",
"beberlei/doctrineextensions": "^1.3",
"composer/package-versions-deprecated": "1.11.99.4",
"doctrine/annotations": "^1.0",
"doctrine/doctrine-bundle": "^2.5",
"doctrine/doctrine-migrations-bundle": "^3.2",
"doctrine/orm": "^2.11",
"knplabs/knp-paginator-bundle": "^5.8",
"knplabs/knp-snappy-bundle": "^1.7",
"phpdocumentor/reflection-docblock": "^5.3",
"phpoffice/phpspreadsheet": "^1.14",
"sensio/framework-extra-bundle": "^6.1",
"symfony/asset": "5.4.*",
"symfony/console": "5.4.*",
"symfony/dotenv": "5.4.*",
"symfony/expression-language": "5.4.*",
"symfony/flex": "^1.17|^2",
"symfony/form": "5.4.*",
"symfony/framework-bundle": "5.4.*",
"symfony/monolog-bundle": "^3.1",
"symfony/process": "5.4.*",
"symfony/property-access": "5.4.*",
"symfony/property-info": "5.4.*",
"symfony/proxy-manager-bridge": "5.4.*",
"symfony/security-bundle": "5.4.*",
"symfony/serializer": "5.4.*",
"symfony/swiftmailer-bundle": "^3.1",
"symfony/translation": "5.4.*",
"symfony/twig-bundle": "5.4.*",
"symfony/validator": "5.4.*",
"symfony/web-link": "5.4.*",
"symfony/webpack-encore-bundle": "^1.5",
"symfony/yaml": "5.4.*",
"vich/uploader-bundle": "^1.19",
"twig/extra-bundle": "^2.12",
"twig/twig": "^2.12"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"symfony/browser-kit": "5.4.*",
"symfony/css-selector": "5.4.*",
"symfony/debug-bundle": "5.4.*",
"symfony/maker-bundle": "^1.0",
"symfony/phpunit-bridge": "^5.3",
"symfony/stopwatch": "5.4.*",
"symfony/web-profiler-bundle": "5.4.*"
},
"config": {
"preferred-install": {
"*": "dist"
},
"sort-packages": true,
"allow-plugins": {
"symfony/flex": 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-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.4.*"
}
}
}
it seams optional paraméters must be at the end of controller arguments.
In this two cases routes work if you omit optional parameter in url.
First case :
/**
* #Route("/{id}/edit/{action}", name="tenant_vente_edit", methods={"GET","POST"})
*/
public function edit(
Request $request, Vente $vente,Panier $panier,MouvementRepository $mouvementRepository,
VenteUtils $venteUtils,?string $action=null): Response
{
Second case
/**
* #Route("/{id}/edit/{action}", name="tenant_vente_edit", methods={"GET","POST"})
*/
public function edit(
Request $request, Vente $vente,Panier $panier,MouvementRepository $mouvementRepository,
?string $action=null, VenteUtils $venteUtils): Response
{
But :
$this->generateUrl('tenant_vente_edit',['id'=>$vente->getId()])
Works only in the second case with "action" optional argument in last position of controller arguments, idem for twig and "path()".
I didnt have this behaviour in symfony 4.4
So no other choice to check all my routes. To avoid this kind of problem i advice to put default value in comment instead of controller arguments.
/**
* #Route("/{id}/edit/{action?}", name="tenant_vente_edit", methods={"GET","POST"})
*/
public function edit(
Request $request, Vente $vente,Panier $panier,MouvementRepository $mouvementRepository,
VenteUtils $venteUtils,?string $action): Response
action?(_blank) for null value in this example.

the PHPUnit test of a uri fails while the request succeeded in the browser

My application is on Symfony 4.4, PHP 7.4.
My composer.json :
{
"name": "saro0h/to-do-list",
"type": "project",
"license": "proprietary",
"require": {
"php": ">=7.1.3",
"ext-ctype": "*",
"ext-iconv": "*",
"composer/package-versions-deprecated": "^1.11",
"doctrine/annotations": "^1.11",
"doctrine/doctrine-bundle": "^2.1",
"doctrine/doctrine-migrations-bundle": "^3.0",
"doctrine/orm": "^2.7",
"sensio/framework-extra-bundle": "^5.6",
"symfony/apache-pack": "^1.0",
"symfony/asset": "4.4.*",
"symfony/console": "4.4.*",
"symfony/dotenv": "4.4.*",
"symfony/flex": "^1.3.1",
"symfony/form": "4.4.*",
"symfony/framework-bundle": "4.4.*",
"symfony/mailer": "4.4.*",
"symfony/monolog-bundle": "^3.6",
"symfony/security-bundle": "4.4.*",
"symfony/security-csrf": "4.4.*",
"symfony/twig-bundle": "4.4.*",
"symfony/validator": "4.4.*",
"symfony/yaml": "4.4.*"
},
"require-dev": {
"phpstan/phpstan": "^0.12.54",
"symfony/browser-kit": "4.4.*",
"symfony/css-selector": "4.4.*",
"symfony/maker-bundle": "^1.23",
"symfony/phpunit-bridge": "^5.1",
"symfony/stopwatch": "^4.4",
"symfony/web-profiler-bundle": "^4.4"
},
"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-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": "4.4.*"
}
}
}
There is the method controller I want to test:
<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\UserType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserController extends AbstractController
{
/**
* list all users.
*
* #Route("/users", name="user_list")
*
* #return Response
*/
public function list(): Response
{
return $this->render('user/list.html.twig', ['users' => $this->getDoctrine()->getRepository(User::class)->findAll()]);
}
}
Then a test it with PHPUnit
<?php
namespace App\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* #internal
* #coversNothing
*/
class UserControllerTest extends WebTestCase
{
/**
* testIndex.
*/
public function testUserList(): void
{
$client = static::createClient();
$client->request('GET', '/users');
$this->assertTrue($client->getResponse()->isSuccessful());
}
}
In the browser, the request is successfull (The page display without error, with 200 HTTP code status, no errors in the profiler)
But, when I run PHPUnit, the test fails with $client->getResponse()->getStatusCode() = 500 !!!!
How can I fix that ?
Thank you for your answers
I solved my problem !
When a had the idea to display the page with the test environment, I get the error:
An exception occurred in driver: SQLSTATE[HY000] [2002] Aucune connexion n’a pu être établie car l’ordinateur cible l’a expressément refusée.
So I solved the problem creating a database for the test environment, in defined my .env.test.

Symfony Api Platform Normalization Context Groups datetime property issue

I'm struggle with strange issue when using normalizer with groups. It look like there is a problem with datetime properties.
Issue occurs when using normalizationContext on ApiResource and/or normalization_context on operation.
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* #ApiResource(
* collectionOperations={
* "get"={
* "normalization_context"={
* "datetime_format"="Y-m-d\TH:i:sP",
* "groups"={"bookmarkdata:collection:read"}
* }
* }
* },
* itemOperations={
* "get"
* },
* normalizationContext={"groups"={"bookmarkdata:read"}}
* )
* #ORM\Entity(repositoryClass="App\Repository\BookmarkDataRepository")
*/
class BookmarkData
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
* #Groups({"bookmarkdata:read", "bookmarkdata:collection:read"})
*/
private $id;
/**
* #ORM\Column(type="string", length=2048, nullable=true)
* #Groups({"bookmarkdata:read", "bookmarkdata:collection:read"})
*/
private $screenshot;
/**
* #ORM\Column(type="string", length=2048)
* #Groups({"bookmarkdata:read", "bookmarkdata:collection:read"})
*/
private $dump;
/**
* #ORM\Column(type="datetime")
* #Groups({"bookmarkdata:read", "bookmarkdata:collection:read"})
*/
private $created_at;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $updated_at;
public function getId(): ?int
{
return $this->id;
}
public function getScreenshot(): ?string
{
return $this->screenshot;
}
public function setScreenshot(?string $screenshot): self
{
$this->screenshot = $screenshot;
return $this;
}
public function getDump(): ?string
{
return $this->dump;
}
public function setDump(string $dump): self
{
$this->dump = $dump;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->created_at;
}
public function setCreatedAt(\DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updated_at;
}
public function setUpdatedAt(?\DateTimeInterface $updated_at): self
{
$this->updated_at = $updated_at;
return $this;
}
}
In result property created_at ignored.
{
"#context": "/api/contexts/BookmarkData",
"#id": "/api/bookmark_datas",
"#type": "hydra:Collection",
"hydra:member": [
{
"#id": "/api/bookmark_datas/1",
"#type": "BookmarkData",
"id": 1,
"screenshot": "This is screen",
"dump": "This is dump"
}
],
"hydra:totalItems": 1
}
I'm using Docker.
My dependencies.
{
"type": "project",
"license": "proprietary",
"require": {
"php": "^7.1.3",
"ext-ctype": "*",
"ext-iconv": "*",
"api-platform/api-pack": "^1.2",
"doctrine/doctrine-migrations-bundle": "^2.1",
"easycorp/easyadmin-bundle": "^2.3",
"lexik/jwt-authentication-bundle": "^2.6",
"nesbot/carbon": "^2.32",
"symfony/console": "4.4.*",
"symfony/dotenv": "4.4.*",
"symfony/flex": "^1.3.1",
"symfony/framework-bundle": "4.4.*",
"symfony/security-bundle": "4.4.*",
"symfony/yaml": "4.4.*"
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.3",
"fzaninotto/faker": "^1.9",
"symfony/maker-bundle": "^1.15",
"symfony/profiler-pack": "^1.0"
},
"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-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": "4.4.*"
}
}
}

Unknown Entity namespace alias 'AppBundle' and "Class 'App\\Entity\\Product' does not exist

I'm trying to implement FOSRestBundle so I've just created my first class controller.
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;
use App\Entity\Product;
class ProductController extends FOSRestController
{
/**
* #Rest\Get("/product")
*/
public function getAction()
{
$em = $this->getDoctrine()->getManager();
$restresult = $em->getRepository('AppBundle:Product')->getAllProduct();
if ($restresult === null) {
return new View("there are no products exist", Response::HTTP_NOT_FOUND);
}
return $restresult;
} // "Get products" [GET] /product*/
}
But Symfony server give me that error:
- "Unknown Entity namespace alias 'AppBundle'."
- "Doctrine\ORM\ORMException";
My composer.json is:
{
"name": "symfony/framework-standard-edition",
"license": "MIT",
"type": "project",
"description": "The \"Symfony Standard Edition\" distribution",
"autoload": {
"psr-4": {
"AppBundle\\": "src/AppBundle"
},
"psr-0": {"": "src/"},
"classmap": [ "app/AppKernel.php", "app/AppCache.php" ]
},
"autoload-dev": {
"psr-4": { "Tests\\": "tests/" },
"files": [ "vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php" ]
},
"require": {
"php": ">=5.5.9",
"doctrine/doctrine-bundle": "^1.6",
"doctrine/orm": "^2.5",
"friendsofsymfony/rest-bundle": "^2.3",
"incenteev/composer-parameter-handler": "^2.0",
"jms/serializer-bundle": "^2.4",
"nelmio/cors-bundle": "^1.5",
"sensio/distribution-bundle": "^5.0.19",
"sensio/framework-extra-bundle": "^5.0.0",
"symfony/monolog-bundle": "^3.1.0",
"symfony/polyfill-apcu": "^1.0",
"symfony/swiftmailer-bundle": "^2.6.4",
"symfony/symfony": "3.4.*",
"twig/twig": "^1.0||^2.0",
"symfony/orm-pack": "^1.0"
},
"require-dev": {
"sensio/generator-bundle": "^3.0",
"symfony/phpunit-bridge": "^4.1"
},
"scripts": {
"symfony-scripts": [
"Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
],
"post-install-cmd": [
"#symfony-scripts"
],
"post-update-cmd": [
"#symfony-scripts"
]
},
"extra": {
"symfony-app-dir": "app",
"symfony-bin-dir": "bin",
"symfony-var-dir": "var",
"symfony-web-dir": "web",
"symfony-tests-dir": "tests",
"symfony-assets-install": "relative",
"incenteev-parameters": {
"file": "app/config/parameters.yml"
},
"branch-alias": {
"dev-master": "3.4-dev"
}
}
Product Entity class is:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Product
*
* #ORM\Table(name="Product")
* #ORM\Entity
*/
class Product
{
/**
* #var integer
*
* #ORM\Column(name="idProduct", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idproduct;
/**
* #var string
*
* #ORM\Column(name="productName", type="string", length=100, nullable=false)
*/
private $productname;
/**
* #var boolean
*
* #ORM\Column(name="Purchased", type="boolean", nullable=true)
*/
private $purchased;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="User", mappedBy="productproduct")
*/
private $useruser;
/**
* Constructor
*/
public function __construct()
{
$this->useruser = new \Doctrine\Common\Collections\ArrayCollection();
}
}
and then, ProductRepository file is:
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
class ProductRepository extends EntityRepository
{
public function getAllProduct()
{
$conn = $this->getEntityManager()->getConnection();
$sql = "SELECT * from product";
$stmt = $conn->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
}
}
I've also tried to replace
$restresult = $em->getRepository('AppBundle:Product')->getAllProduct();
with
$restresult = $em->getRepository(Product::class)->getAllProduct();
but the error now is:
-"Class 'App\Entity\Product' does not exist"
-"Doctrine\Common\Persistence\Mapping\MappingException"
I've already tried the solutions of other stack overlow's users about this topic but nothing.
Someone can help me please?
use App\Entity\Product;
This should be the culprit. (in your Controller)
EDIT: Sorry, missed the 1st error. Could you post your doctrine config? Is automapping on?
In ProductController file
instead of
use App\Entity\Product;
replace it with
use AppBundle\Entity\Product;
Your dir structure is wrong. https://github.com/axeowl/projectKobe/tree/master/src
Entity and Repo dirs should be inside AppBundle.

Resources