Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all 3925 articles
Browse latest View live

php bin/console make:entity --regenerate App doesn't generate new fields

$
0
0

I updated this entity adding some fields.

Now I'd like to regenerate getters and setters but whe I execute php bin/console make:entity --regenerate App I have no results; my entites are listet but it says "no change". I'v tried event with --overwrite option.

<?php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity(repositoryClass="App\Repository\ProfessionalRepository")
*/
class Professional
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=255)
 */
private $nom;


/**
 * @ORM\Column(type="boolean")
 */
private $actiu;

/**
 * @ORM\ManyToOne(targetEntity="Especialitat")
 * @ORM\JoinColumn(referencedColumnName="id")
 */
private $especialitat;

public function getId(): ?int
{
    return $this->id;
}

public function getNom(): ?string
{
    return $this->nom;
}

public function setNom(string $nom): self
{
    $this->nom = $nom;

    return $this;
}

public function getActiu(): ?bool
{
    return $this->actiu;
}

public function setActiu(bool $actiu): self
{
    $this->actiu = $actiu;

    return $this;
}
}

I'm using symfony 4.3.8 In previous versions I did it executring 'php bin/console doctrine:genetrate:entities App', I'm not sure if I can use this command in symfony 4, anyway it neither doesn't work.

I'm don't know what else to try...


Getting a Syntax error on Doctrine CreateQueryBuilder with multiple SELECT

$
0
0

I have this query below which returns everything as expected. However, when run I get a doctrine syntax error but I cant pintpoint it. Is there a special way to add multiple selects in Doctrine?

This is my function.

public function summaryReport()
{
    $qb = $this->createQueryBuilder('ds')
        ->select('ds.d_id, ds.d_name,
                        SUM(ds.c_email IS NOT NULL) * 100.00 / COUNT(c_number) AS percentage,
                        COUNT(DISTINCT ds.c_number) AS Qualifying_customers,
                        sum(ds.c_email IS not NULL) AS Qualifying_Customers_with_Email')
        ->groupBy('ds.d_id, ds.d_name')
        ->getQuery();
    dd($qb->getDQL());
    return $qb->getResult();
}

error I am receiving is

 Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got 'IS'

would an addSelect seperate them?

SF4 autenticator failure in CsrfTokenManager with iOs

$
0
0

Working with Symfony 4, and making an User environment (using SymfonyCast tutorials) I wrote a LoginFormAuthenticator :

class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
    use TargetPathTrait;

    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    private $passwordEncoder;

    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->passwordEncoder = $passwordEncoder;
    }

    public function supports(Request $request)
    {
        return 'login' === $request->attributes->get('_route')
            && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
        $credentials = [
            'username' => $request->request->get('username'),
            'password' => $request->request->get('password'),
            'csrf_token' => $request->request->get('_csrf_token'),
        ];
        $request->getSession()->set(
            Security::LAST_USERNAME,
            $credentials['username']
        );

        return $credentials;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();
        }

        $user = $this->entityManager->getRepository(User::class)->findOneBy(['username' => $credentials['username']]);
        if (!$user) {
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException('L\'username ne peut pas être trouvé.');
        }

        return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

        return new RedirectResponse($this->urlGenerator->generate('core_home'));
    }

    protected function getLoginUrl()
    {
        return $this->urlGenerator->generate('login');
    }
}
`

But the issue is in the csrf protection. (after many searches, reducing the area of the issue) : I can't connect with my username, a loop give me always the form, with last username...

From the log :

[2019-11-16 15:27:17] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"main","authenticator":"App\Security\LoginFormAuthenticator"} [] [2019-11-16 15:27:17] security.DEBUG: Guard authenticator does not support the request. {"firewall_key":"main","authenticator":"App\Security\LoginFormAuthenticator"} []

Trying to better understand, I put a dd() in the getUser function :

$token = new CsrfToken('authenticate', $credentials['csrf_token']); dd($token);

and the result is :

LoginFormAuthenticator.php on line 63: CsrfToken^ {#345 ▼ -id: "authenticate" -value: "A11CgM6FtyduixvNmOotNkjqbakFCfYPD-TSXv8_PGE" }

We have a Csrf token. Searching more, I put in CsrfTokenManager (from Symfony/Security/Csrf) two dump() an a dd() in the istokenValid function :

    public function isTokenValid(CsrfToken $token)
{
    dump($token);
    $namespacedId = $this->getNamespace().$token->getId();
    dump($namespacedId);
    if (!$this->storage->hasToken($namespacedId)) {
    dd(!$this->storage->hasToken($namespacedId));
     return false;
    }

    return hash_equals($this->storage->getToken($namespacedId), $token->getValue());
}

and the results are :

CsrfTokenManager.php on line 109:

CsrfToken^ {#345 ▼ -id: "authenticate" -value: "YPZIzpw_8eU5Uy3YvV6PwySz4qz8FIz0EzkIwkBd-OQ" }

CsrfTokenManager.php on line 111:

"authenticate"

CsrfTokenManager.php on line 113:

true

So, if I understand well, we have a cookie, and the function return 'this cookie is not valid'...

What's wrong ?

Symfony 4 Single-Text DateTime Widget no longer accepting yyyy-MM-dd string

$
0
0

I'm sending a POST with the string 1980-01-02 as birth.

My controller is verifying it using a form with this config.

  ->add('birth', DateTimeType::class, array(
                'required' => false,
                'widget' => 'single_text', // so the API can send '2012-12-30''attr' => ['date-widget' => 'single_text', 'date_format' => 'yyyy-MM-dd']
            ));

This code was working on SF3, and maybe even on SF 4.1

Now I'm getting this error. Unable to reverse value for property path "birth": The date "1980-01-02" is not a valid date.

Any idea how to solve it? Cheers

Symfony 4.4 unknown inky_to_html filter

$
0
0

I recently updated Symfony to 4.4 (from 4.3) and can't have my translations files updated automatically (using php bin/console tran:up --force) any more. The error that pops up is:

In body.html.twig line 1:
Unknown "inky_to_html" filter.

The file in question is vendor/symfony/twig-bridge/Resources/views/Email/zurb_2/notification/body.html.twig which I never use, I have no idea why it's inclued all at a sudden. To get rid of the message I tried to require twig/inky-extra but that requires the ext-xsl-extension and I don't really want to bloat my code with things I don't need just to get rid of an error related to a twig-extension that's also not needed.

I tried to change the version of the translation-interface as described here, but that also didn't change anything.

I guess it has something to do with my project as I couldn't find any similar problem, but I can't figure it out, so any help is appreciated.

EDIT: Here's my composer.json, it's basically the same as it was generated when creating the Symfony 4.3-project, I only changed the version names to upgrade as described in the docs and ran composer update.

{
  "type": "project",
  "license": "proprietary",
  "require": {
    "php": "^7.1.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "ext-intl": "*",
    "apy/breadcrumbtrail-bundle": "^1.5",
    "craue/config-bundle": "^2.3",
    "easycorp/easy-log-handler": "^1.0",
    "friendsofsymfony/jsrouting-bundle": "^2.4",
    "league/csv": "^9.4",
    "nesbot/carbon": "^2.25",
    "sensio/framework-extra-bundle": "^5.1",
    "sg/datatablesbundle": "^1.1",
    "symfony/apache-pack": "^1.0",
    "symfony/asset": "^4.0",
    "symfony/console": "^4.0",
    "symfony/dotenv": "^4.0",
    "symfony/expression-language": "^4.0",
    "symfony/flex": "^1.3.1",
    "symfony/form": "^4.0",
    "symfony/framework-bundle": "^4.0",
    "symfony/http-client": "^4.0",
    "symfony/intl": "^4.0",
    "symfony/monolog-bundle": "^3.1",
    "symfony/orm-pack": "*",
    "symfony/process": "^4.0",
    "symfony/security-bundle": "^4.0",
    "symfony/security-csrf": "^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/yaml": "^4.0",
    "tetranz/select2entity-bundle": "^3.0"
  },
  "require-dev": {
    "dama/doctrine-test-bundle": "^6.1",
    "doctrine/doctrine-fixtures-bundle": "^3.2",
    "pdepend/pdepend": "^2.5",
    "phpmd/phpmd": "^2.7",
    "phpunit/php-code-coverage": "^7.0",
    "roave/security-advisories": "dev-master",
    "squizlabs/php_codesniffer": "3.*",
    "symfony/debug-pack": "*",
    "symfony/maker-bundle": "^1.0",
    "symfony/phpunit-bridge": "^4.3",
    "symfony/profiler-pack": "*",
    "symfony/test-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": {
    "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.*"
    }
  }
}

how to do a subquery sql in Doctrine 2.9

$
0
0

I would like to format a query sql dql request but I can not do it for several days!

       SELECT bh.id, bh.PrixPublic 
       FROM bien_hermes AS bh
       LEFT OUTER JOIN property_alert AS pa ON bh.id = pa.bien_id
       WHERE bh.PrixPublic <= (SELECT au.max_price FROM alert AS au_user LIMIT 1)
       AND pa.bien_id IS null

How would I do this query with the query builder?

Is there anything new to use translatable entities with EasyAdminBundle?

$
0
0

how can i use doctrine Extensions Bundle with EasyAdminBundle i want to translate my entities using doctrineExtensions Bundle with EasyAdminBundle

FOSUser : templates are not showing CSS after deployment SF4

$
0
0

My CSS is not displayed on my FOSUser template after deployment. In local, everything's fine. I followed the documention of FOSUser and I don't understand what's going on.

'Could you help me please ?'

base.html.twig

<!doctype html>
<html lang="fr-FR">
<head>

    {% block stylesheets %}
        ...
        <link rel="stylesheet" href="/css/bootstrap.min.css">
        <link rel="stylesheet" href="/css/jquery.fancybox.min.css" />
        <link rel="stylesheet" href="/css/index.css">
    {% endblock %}
</head>

<body>


    {% block content %}

    {% endblock %}

...

'layout.html.twig'

{% extends 'base.html.twig' %}


{% block content %}
    <div>
        <div>
            <div>
                {% block fos_user_content %}{% endblock %}
            </div>
        </div>
    </div>
{% endblock %}

example of my login template with FOSUser :

{% extends "FOSUserBundle::layout.html.twig" %}

{% block stylesheets %} {% endblock %}

{% block fos_user_content %}

.....

{% endblock %}

How to add an image in an email with swiftmailer?

$
0
0

I'm trying to have an image in the email. I use Symfony 4 and SwiftMailer. I read the documentation, the forum but it doesn't work. So I tried:

 $message = (new \Swift_Message('Title of the email'))
                        ->setFrom('myemailadress@xxxxxx.com')
                        ->setTo($data['email']);

                    $headers = $message->getHeaders();

                    $attachment = \Swift_Attachment::fromPath('assets/img/logo.png');

                    $headers = $attachment->getHeaders();
 $message->setBody(
                        $this->renderView(
                            'resetemail.html.twig',
                            [ 'resetPassword' => $resetPassword], $headers
                        ),
                        'text/html'
                    );
$mailer->send($message);
                    return $this->redirectToRoute("requestMail");

For the Twig, I did:

<img id="customHeaderImage" align="top" label="Image" src="headers" alt="the title of the logo" class="w640" border="0" style="display: inline">

I also tried to replace the headers'part by: $img = $message->embed(Swift_Image::fromPath('assets/img/logo.png'));

But I just have : enter image description here

If you have a solution, I would love to read it.

Thanks.

Doctrine statement is not returning data correctly when raw query is used

$
0
0

Using symfony4 I have a raw query in one of my repositories which receives two dates as paramenters to result in something as follow:

SELECT ss.company_name, count(ss.id) AS total, 
        count(ss.id) filter (WHERE ss.container_dimention = '20') AS total_20,
        count(ss.id) filter (WHERE ss.container_dimention = '40') AS total_40, count(ss.id) filter (WHERE ss.container_type = 'RH') AS total_rh, count(ss.id) filter (WHERE ss.container_type != 'RH') AS total_dry, count(ss.id) filter (WHERE ss.container_type = 'RH' AND ss.days_in_tcm > 7) AS total_rh_plus_seven, count(ss.id) filter (WHERE ss.days_in_tcm > 3) AS total_plus_three, count(ss.id) filter (WHERE ss.days_in_tcm > 3 AND ss.container_type = 'RH') AS total_plus_three_rh, count(ss.id) filter (WHERE ss.days_in_tcm > 15) AS total_plus_fifteen, count(ss.id) filter (WHERE ss.is_enabled) AS total_enabled, count(ss.id) filter (WHERE NOT ss.is_locked) AS total_locked FROM shipment ss WHERE ss.extraction_at IS NULL AND ss.arrived_at BETWEEN '2019-11-30' AND '2019-12-02' GROUP BY ss.company_name

This query is taken from the profiler...

After building the query I do as follow

    $conn = $this->getEntityManager()->getConnection();
    $stmt = $conn->prepare($dql);
    $stmt->execute();

    return $stmt->fetchAll();

The problem is when I execute the generated query on PostgreSQL console I get one result but the fetch method is returning an empty array.

Any tip about why is happening this, there is no error in the profiler and the query is OK as is returning results on server console.

Thanks in advance!

deploying a Symfony 4.3 application

$
0
0

I am new to Symfony4 and i can't deploy it on my host...

I created a sub domain to test my website before uploading it (http://symfony.photoclubchirac.org/) on my host (nuxit).

I asked them if they already have a tutorial for uploading Symfony on their system but they don't know how to do it, and they asked me to see with a web master..

I upload all my files (i think it's the first step to do) and then i am at the "Check requirements" step. Here i am stuck cause i have to install Composer and Symfony but i don't have any ssh access on my host account... How can i know if all the technical requirements are ok please ?

Symfony 4 | Get config parameters from controller within a custom bundle

$
0
0

I'm trying to get some params from a config yaml file, Im doing the following:

namespace ExampleVendor\AdminBundle\Controller;

/**
 * @Route("/", name="_home")
 */
public function index(ParameterBagInterface $params) {
    $menuIcons = $this->getParameter('admin-aside-menu');
    dump($menuIcons);

    return $this->render('@ExampleVendorAdminBundle/index.html.twig');
}

As you can see is just a dump function that prints the admin-aside-menu parameter, the problem is, this code works when it is in a controller in App\src\Controller, I mean in the "main" application src folder, but when I copy this code and paste it in a controller inside a custom bundle (something like vendor/myVendor/myBundle/src/Controller) I get an error when reloading the page:

Could not resolve argument $params of "ExampleVendor\AdminBundle\Controller\AdminController::index()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?

I need ParameterBagInterface to get those parameters but I dont know how to "inject" it in my controller.

Thank you for reading.

---------------------- EDIT ----------------------

Okay so it seems like this post says how to fix this issue but, since the controller I need to inject something is in a custom bundle in the vendor folder, the answer doesn't help me at all

Project
|
+--AdminBundle <- My custom bundle, installed via composer as symlink
|  |
|  +--Controller
|  |  |
|  |  +--AdminController.php <- Heres where I want to get my parameter
|  |
|  +--DependencyInjection
|  +--Entity
|  +--Resources
|     |
|     +--config
|        |
|        +--custom.yaml <- There are my custom params
|        +--services.yaml <- Heres where I should register my controller as service?
|
+--assets
|
+--bin
|
+--config
|
+--public
|
+--src
|
+--templates
|
+--vendor <- Heres my admin bundle as symlink

The AdminBundle folder is installer via composer as symlink so I can use it in my project, so knowing this, anyone know how can I inject ParametersBag or the parameter directly into my controller? Im so so confused, the docs can't help me so I really need your help.

listen to request before json authentication symfony 4

$
0
0

I have tow way to login the users to my application: from a backoffice or from an api. for some reason i want to process a ldap check before the authentification proccess start.

  • for the BO i found this,and its work fine:

listen to request before authentication or rewrite /login_check in symfony3

  • I want also do that for the api json login,so i want to Extend the UsernamePasswordJsonAuthenticationListener

but i had this error when i try to login to the api:

Argument 3 passed to Symfony\Component\Security\Http\Firewall\UsernamePasswordJsonAuthenticationListener::__construct() must be an instance of Symfony\Component\Security\Http\HttpUtils, instance of Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy given

this is my code

services.yaml

    security.authentication.listener.json:
    class: App\EventListener\UsernamePasswordJsonAuthenticationListener
    parent: security.authentication.listener.abstract
    abstract: true
    autowire: true
    autoconfigure: false
    calls: [ [initialize, ["@doctrine.orm.entity_manager"]] ]

//UsernamePasswordJsonAuthenticationListener.php

<?php


namespace App\EventListener;

use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use App\Service\LdapTools;
use Symfony\Component\Security\Http\Firewall\UsernamePasswordJsonAuthenticationListener as baseJsonAuthenticationListener;

class UsernamePasswordJsonAuthenticationListener extends baseJsonAuthenticationListener
{

/** @var EntityManagerInterface */
protected $entityManager;

/** @var LdapTools */
protected $ldapTools;

/** @var UserManagerInterface */
protected $userManager;

/**
 * setter is called through DI container
 *
 * @param EntityManagerInterface $entityManager
 */
public function initialize(EntityManagerInterface $entityManager,LdapTools $ldapTools,UserManagerInterface $userManager)
{

    $this->entityManager = $entityManager;
    $this->ldapTools = $ldapTools;
    $this->userManager = $userManager;
}

}

?>

thanx before .

What is the recommended way of handling user management in symfony 4?

$
0
0

I'm migrating a sf3 app to sf4 and I'm having a hard time dealing with user authentication/management.

In my original application I used FOSUserBundle which had some really nice features (like the ability to manage user data through the CLI).

I found msgphp/userbundle which seems ok but I'd like to use the standard solution (should there be any).

So... what's the recommended option?

Thanks!

How to reference built assets in the config for Sonata Admin

$
0
0

I have an application developed with Symfony 4, using SonataAdminBundle and Webpack Encore.

For the admin I use extra JS and CSS. The source files are:

- assets
  - css
    app.css
  - js
    app.js

After I run yarn encore dev the following files are bumped into public\build\:

app.css
app.js
runtime.js

In the config for sonata_admin (config/packages/sonata_admin.yaml) I reference them like this:

sonata_admin:
    extra_stylesheets:
        - build/app.css
    extra_javascripts:
        - build/runtime.js
        - build/app.js

The problem is when I want to deploy the app I have to run yarn encore prod, and then the filenames of the assets change, something like app.ea54ac26.js, where the middle part is dynamically generated.

In a Twig template I can use for example:

{{ encore_entry_script_tags('app') }}

to load all built JS files.

What is the proper way to reference these files in the config file for Sonata Admin?


Symfony 4 | Configuration class: Making a TreeBuilder from yaml file

$
0
0

I'm trying to write a TreeBuilder to inject a yaml params in my custom bundle, this is my yaml file

example_admin:
  items:
      - icon: 'Home/Chair2'
        title: 'Prueba'
      - icon: 'Home/Deer'
        title: 'Prueba Venado'

and this is my what I tried in the extension class from the bundle:

class Configuration implements ConfigurationInterface {
    public function getConfigTreeBuilder() {
        $treeBuilder = new TreeBuilder('example_admin');

        $treeBuilder->getRootNode()
            ->children()
                ->arrayNode('items')
                    ->children()
                        ->variableNode('icon')->end()
                        ->variableNode('title')->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

But when I run the code I get the following error:

Unrecognized options "0, 1" under "example_admin.items". Available options are "icon", "title".

This is services.yaml from my bundle, where Im trying to inject some params to a controller

services:
    admin-bundle.controller.admin-controller:
        class: ExampleVendor\AdminBundle\Controller\AdminController
        arguments:
            - "%example_admin.items%"

I guess the error is in the TreeBuilder, maybe I did something wrong, I need some help here

Symfony 4 - load fixtures for dynamic user roles

$
0
0

Currently I'm trying to modify my classes and looking for idea to save dynamic relations between users and roles.

I want to create associations when loading fixtures and also to have such a functionality in controller when I need to create an user with relation, example:

...
$user = new User();
$user->setName($_POST['name']);
$user->setPassword($_POST['password']);
...
$user->setRole('ROLE_USER');//Role for everyone
...
$role = new Role();
$role->setName('ROLE_' . strtoupper($_POST['name']) );//Role for personal use
...
//Here need to implement user+role association (I'm looking for recommendations)
...
$entityManager->persist($user);
$entityManager->persist($role);
//Persist role+user assosiacion
$entityManager->flush();
$entityManager->clear();

My User.php :

<?php

    namespace App\Entity;

    use DateTime;
    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    use Symfony\Component\Security\Core\User\UserInterface;

    /**
     * User
     *
     * @ORM\Table(name="user", uniqueConstraints={@ORM\UniqueConstraint(name="user_name", columns={"user_name"}), @ORM\UniqueConstraint(name="email", columns={"email"})})
     * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
     * @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="fast_cache")
     * @UniqueEntity(fields="email", message="Email already taken")
     * @UniqueEntity(fields="username", message="Username already taken")
     */
    class User implements UserInterface, \Serializable
    {
        /**
         * @var ArrayCollection
         *
         * @ORM\ManyToMany(targetEntity="App\Entity\Role", inversedBy="users", cascade={"remove"})
         * @ORM\JoinTable(name="users_roles",
         *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
         *      inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
         *      )
         */
        protected $roles;
        /**
         * @var int
         *
         * @ORM\Column(name="id", type="smallint", nullable=false, options={"unsigned"=true})
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
        /**
         * @var string
         *
         * @ORM\Column(name="user_name", type="string", length=255, nullable=false)
         */
        private $username;
        /**
         * @var string
         *
         * @ORM\Column(name="email", type="string", length=255, nullable=false)
         */
        private $email;
        /**
         * @var string
         *
         * @ORM\Column(name="password", type="string", length=255, nullable=false)
         */
        private $password;
        /**
         * @var bool
         *
         * @ORM\Column(name="is_enabled", type="boolean", nullable=false)
         */
        private $isEnabled;
        /**
         * @var bool
         *
         * @ORM\Column(name="is_verified", type="boolean", nullable=false)
         */
        private $isVerified;
        /**
         * @var DateTime
         *
         * @ORM\Column(name="created_at", type="datetime", nullable=false)
         */
        private $createdAt;
        /**
         * @var DateTime
         *
         * @ORM\Column(name="updated_at", type="datetime", nullable=false)
         */
        private $updatedAt;

        /**
         * @return int
         */
        public function getId(): int
        {
            return $this->id;
        }

        /**
         * @return string
         */
        public function getEmail(): string
        {
            return $this->email;
        }

        /**
         * @param string $email
         */
        public function setEmail(string $email): void
        {
            $this->email = $email;
        }

        /**
         * @return bool
         */
        public function isEnabled(): bool
        {
            return $this->isEnabled;
        }

        /**
         * @param bool $isEnabled
         */
        public function setIsEnabled(bool $isEnabled): void
        {
            $this->isEnabled = $isEnabled;
        }

        /**
         * @return bool
         */
        public function isVerified(): bool
        {
            return $this->isVerified;
        }

        /**
         * @param bool $isVerified
         */
        public function setIsVerified(bool $isVerified): void
        {
            $this->isVerified = $isVerified;
        }

        /**
         * @return DateTime
         */
        public function getCreatedAt(): DateTime
        {
            return $this->createdAt;
        }

        /**
         * @param DateTime $createdAt
         */
        public function setCreatedAt(DateTime $createdAt): void
        {
            $this->createdAt = $createdAt;
        }

        /**
         * @return DateTime
         */
        public function getUpdatedAt(): DateTime
        {
            return $this->updatedAt;
        }

        /**
         * @param DateTime $updatedAt
         */
        public function setUpdatedAt(DateTime $updatedAt): void
        {
            $this->updatedAt = $updatedAt;
        }

        /**
         * String representation of object
         * @link http://php.net/manual/en/serializable.serialize.php
         * @return string the string representation of the object or null
         * @since 5.1.0
         * NOTE: SYNFONY BUG 3.4 -> 4.1; https://github.com/symfony/symfony-docs/pull/9914
         */
        public function serialize(): string
        {
            // add $this->salt too if you don't use Bcrypt or Argon2i
            return serialize([$this->id, $this->username, $this->password]);
        }

        /**
         * Constructs the object
         * @link http://php.net/manual/en/serializable.unserialize.php
         * @param string $serialized <p>
         * The string representation of the object.
         * </p>
         * @return void
         * @since 5.1.0
         */
        public function unserialize($serialized): void
        {
            // add $this->salt too if you don't use Bcrypt or Argon2i
            [$this->id, $this->username, $this->password] = unserialize($serialized, ['allowed_classes' => false]);
        }

        /**
         * Returns the roles granted to the user.
         *
         * <code>
         * public function getRoles()
         * {
         *     return array('ROLE_USER');
         * }
         * </code>
         *
         * Alternatively, the roles might be stored on a ``roles`` property,
         * and populated in any number of different ways when the user object
         * is created.
         *
         * @return array The user roles
         */
        public function getRoles(): array
        {
            $roles = [];
            foreach ($this->roles->toArray() AS $role) {
                $roles[] = $role->getName();
            }
            return $roles;
        }

        /**
         * Returns the password used to authenticate the user.
         *
         * This should be the encoded password. On authentication, a plain-text
         * password will be salted, encoded, and then compared to this value.
         *
         * @return string The password
         */
        public function getPassword(): string
        {
            return $this->password;
        }

        /**
         * @param string $password
         */
        public function setPassword(string $password): void
        {
            $this->password = $password;
        }

        /**
         * Returns the salt that was originally used to encode the password.
         *
         * This can return null if the password was not encoded using a salt.
         *
         * @return string|null The salt
         */
        public function getSalt()
        {
            // See "Do you need to use a Salt?" at https://symfony.com/doc/current/cookbook/security/entity_provider.html
            // we're using bcrypt in security.yml to encode the password, so
            // the salt value is built-in and you don't have to generate one

            return null;
        }

        /**
         * Returns the username used to authenticate the user.
         *
         * @return string The username
         */
        public function getUsername()
        {
            return $this->username;
        }

        /**
         * @param string $username
         */
        public function setUsername(string $username): void
        {
            $this->username = $username;
        }

        /**
         * Removes sensitive data from the user.
         *
         * This is important if, at any given point, sensitive information like
         * the plain-text password is stored on this object.
         */
        public function eraseCredentials()
        {
            // if you had a plainPassword property, you'd nullify it here
            $this->plainPassword = null;
        }
    }

Role.php file:

<?php

    namespace App\Entity;

    use DateTime;
    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\ORM\Mapping as ORM;

    /**
     * Role
     *
     * @ORM\Table(name="role", uniqueConstraints={@ORM\UniqueConstraint(name="name", columns={"name"})})
     * @ORM\Entity(repositoryClass="App\Repository\RoleRepository")
     */
    class Role
    {
        /**
         * @var ArrayCollection
         *
         * @ORM\ManyToMany(targetEntity="App\Entity\User", mappedBy="roles", cascade={"remove"})
         * @ORM\JoinTable(name="users_roles",
         *      joinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")},
         *      inverseJoinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")}
         *      )
         */
        protected $users;
        /**
         * @var int
         *
         * @ORM\Column(name="id", type="smallint", nullable=false, options={"unsigned"=true})
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
        /**
         * @var string
         *
         * @ORM\Column(name="name", type="string", length=255, nullable=false)
         */
        private $name;
        /**
         * @var DateTime
         *
         * @ORM\Column(name="created_at", type="datetime", nullable=false)
         */
        private $createdAt;
        /**
         * @var DateTime
         *
         * @ORM\Column(name="updated_at", type="datetime", nullable=false)
         */
        private $updatedAt;

        /**
         * Role constructor.
         */
        public function __construct()
        {
            $this->users = new ArrayCollection();
        }

        /**
         * @return array
         */
        public function getUsers(): array
        {
            return $this->users->toArray();
        }

        /**
         * @return int
         */
        public function getId(): int
        {
            return $this->id;
        }

        /**
         * @param int $id
         */
        public function setId(int $id): void
        {
            $this->id = $id;
        }

        /**
         * @return string
         */
        public function getName(): string
        {
            return $this->name;
        }

        /**
         * @param string $name
         */
        public function setName(string $name): void
        {
            $this->name = $name;
        }

        /**
         * @return DateTime
         */
        public function getCreatedAt(): DateTime
        {
            return $this->createdAt;
        }

        /**
         * @param DateTime $createdAt
         */
        public function setCreatedAt(DateTime $createdAt): void
        {
            $this->createdAt = $createdAt;
        }

        /**
         * @return DateTime
         */
        public function getUpdatedAt(): DateTime
        {
            return $this->updatedAt;
        }

        /**
         * @param DateTime $updatedAt
         */
        public function setUpdatedAt(DateTime $updatedAt): void
        {
            $this->updatedAt = $updatedAt;
        }
    }

My data fixtures AppFixtures.php:

<?php

    namespace App\DataFixtures;

    use App\Entity\Role;
    use App\Entity\User;
    use DateTime;
    use Doctrine\Bundle\FixturesBundle\Fixture;
    use Doctrine\Common\Persistence\ObjectManager;
    use Doctrine\ORM\EntityManagerInterface;
    use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

    /**
     * Class AppFixtures
     * @package App\DataFixtures
     */
    class AppFixtures extends Fixture
    {
        /**
         * @var UserPasswordEncoderInterface
         */
        private $encoder;
        /**
         * @var EntityManagerInterface
         */
        private $entityManager;

        /**
         * AppFixtures constructor.
         * @param UserPasswordEncoderInterface $userPasswordEncoder
         * @param EntityManagerInterface $entityManager
         */
        public function __construct(UserPasswordEncoderInterface $userPasswordEncoder, EntityManagerInterface $entityManager)
        {
            $this->encoder = $userPasswordEncoder;
            $this->entityManager = $entityManager;
        }

        /**
         * @param ObjectManager $manager
         */
        public function load(ObjectManager $manager)
        {
            //Creating default roles
            $role = new Role();
            $role->setName('ROLE_USER');
            $role->setCreatedAt(new DateTime());
            $role->setUpdatedAt(new DateTime());
            $manager->persist($role);
            $role = new Role();
            $role->setName('ROLE_MODERATOR');
            $role->setCreatedAt(new DateTime());
            $role->setUpdatedAt(new DateTime());
            $manager->persist($role);
            $role = new Role();
            $role->setName('ROLE_ADMIN');
            $role->setCreatedAt(new DateTime());
            $role->setUpdatedAt(new DateTime());
            $manager->persist($role);
            $manager->flush();
            $manager->clear();
            //Creating users
            $user = new User();
            $user->setUserName('john');
            $user->setEmail('john@localhost');
            //$user->setRoles(['ROLE_USER', 'ROLE_JOHN']);
            //$roleAssociation = null;
            $user->setPassword($this->encoder->encodePassword($user, 'test'));
            $user->setCreatedAt(new DateTime());
            $user->setUpdatedAt(new DateTime());
            $user->setIsVerified(true);
            $user->setIsEnabled(true);
            //$manager->persist($roleAssociation);
            $manager->persist($user);

            $user = new User();
            $user->setUserName('tom');
            $user->setEmail('tom@localhost');
            //$user->setRoles(['ROLE_USER', 'ROLE_TOM', 'ROLE_MODERATOR']);
            //$roleAssociation = null;
            $user->setPassword($this->encoder->encodePassword($user, 'test'));
            $user->setCreatedAt(new DateTime());
            $user->setUpdatedAt(new DateTime());
            $user->setIsVerified(true);
            $user->setIsEnabled(true);
            //$manager->persist($roleAssociation);
            $manager->persist($user);

            $user = new User();
            $user->setUserName('jimmy');
            $user->setEmail('jimmy@localhost');
            //$user->setRoles(['ROLE_USER', 'ROLE_JIMMY', 'ROLE_ADMIN']);
            //$roleAssociation = null;
            $user->setPassword($this->encoder->encodePassword($user, 'test'));
            $user->setCreatedAt(new DateTime());
            $user->setUpdatedAt(new DateTime());
            $user->setIsVerified(true);
            $user->setIsEnabled(true);
            //$manager->persist($roleAssociation);
            $manager->persist($user);

            $manager->flush();
            $manager->clear();
        }
    }

I'm looking for advises for:

  1. User entity is cached in annotation, because symfony on each request loads it. config part:

    orm:
        metadata_cache_driver:
          type: redis
        result_cache_driver:
          type: redis
        query_cache_driver:
          type: redis
    

I'm caching all the data for 1min in redis. Any better solution?

  1. DB schema creates Foreign Keys (FK) and extra indexes on users_roles table and I would love to not to have FK, because IMHO it's "heavy" thing. I would prefer to have primary key on (user_id,role_id) only. Any recommendations of this?

  2. The solution for having flexible add/remove for user + role + roles_users

Big thanks!

Load fixtures from custom bundle

$
0
0

I'm building a simple bundle for Symfony and I was wondering if I can run fixtures located in there since it is not in the project src root folder. This is my project structure:

Project
|
+--AdminBundle <- My custom bundle
|  +--Controller
|  +--DataFixtures
|  |  |
|  |  +--AdminFixtures.php <- The fixtures I want to run
|  | 
|  +--DependencyInjection
|  +--Entity
|  +--Resources
|
+--assets
+--bin
+--config
+--public
+--src
+--templates
+--vendor

This is the code of AdminFixtures.php


namespace ExampleVendor\AdminBundle\DataFixtures;

use App\AdminBundle\Entity\User;
use App\AdminBundle\Entity\Profile;
use Doctrine\Bundle\FixturesBundle\Fixture;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Bundle\FixturesBundle\ORMFixtureInterface;
use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class AdminFixtures extends Fixture implements FixtureGroupInterface {
    private $passwordEncoder;


    public function __construct(UserPasswordEncoderInterface $passwordEncoder) {
        $this->passwordEncoder = $passwordEncoder;
    }

    public function load(ObjectManager $manager) {
        // Fixtures stuff
    }

    /**
     * This method must return an array of groups
     * on which the implementing class belongs to
     *
     * @return string[]
     */
    public static function getGroups(): array {
        return ['admin'];
    }
}

When I run php bin/console doctrine:fixtures:load I get an error that says:

[ERROR] Could not find any fixture services to load.

I read something that every class that implements FixtureGroupInterface will be automatically registered as fixture but I think that is not working since I am here crying for help.

How can I register it manually as fixture? how to make php bin/console doctrine:fixtures:load command work??

How to start local server with symfony 5 or downgrade version to 4.4?

$
0
0

I started a new project in new Symfony 5 and i can't open my local server.

On symfony 4.4 the command PHP bin/console server:run is OK, but with Symfony 5 the command is not defined...

C:\Users\Chris\Code\api-test> php bin/console server:run
Command "server:run" is not defined.
Do you want to run "server:dump" instead?  (yes/no) [no]:

So how to downgrade or start the local server, for start the server I follow this document.

https://symfony.com/doc/current/setup/web_server_configuration.html

But I did not understand that...

How to register twig filter into Symfony 4?

$
0
0

I have a problem of registration with my custom twig extension in Symfony 4 . I have create extension who help me to decode my json data but it's not work. This message is display when I want to use my json_decode filter. Error message

The code of my custom twig filter :

<?php
namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AppExtension extends AbstractExtension
{
    public function getName() {
        return 'Json Decode';
    }

    public function getFunctions()
    {
        return [
            new TwigFilter('json_decode', [$this, 'json_decode']),
        ];
    }

    public function json_decode($input, $assoc = false) {
       return json_decode($input,$assoc);
    }
}
?>

Here is a twig_exension.yaml

services:
    _defaults:
        public: false
        autowire: true
        autoconfigure: true

    # Uncomment any lines below to activate that Twig extension
    #Twig\Extensions\ArrayExtension: null
    #Twig\Extensions\DateExtension: null
    Twig\Extensions\IntlExtension: null
    Twig\Extensions\TextExtension: null
    App\Twig\AppExtension: null

Here is the line that return and error in my twig file

{% set commande = render(controller('App\\Controller\\StoreController::getProduitsCommandes')) | json_decode  %}

Here is the Response return in StoreController.php

$response = new Response(json_encode(["produits"=>$produitsArray,"total_ht"=>$total_ht,"tva"=>$tva,"nbre_produits"=>$nbre_produits]));
$response->headers->set('Content-Type', 'application/json');
return $response;

When I type php bin/console debug:twig --filter=json_decode The debugger return me this result

---------

* json_decode(input, assoc = false)

Thank you for your attention If any people has a solution it will help me

Viewing all 3925 articles
Browse latest View live