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

Symfony 4: use localizeddate

$
0
0

I am trying to use localizeddate to show a date in French on my website:

<td>{{ saison.start|localizeddate('medium', 'none') }}</td>

I followed the various documentations and:

  • I installed the PHP Intl extension: sudo pacman -S php-intl
  • I installed Twig extensions on Symfony: composer require twig/extensions
  • As well in Intl extension: composer require symfony/intl

I also edited config/services.yaml to change the locale, but it does not seem to have an effect:

parameters:
    locale: 'fr'

I enabled Date and Intl extensions in files configpackages\twig_extensions.yaml`:

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

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

But I still have the date shown in english in the output file.

I also tried to specify more clearly the locale in localizeddate like this:

<td>{{ saison.start|localizeddate('medium', 'none', 'fr') }}</td>

But in this case I get an error:

An exception has been thrown during the rendering of a template ("The Symfony\Component\Intl\DateFormatter\IntlDateFormatter::__construct() method's argument $locale value 'fr' behavior is not implemented. Only the locale "en" is supported. Please install the "intl" extension for full localization capabilities.").

I don't know what is missing.


how to use Social login with api-platform and angular 8

$
0
0

i'm developing a symfony 4 backend using api-platform and angular 8 for the frontend. i already make an authentication system with api-platform using JWT and i want to add the possibility to login and signup with social network. The problem is that i found that all website like google and facebook are using OAuth, so i didn't know if i should change my authentication system to use OAuth or no. And the second problem, i didn't know if i should implement the social login in the front app or the back

how could i add an entity in this class

$
0
0

hello, a friend tell me i coulld use handler and abstract cllass for handlle my symfony forms.

I'm new in symfony and try do llike he say,

some parts are ok, but it's not so easy

I had this three part code.

I use it here : create ==> it's ok

I want use the Handler in : show

The problem is i need send entity user and trick in my handler.

if you have an idea, i take and try it :)

thanks a lot

controller

<?php

namespace App\Controller;

use App\Entity\Comment;
use App\Entity\Trick;
use App\Form\CommentType;
use App\Form\TrickType;
use App\Handler\CommentHandler;
use App\Handler\TrickHandler;
use App\Repository\CommentRepository;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use App\Repository\TrickRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class TrickController extends AbstractController
{
    private $trickRepository;

    public function __construct(TrickRepository $trickRepository, CommentRepository $commentRepository)
    {
        $this->trickRepository = $trickRepository;
        $this->commentRepository = $commentRepository;

    }


    /**
     * @Route("/trick/{slug}", name="trick.show", requirements={"slug": "[a-z0-9\-]*"})
     * @return Response
     */
    public function show(Trick $trick, Request $request,CommentHandler $handler): Response
    {
        $comment = new Comment();
        $form = $this->createForm(CommentType::class, $comment)->handleRequest($request);
        $user = $this->getUser();
        $displayedComments = $this->commentRepository->getAllComments(1);

        if ($form->isSubmitted() && $form->isValid()) {
            $comment->setTrick($trick);
            $comment->setAuthor($user);
            $this->getDoctrine()->getManager()->persist($comment);
            $this->getDoctrine()->getManager()->flush();
            $slug = $trick->getSlug();

            return $this->redirectToRoute("trick.show",array('slug' => $slug));

        }
        return $this->render('pages/trick/show.html.twig',[
                'trick' => $trick,
                'displayedComments' => $displayedComments,
                'current_menu'=>'home',
                "form" => $form->createView()
            ]
        );
    }


    /**
     * @Route("/create", name="trick_create")
     * @param Request $request
     * @param TrickHandler $handler
     * @return Response
     */
    public function create(Request $request,TrickHandler $handler): Response
    {
        if($handler->handle($request, new Trick(), ["validation_groups" => ["Default", "add"]        ]
        )) {
            return $this->redirectToRoute("trick_create");
        }
        return $this->render("admin/trick/create.html.twig", [
            "form" => $handler->createView()
        ]);
    }
}

AbstractHandler

<?php

namespace App\Handler;


use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Test\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\FormFactoryInterface;

abstract class AbstractHandler
{
    /**
    * @var FormFactoryInterface
     */

    private $formFactory;

    /**
     * @var FormInterface
     */
    private $form;

    /**
     * @return string
     */
    abstract protected function getForm() : string;

    /**
     * @param $data
     * @param array $entities
     */
    abstract protected function process($data) : void;

    /**
     * @required
     * @param FormFactoryInterface $formFactory
     */
    public function setFormFactory(FormFactoryInterface $formFactory) :void
    {
        $this->formFactory = $formFactory;
    }

    /**
     * @param Request $request
     * @param $data
     * @param array $options
     * @return bool
     */
    public function handle(Request $request, $data, array $options = []) :bool
    {
        $this->form = $this->formFactory->create($this->getForm(), $data, $options)->handleRequest($request);
        if ($this->form->isSubmitted() && $this->form->isValid()) {
            $this->process($data);
            return true;
        }
        return false;
    }
    public function createView() :FormView
    {
        return $this->form->createView();
    }
}

CommentHandler

<?php
/**
 * Created by PhpStorm.
 * User: khysh
 * Date: 10/03/2020
 * Time: 19:13
 */

namespace App\Handler;

use App\Form\CommentType;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\UnitOfWork;

class CommentHandler extends AbstractHandler
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * TrickHandler constructor.
     * @param EntityManagerInterface $entityManager
     */
    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    protected function getForm(): string
    {
        // TODO: Implement getForm() method.
        return CommentType::class;
    }

    /**
     * @param $data
     * @param array $entities
     */
    protected function process($data): void
    {
        // TODO: Implement process() method.
        if ($this->entityManager->getUnitOfWork()->getEntityState($data) === UnitOfWork::STATE_NEW) {
            $this->entityManager->persist($data);
        }
        $this->entityManager->flush();

    }

}

How to cache DynamoDB credentials using symfony 4

$
0
0

symfony: 4.4

aws-php-sdk: 3.83

I injected the Aws\DynamoDb\DynamoDbClient using Symfony 4 services like this:

Aws\DynamoDb\DynamoDbClient:
    arguments:
        -
            region: '%dynamodb.region%'
            version: 'latest'
            endpoint: '%dynamodb.client.endpoint%'
            credentials:
                key: '%dynamodb.client.key%'
                secret: '%dynamodb.client.secret%'
            http:
                connect_timeout: 0.3
                timeout: 1
            retries: 0
            validate: '%dynamodb.client.validate%'

How would I cache the credentials to don't call each time?

delete delete action cascade symfony

$
0
0

Good morning all,

I am looking for a solution to cascade delete data from my table.

I have an Orders table:

    class Order
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups({"orderGET", "orderDELETE", "orderPostCustomer"})
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"orderGetItem", "orderPostCustomer", "orderTracking"})
     */
    private $firstname;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"orderGetItem", "orderPostCustomer", "orderTracking"})
     */
    private $lastname;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"orderGetItem", "orderPostCustomer", "orderTracking"})
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"orderGetItem", "orderPostCustomer", "orderTracking"})
     */
    private $phone;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"orderGetItem", "orderPostCustomer", "orderTracking"})
     */
    private $address;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"orderGetItem", "orderPostCustomer", "orderTracking"})
     */
    private $address1;

    /**
     * @ORM\Column(type="integer")
     * @Groups({"orderGetItem", "orderPostCustomer", "orderTracking"})
     */
    private $zipcode;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"orderGET", "orderPostCustomer", "orderTracking"})
     */
    private $city;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"orderGetItem", "orderPostCustomer", "orderTracking"})
     */
    private $country;

    /**
     * @ORM\Column(type="string", length=2000, nullable=true)
     * @Groups("orderGetItem")
     */
    private $urlTracking;

    /**
     * @ORM\Column(type="string", length=2000, nullable=true)
     * @Groups("orderGetItem")
     */
    private $urlTracking;

    /**
     * @ORM\Column(type="integer")
     * @Groups({"orderGetItem", "orderPostCustomer"})
     */
    private $idOrderMerchant;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     * @Groups({"orderGET"})
     */
    private $idTrackingMerchant;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     * @Groups("orderGET")
     */
    private $idTracking;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\OrderHistory", mappedBy="orderId", cascade={"persist", "remove"})
     * @Groups({"orderGetItem", "orderTracking"})
     */
    private $orderHistories;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\OrderHistory", cascade={"persist", "remove"})
     * @ORM\JoinColumn(name="last_history_id", referencedColumnName="id")
     * @Groups({"orderGetCollection", "orderTracking"})
     */
    private $lastHistory;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Customer", inversedBy="orders")
     * @ORM\JoinColumn(nullable=true)
     * @Groups({"orderGET", "orderTracking"})
     */
    private $customer;

    /**
     * @ORM\Column(type="integer")
     * @Groups({"orderGetItem", "orderPostCustomer"})
     */
    private $weightMerchant;

    /**
     * @ORM\Column(type="integer", nullable=true)
     * @Groups("orderGetItem")
     */
    private $weightReal;

    /**
     * @ORM\Column(type="integer")
     * @Groups({"orderGetItem", "orderPostCustomer", "orderTracking"})
     */
    private $packages;

    /**
     * @ORM\Column(type="datetime")
     * @Groups("orderGET")
     */
    private $dateAdd;

    /**
     * @ORM\Column(type="datetime")
     * @Groups("orderGET")
     */
    private $dateUpd;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\OrderDetail", mappedBy="orderId", cascade={"persist", "remove"})
     * @Groups({"orderGetItem", "orderPostCustomer"})
     */
    private $orderDetails;
}

and I have relation with several table: order_history, order_details.

I am looking to delete the order information in the other tables (order_history and order_details) when I delete an order. I tried by adding the parameters "Cascade" etc .... but its does not work I have this error:

"hydra:description": "An exception occurred while executing 'DELETE FROM order_history WHERE id = ?' with params [7]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (db_api_dev.order, CONSTRAINT order_ibfk_3 FOREIGN KEY (last_history_id) REFERENCES order_history (id))",

Thank you for your help

Endpoint Server GraphQL (overblog-GraphQLBundle) Not support Method POST

$
0
0

For 3 Days, my project which worked perfectly locally, once put on the production server. GraphQl requests are a failure with the error "[Error: Network error: JSON Parse error: Unrecognized token '<']" and after log analysis it is a 404 error because the route was not found.

After investigation via the GraphQl Atlair client for chrome by changing the method to GET to make my GrasphQl requests, the error everything works.

my question is how to work the POST method?

I really need to use the METHOD POST for mutations Thanks everyone Very cordially

PHPunit execute tests with wrong PDO driver in Symfony 4

$
0
0

I have a PHP unit working on a remote interpreter perfectly.

It work in all cases without PHP Storm (I.E. using the same command in command line on the docker)

Here is the command command executed by phpstorm, and its the one i try in all situation to compare: php /var/www/privateapi/vendor/bin/simple-phpunit --bootstrap /var/www/privateapi/tests/bootstrap.php --configuration /var/www/privateapi/phpunit.xml.dist --teamcity --cache-result-file=/va r/www/privateapi/.phpunit.result.cache

In PhpStorm when I run tests that should communicate with database, it fails because it tries to use a MYSQL driver and I use PGSQL.

Summary:

Working cases:

  • In commandline, on the docker, with or without DB Tests
  • In commandline, outside the docker (i.e. docker exec -it ... ), with or without DB Tests
  • With PHPStorm, with remote interpreter, without DB Tests

Failing case:

  • With PHPStorm, with remote interpreter, with DB Tests

Here is my conf :

app/config/packages/test/doctrine.yaml

doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL_TEST)%'
        driver: 'pdo_pgsql'
        mapping_types:
            container_mode: string
            network_provider: string
            sensor_status: string
            notification_channel: string
        server_version: 11
    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

app/phpunit.xml.dist

<?xml version="1.0" encoding="UTF-8"?>

<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/7.5/phpunit.xsd"
         backupGlobals="false"
         colors="true"
         bootstrap="tests/bootstrap.php">
    <php>
        <ini name="error_reporting" value="-1" />
        <server name="SHELL_VERBOSITY" value="-1" />
        <server name="SYMFONY_PHPUNIT_REMOVE" value="" />
        <server name="SYMFONY_PHPUNIT_VERSION" value="7.5" />
        <env name="APP_ENV" value="test" />
        <env name="KERNEL_CLASS" value="App\Kernel" />
    </php>

    <testsuites>
        <testsuite name="Project Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
            <exclude>
                <file>src/Kernel.php</file>
                <file>src/Event/Listener/JsonToHtmlDevEventListener.php</file>
            </exclude>
        </whitelist>
    </filter>

    <listeners>
        <listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener" />
    </listeners>
</phpunit>

It works well with any code, but as soon as I want to test some use case with Database like this one :

app/tests/Security/Voter/OrganizationVoterTest.php

class OrganizationVoterTest extends KernelTestCase
{
    private ?OrganizationVoter $voter;
    private ?UserRepository $userRepository;
    private ?OrganizationRepository $orgaRepository;

    protected function setUp()
    {
        self::bootKernel();
        $container = self::$container;
        $this->voter = $container->get(OrganizationVoter::class);
        $this->userRepository = $container->get('doctrine')->getRepository(User::class);
        $this->orgaRepository = $container->get('doctrine')->getRepository(Organization::class);

        parent::setUp();
    }

    public function testGetMinRequiredLevel()
    {
        $orga = $this->orgaRepository->findOneBy(['name' => 'orga1']);
        [....]
    }
}

I will get the following error :

Doctrine\DBAL\Exception\DriverException : An exception occurred in driver: could not find driver
 /var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:106
 /var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:166
 /var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:154
 /var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php:28
 /var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:362
 /var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:1443
 /var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:890
 /var/www/privateapi/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php:718
 /var/www/privateapi/vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php:193
 /var/www/privateapi/tests/Security/Voter/OrganizationVoterTest.php:32

Symfony - Get security.token_storage in Sylius repositories

$
0
0

I have tried to inject security.token_storage service via CompilerPass, I do not have errors and user is currently logged, however when I access the TokenStorage, $tokenStorage->getToken() I got a null response.

I checked these links to reference, but I cannot achieve to get a valid token.

How to inject shared service from compiler pass in Symfony and Access currently logged in user in UserRepository in Sylius

Do you an idea why it returns null response?

  • Sylius version: 1.4 and Symfony 4.4

Bundle class:

   public function build(ContainerBuilder $container)
   {
       parent::build($container);
       $container->addCompilerPass(new ModifyRepositoryPass());
   }

ModifyRepositoryPass class:

class ModifyRepositoryPass implements CompilerPassInterface
{

   public function process(ContainerBuilder $container)
   {
       $container
           ->getDefinition('sylius.repository.order')
           ->addMethodCall('getTokenStorage', array(
               new Reference('security.token_storage')
           ));

    }
  }

Get token:

class OrderRepository extends BaseOrderRepository
{

    /** @var TokenStorageInterface */
    protected $tokenStorage;

    public function getTokenStorage(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function createListFilter()
    {

        $token = $this->tokenStorage->getToken()); //  NULL token
    }



Strange Issue With Entity Relationship in Symfony 4

$
0
0

This is a very odd one, i'll try to explain with couple of sample entities.

class Property{

    /**
     * @var string
     * @ORM\Column(type="string", length=10)
     */
    private $postCode;


    /**
     * @var InstructionToSell
     * @ORM\OneToOne(targetEntity="App\Entity\InstructionToSell")
     * @ORM\JoinColumn(nullable=true)
     */
    private $instructionToSell;

}

class InstructionToSell{

    /**
     * @var Property
     * @ORM\OneToOne(targetEntity="App\Entity\Property")
     * @ORM\JoinColumn(nullable=true)
     */
    private $property;

}

So two sample entities, the property can have an instruction to sell entity and vice versa. I then have a very basic post code search method in the repo:

/**
     * @param string $postCode
     * @return array|null
     */
    public function searchByPostcode(string $postCode) : ?array{

        $builder = $this->createQueryBuilder('p');

        $builder->where(
            $builder->expr()->like('p.postCode',':postCode')
        )->setParameter('postCode',str_replace('','','%'.$postCode.'%'));

        return $builder->getQuery()->getResult();
    }

It all works fine except for one very strange thing. If say a property had the Uk post code of "YO12 7YA" and we run a search for "YO127YA" then it's bringing back a result, but if we use "YO12 7YA" it's bringing back a result but the instructionToSell is null on the property, but it's not null if i remove the space from the search term.

I'm aware this search isn't the best as it stands, need to strip spaces out of the column as well, but the point i am making is, the same code runs for "YO12 7YA" and "YO127YA" which brings back the same property, but one of them has the relationship matched to the instruction to sell, the other it's null.

Why would this happen? It's exactly the same property it's bringing back.

Solving Recursion issues with Symfony and JsonSerializable

$
0
0

I'm looking for some input on recursion issues in doctrine entities using Symfony. A lot of the time we are running into this problem when we use JsonSerializable.

It makes total sense why this happens but it's extremely annoying when you're using a lot of related entities that needs to be serialized.

I know there are other libraries for seralizing with depth monitoring, but those aren't quite as convenient as JsonSerializable; especially when an entire project is already built this way.

Is there any way to limit the depth with JsonSeralizable?

Attempted to call an undefined method named "redirect" error in Symfony 4

$
0
0

i have this error in my code and I have writing the "use" but i have this error:

Attempted to call an undefined method named "redirect" of class "App\Controller\SetlocaleController".

My code:

<?php 

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SetlocaleController extends HomeController {

    public function __construct(\Twig\Environment $twig)
    {
        $this->twig = $twig;
    }

    public function setLocaleAction(Request $request, $language = null)
    {
        if($language != null)
        {
            $session->set('_locale', $language);
        }

        $url = $request->headers->get('referer');
        if(empty($url))
        {
            return new response($this->twig->render('page/home.html.twig'));
        }
        else{
            return $this->redirect($url);
        }
    }
}

You have an answer for me please ?

Symfony 4 - Good practice to remove your own user account while connected

$
0
0

I would like my users to be able to delete their own user account. I made a SecurityController where there is my 3 functions login, logout and deleteUser. When I delete the current user in database this error appears :

You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine.

When I delete another user, it works correctly because he's not connected. Do I have to serialize the User and pass it through a Service, logout the user then remove it in a Service? Or can I clear the PHP session in the controller but I don't know how to do it with I think it changed since version 4.

<?php

namespace App\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;

use App\Entity\User;
use App\Form\UserType;

class SecurityController extends Controller
{
  /**
   * @Route("/createAdmin", name="create_admin")
   */
    public function createAdminUser(Request $request, UserPasswordEncoderInterface $passwordEncoder)
    {
      $usersRepo = $this->getDoctrine()->getRepository(User::class);
      $uCount = $usersRepo->countAllUsers();

      if ($uCount == 0)
      {
        $user = new User();
        $form = $this->createForm(UserType::class, $user, array(
          'is_fresh_install' => true,
        ));

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            // Encode the password
            $password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);

            // save the User
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            // Do what you want here before redirecting the user

            return $this->redirectToRoute('login');
        }

        return $this->render('security/register_admin_user.html.twig', array(
          'form' => $form->createView(),
        ));
      } else {
        if ($this->getUser())
        {
          return $this->redirectToRoute('user_account');
        } else {
          return $this->redirectToRoute('login');
        }
      }
    }

    /**
     * @Route("/login", name="login")
     */
    public function login(Request $request, AuthenticationUtils $authUtils)
    {
      $usersRepo = $this->getDoctrine()->getRepository(User::class);
      $uCount = $usersRepo->countAllUsers();

      if ($uCount == 0)
      {
        return $this->redirectToRoute('create_admin');
      } else {
        $error = $authUtils->getLastAuthenticationError();
        $lastUsername = $authUtils->getLastUsername();

        return $this->render('security/login.html.twig', array(
         'last_username' => $lastUsername,
         'error'         => $error,
        ));
      }
    }

    /**
     * @Route("/logout", name="logout")
     */
    public function logout()
    {

    }

    /**
     * @Route("/delete_user/{id}", name="delete_user")
     */
    public function deleteUser($id)
    {
      $em = $this->getDoctrine()->getManager();
      $usrRepo = $em->getRepository(User::class);

      $user = $usrRepo->find($id);
      $em->remove($user);
      $em->flush();

      return $this->redirectToRoute('user_registration');

    }

}

Docker or symfony missconfig. error SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known

$
0
0

How can I fix this? Is this a miss config in docker-compose or maybe is a miss config in PHP-fpm or I should do something in simfony env. I really don't know what to change. If I call doctrine from console require localhost as host and when the browser use pdo need to have host as MySQL (the docker name)

Very strange issue. After hours of debugging I find out why doctrine:migrations:migrate failed

C:\Users\Admin\Development\lemp\www\web>php bin/console doctrine:migrations:migrate 

returning the following error:

An exception occurred in driver: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.

I found out that runing migration is working if I replace the host in the .env file:

DATABASE_URL=mysql://dummy:dummy@mysql:3306/dummy?serverVersion=5.7 with DATABASE_URL=mysql://dummy:dummy@localhost:3306/dummy?serverVersion=5.7

But a new problem arose. The http://localhost:8080/ require the old env with mysql to run: DATABASE_URL=mysql://dummy:dummy@mysql:3306/dummy?serverVersion=5.7

You can find all the config file in my public repo: https://github.com/dumitriucristian/nginx-server

This is my docker-compose.yml content

version: '3'
# https://linoxide.com/containers/setup-lemp-stack-docker/
# http://www.inanzzz.com/index.php/post/zpbw/creating-a-simple-php-fpm-nginx-and-mysql-application-with-docker-compose
#https://www.pascallandau.com/blog/php-php-fpm-and-nginx-on-docker-in-windows-10/
#http://www.inanzzz.com/index.php/post/0e95/copying-symfony-application-into-docker-container-with-multi-stage-builds
#https://learn2torials.com/a/dockerize-reactjs-app
#https://knplabs.com/en/blog/how-to-dockerise-a-symfony-4-project
services:
  nginx:
    build:
     context: .
     dockerfile: docker/nginx/Dockerfile
    ports:
      - "8080:80"
    volumes:
     - ./nginx-server/logs:/var/log/nginx
     - ./nginx-server/default.conf:/etc/nginx/conf.d/default.conf
     - ./www/:/srv/www
    depends_on:
     - phpfpm

  phpfpm:
    build:
       context: .
       dockerfile: docker/phpfpm/Dockerfile
    ports:
     - "9000:9000"
    volumes:
     - ./www:/srv/www
     - ./docker/phpfpm/default.conf:/usr/local/etc/php-fpm.d/default.conf
    environment:
      MYSQL_USER: "dummy"
      MYSQL_PASSWORD: "dummy"

  mysql:
    image: mysql:5.7
    ports:
        - 3306:3306
    depends_on:
        - phpfpm
    environment:
        MYSQL_ROOT_PASSWORD: "dummy"
        MYSQL_DATABASE: "dummy"
        MYSQL_USER: "dummy"
        MYSQL_PASSWORD: "dummy"

  app:
    build:
      context: .
      dockerfile: docker/app/Dockerfile
    environment:
      - NODE_ENV=test
    command: npm run start
    ports:
      - 3000:3000
    volumes:
      - ./app:/app

nginx\Dockerfile

FROM nginx:latest
RUN apt-get update && apt-get install -y unzip zlib1g-dev git curl libmcrypt-dev bcrypt nano man

COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer

WORKDIR /usr/src
RUN mkdir -p web
COPY ./www/web /usr/src/web

RUN PATH=$PATH:/web/vendor/bin:bin


EXPOSE 9000
EXPOSE 80

phpfpm\Dockerfile

FROM php:7.4.0-fpm-alpine

RUN apk update \
 && apk add --no-cache $PHPIZE_DEPS \
    git \
    zip \
    unzip \
 && docker-php-ext-install \
    opcache \
    pdo_mysql \
 && docker-php-ext-enable \
    opcache \
 && rm -rf \
    /var/cache/apk/* \
    /var/lib/apt/lists/*

COPY ./docker/phpfpm/php.ini /usr/local/etc/php/conf.d/php.override.ini
COPY ./nginx-server/default.conf /usr/local/etc/php-fpm.d/default.conf``

and nginx default.conf

  server {
        listen       0.0.0.0:80;
        listen       [::]:80 default_server;
        server_name  _;
        root  /srv/www/web/public;
        index index.htm index.html index.php ;

        default_type text/html;

        location ~* \.php$ {
            try_files $uri $uri/ /index.php;
            fastcgi_pass   phpfpm:9000;
           #fastcgi_pass unix:/run/php/php7.4-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
           #fastcgi_pass unix:/tmp/phpcgi.socket;
            fastcgi_param SCRIPT_NAME  $fastcgi_script_name;
            fastcgi_index  index.php;
            include fastcgi_params;
        }

    }

Thanks, I am new to dev-ops but I try.

Symfony 4: Execute standalone service without it being specifically referenced somewhere

$
0
0

I have written a standalone service I would like to have executed at the start of every page request in the container without it being referenced by any specific controller in example.

My thinking right now goes in the following direction: Creating a compiler pass:

class SchedulerCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        // always first check if the primary service is defined
        if (!$container->has(TestService::class)) {
            return;
        }

        $definition = $container->findDefinition(TestService::class);

        // find all service IDs with the app.mail_transport tag
        $taggedServices = $container->findTaggedServiceIds('app.service.standalone');

        foreach ($taggedServices as $id => $tags) {
            $definition->addMethodCall('someFunctionName', arguments);
        }
    }
}

but the "someFunctionName" function from the service is never called although I have assigned the correct tag to it and the compiler pass is executed correctly and without error.

Am I forgetting something?

OR

Is there a better way to just have this service executed?

Thanks in advance!

Knp_paginator template issue

$
0
0

I have a small issue on symfony 4.12 with knp_paginator bundle I want to apply a template for it I create a knp_paginator.yaml in config/packages/test because it didn't generate it

knp_paginator: page_range: 5
page_name: page
sort_field_name: sort
sort_direction_name: direction
distinct: true
filter_field_name: filterField filter_value_name: filterValue
template: pagination: '@KnpPaginator/Pagination/twitter_bootstrap_v3_pagination.html.twig' sortable: '@KnpPaginator/Pagination/twitter_bootstrap_v3_sortable_link.html.twig'

and in my repository

 $query=$query->getQuery();
    return $this->paginator->paginate(
        $query,
        1,
        2
    );

I tried all things but the only result I obtain is the simple paginator : <<<12>>>


Data Transformer vs.Constraints

$
0
0

I stumbled upon a question regarding Symfony's DataTransformers and how to properly use them. While I know how to implement and add them to my form field, I was wondering how DataTransformers are supposed to be combined with Constraints.

The following code shows my use case.

The Form

<?php

namespace AppBundle\Form;

use Passioneight\Bundle\FormBuilderBundle\Form\AbstractForm;
use Passioneight\Bundle\FormBuilderBundle\Form\DataTransformer\Consent\ConsentTransformer;
use Passioneight\Bundle\FormBuilderBundle\Form\Field\Button\SubmitButton;
use Passioneight\Bundle\FormBuilderBundle\Form\Field\Checkbox\AccountConsentField;
use Passioneight\Bundle\FormBuilderBundle\Form\Field\Text\EmailField;
use Passioneight\Bundle\FormBuilderBundle\Form\Field\Text\RepeatedField\RepeatedPasswordField;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RegistrationForm extends AbstractForm
{
    const OPTION_TERMS_AND_CONDITIONS_HREF = "terms-and-conditions-href";

    /** @var ConsentTransformer $consentTransformer */
    private $consentTransformer;

    /**
     * RegistrationForm constructor.
     * @param ConsentTransformer $consentTransformer
     */
    public function __construct(ConsentTransformer $consentTransformer)
    {
        $this->consentTransformer = $consentTransformer;
    }

    /**
     * @inheritDoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addField(new EmailField());
        $builder->addField(new RepeatedPasswordField());
        $builder->addField(new AccountConsentField([
            'label_translation_parameters' => [
                '{{ href }}' => $options[self::OPTION_TERMS_AND_CONDITIONS_HREF],
                '{{ href-class }}' => 'text-primary-hover'
            ],
        ]));
        $builder->get(AccountConsentField::NAME)->addModelTransformer($this->consentTransformer);

        $builder->addField(new SubmitButton([
            'label_format' => 'form.registration.%name%',
            'attr' => [
                'class' => 'btn-primary btn-raised m-0'
            ]
        ]));
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        $this->allowOption($resolver, self::OPTION_TERMS_AND_CONDITIONS_HREF, "#");
    }
}

Wondering about the way form fields are added to the form? That's because I'm using my bundle. It's essentially the same as $builder->addField(...);, only that any predefined fields in the bundle can be added in a more convenient way.

The Model

<?php

class User extends Concrete implements \Pimcore\Model\DataObject\DirtyIndicatorInterface
{
    protected $accountConsent;

    /**
    * Get accountConsent - Account Consent
    * @return \Pimcore\Model\DataObject\Data\Consent
    */
    public function getAccountConsent () {
        if($this instanceof PreGetValueHookInterface && !\Pimcore::inAdmin()) { 
            $preValue = $this->preGetValue("accountConsent"); 
            if($preValue !== null) { 
                return $preValue;
            }
        } 

        $data = $this->accountConsent;

        if ($data instanceof \Pimcore\Model\DataObject\Data\EncryptedField) {
            return $data->getPlain();
        }

        return $data;
    }

    /**
    * Set accountConsent - Account Consent
    * @param \Pimcore\Model\DataObject\Data\Consent $accountConsent
    * @return \Pimcore\Model\DataObject\User
    */
    public function setAccountConsent ($accountConsent) {
        $fd = $this->getClass()->getFieldDefinition("accountConsent");
        $this->accountConsent = $accountConsent;
        return $this;
    }
}

A lot of code was omitted for the sake of brevity. The model is a Pimcore class, which also holds the code required for mapping the other form fields (such as EmailField).

The DataTransformer

<?php

namespace Passioneight\Bundle\FormBuilderBundle\Form\DataTransformer\Consent;

use Pimcore\Model\DataObject\Data\Consent;
use Symfony\Component\Form\DataTransformerInterface;

class ConsentTransformer implements DataTransformerInterface
{
    /**
     * @inheritDoc
     * @param Consent|null $consent
     */
    public function transform($consent)
    {
        return $consent instanceof Consent && $consent->getConsent();
    }

    /**
     * @inheritDoc
     * @param bool|null $consented
     */
    public function reverseTransform($consented)
    {
        $consent = new Consent();
        $consent->setConsent($consented ?: false);
        return $consent;
    }
}

As you can see any submitted value (i.e., null, true, false) will be converted to a Consent and vice-versa.

Building the Form

<?php

namespace AppBundle\Controller;

use AppBundle\Form\RegistrationForm;
use Pimcore\Model\DataObject\User;
use Passioneight\Bundle\FormBuilderBundle\Service\FormBuilderService;

/**
* Class AuthController
* @package AppBundle\Controller
*
* @Route("/{_locale}")
*/
class AuthController extends AbstractFrontendController
{
    /**
    * @Route("/registration")
    *
    * @param FormBuilderService $formBuilderService
    */
    public function registrationAction(FormBuilderService $formBuilderService)
    {
        $options = [
            RegistrationForm::OPTION_TERMS_AND_CONDITIONS_HREF => "/url/to/TACs",
        ];

        $formEvent = $formBuilderService->buildForm(RegistrationForm::class, new User(), $options);
        $this->view->registrationForm = $formEvent->getFormView();
    }
}

Note how a new User() is passed as entity in order to automatically populate it with the submitted values.

The FormBuilderService is also available in my bundle, as it is just some convience class to avoid doing the same thing over and over again for each form.

The Problem

The form can be built just fine, ultimately, displaying a checkbox with my specified label. Due to the transformer, the checked-state is even correctly displayed, as the transform method converts the Users Consent into a boolean (even if no Consent was set yet).

However, when submitting the form an error is displayed, saying that the account consent is required. While this is fine when it comes to submitting the form without giving consent, it's not quite the desired outcome when acutally consenting.

The submitted value is converted to a Consent, which will then hold the value true. But since the transformation is done before the submitted value is validated the beforementioned error is displayed. This happens, because the AccountConsentField that was added in the form has a Constraint set, namely, IsTrue. Due to this, the IsTrueValidator validates the Consent (instead of the actually submitted value).

Obviously, the IsTrueValidator cannot know about Pimcore's Consent class. So, I've found the following workarounds.

Known Workarounds

  1. Removing the IsTrue-constraint.

    By doing so, the value is not validated anymore, but that's not a good idea - for obvious reasons.

  2. Same as 1., but with the validation in the transformer (i.e., by throwing the TransformationFailedException if the user did not consent).

    This way the value is still validated, but a DataTransformer should not handle validation (which others think too).

  3. Leaving the transformation to the developer.

    Well, obviously I don't want to go with this option, because I want to ease these kind of things for the developers.

All of these workarounds also leave me with the problem of a possible combination of the DataTransformer and any Constraint when a developer is not aware of this issue.

Side-Note: I labled this "workarounds" because these solutions just don't feel like the proper way to go.

The Question

All of this leaves me with the question: how do I properly combine the IsTrue-constraint with my ConsentDataTransformer?


What else I tried

  • Using a NotBlank-constraint instead of the IsTrue-constraint. The reason being that this Constraint allows to define a normalizer, which could transform the Consent back to a boolean for the NotBlankValidatoronly.

    If only the normalizer was called independent of the value's data type (currently only string is supported).

  • Extending the IsTrue-constraint in order to override the validatedBy method.

    While this allows me to create a custom validator that is aware of the Consent class, the developer needs to know which IsTrue-constraint to use, if they decide to customize the AccountConsentField, e.g. by overriding default Constraints. Even though this situation is unlikely; just imagine a different transformer for a field that is likely changed in terms of constraints. Symfony's built-in Validators would most likely behave unexpectedly.

Research

I've already searched for similar issues and found that especially this question seems to be alike (though only in the beginning). Yet, it did not quite answer my question.

isGranted returns false for logged in user JWT - Symfony API-Platform AWS-EB

$
0
0

I have deployed an API-Platform app using JWT token to ElasticBeanstalk which, as usual, works fine in my local server.

On EB though it is denying access to logged in users despite the correct BearerToken being provided.

This is the error thrown:

{
 "errors": [
    {
        "message": "Access Denied.",
        "extensions": {
            "category": "graphql"
        },
        "locations": [
            {
                "line": 6,
                "column": 9
            }
        ],
        "path": [
            "retrievedQueryUser"
        ]
    }
],
"data": {
    "retrievedQueryUser": null
}
}

The query in question attempts to retrieve user profile info through the below graphql config:

*          "retrievedQuery"={
*              "item_query"=UserProfileResolver::class,
*              "normalization_context"={"groups"={"get-owner"}},
*              "security"="is_granted('IS_AUTHENTICATED_FULLY') and object == user"
*          },

So, it should be a simple matter of checking if the users IS_AUTHENTICATED_FULLY and if it is the user him/herself trying to execute the query.

Far as I could tell, by dump below on /vendor/symfony/security-core/Authorization/AuthorizationChecker.php, it's failing to retrieve a token.

 var_dump($this->tokenStorage->getToken()->getUser()->getUsername());

I did a cursory comparison of phpinfo() between my local installation and the one at AWS-EB and could not find any obvious mismatch.

This is the config for JWT at /config/packages/lexik_jwt_authentication.yaml.

lexik_jwt_authentication:
   secret_key: '%env(resolve:JWT_SECRET_KEY)%'
   public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
   pass_phrase: '%env(JWT_PASSPHRASE)%'
   user_identity_field: email
   token_ttl: 1800

Just to confirm that the users are able to login. It's passing through the isGranted() check that fails.

Any ideas?

EDIT - add `/config/packages/security.yaml

security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
encoders:
    App\Entity\User:
        algorithm: auto
        #algorithm: bcrypt
        #algorithm: argon2i
        cost: 12
providers:
    database:
        entity:
            class: App\Entity\User
            property: email
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    refresh:
        pattern:  ^/api/token/refresh
        stateless: true
        anonymous: true
    api:
        pattern:  ^/api
        stateless: true
        anonymous: true
        json_login:
            check_path:               /api/login_check
            success_handler:          lexik_jwt_authentication.handler.authentication_success
            failure_handler:          lexik_jwt_authentication.handler.authentication_failure
        guard: 
            authenticators: 
                - app.google_login_authenticator
                - App\Security\TokenAuthenticator
            entry_point: App\Security\TokenAuthenticator
        user_checker: App\Security\UserEnabledChecker
     access_control:
    - { path: ^/login,     roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin,     roles: ROLE_SUPERADMIN }
    - { path: ^/api/token/refresh, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api,       roles: IS_AUTHENTICATED_ANONYMOUSLY }
role_hierarchy:
    ROLE_PROVIDER: ROLE_USER
    ROLE_ADMIN: [ROLE_PROVIDER, ROLE_EDITOR]
    ROLE_SUPERADMIN: ROLE_ADMIN

How to count distinct columns query? [closed]

$
0
0

I have to find the total number or records but count is based on distinct of multiple columns.

I have following lines in my query.

$query = $this->createQueryBuilder("j");
$query->select(
                "COUNT(DISTINCT 
                        'j.mark',
                        'j.model'
                    ) as total");

But this is giving me error:

[Syntax Error] line 0, col 76: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got ','

Can anybody please help me solve this issue?

Thank You.

Symfony 4 Route gets mismatched - redirectToRoute leads to the current page

$
0
0

Dear intelligent hive,

I got problems with redirect in symfony 4. Of course I tried to find a similar question, but found no solution.

I just started learning Symfony 4 by working through some tutorials. (AND I LOVE IT!!!)

The program is a really simple blog example on a local apache server (maybe this is important). Means List, Add, Show

So my problem is in the add method. After adding an article (which works fine), I want to use redirectToRout('article_list'). But that doesn't lead me anywhere except on the add-page.

When I debug my routes, I can see the correct routes:

article_list               ANY      ANY      ANY    /article                          
article_delete             DELETE   ANY      ANY    /article/delete/{id}              
article_add                ANY      ANY      ANY    /article/add                      
article_show               ANY      ANY      ANY    /article/{id}

And these routes all work fine, when I type them in manually.

The add-function is also pretty simple:

/**
     * @Route(
     * "/article/add", 
     * name="article_add",
     * )
     */
    public function add(Request $request)
    {
        $article = new Article();
        $form = $this->createFormBuilder($article)
            [...]
        ->getForm();

        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()){
            $article = $form->getData();

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($article);

            $entityManager->flush();

            $this->redirectToRoute('article_list');
        }


        return $this->render('article/new.html.twig', array(
            'form' => $form->createView()
        ));
    }

As well as the list-function

/**
     * @Route(
     * "/article", 
     * name="article_list",
     * )
     */
    public function index()
    {
        $articles = $this->getDoctrine()->getRepository(Article::class)->findAll();
        return $this->render('article/list.html.twig', [
            'articles' => $articles,
        ]);
    }

As you can see, the name in the annotations is correct.

When I change the redirectToRoute-Method to

redirectToRoute("/article");

I get the error "Unable to generate a URL for the named route "/article" as such route does not exist. In the log, I see Matched route "article_add" So the route "/article" was matched to the route "article_add". Thats not, what I would expect....

So I kind of have the feeling, that something on the add-page is ignoring my routes.

Does anybody have any idea, what simple problem I'm not able to see?

Thanks! I would really like to understand, whats going wrong here...

Virtual hosts configuration with Symfony 4

$
0
0

I have a problem with my virtual host on WAMP server. I tested projected that I worked on before, and they all work.

When I hit my defined localhost name of the project

127.0.0.1 project.local

defined in my hosts file, it returns

This page isn’t working

It's my first Symfony 4 project and I think my virtual hosts configuration may not be right.

This is my project skeleton:

iproject-skeleton-image

And my virtual host config:

<VirtualHost *:80>
     ServerName project.local
     DocumentRoot "${INSTALL_DIR}/www/project/public"
     SetEnv APPLICATION_ENV "development"<Directory "${INSTALL_DIR}/www/project/public/">
           AllowOverride All
           Order Allow,Deny
           Allow from All
           <IfModule mod_rewrite.c>
             Options -MultiViews +FollowSymlinks
               RewriteEngine On
               RewriteCond %{REQUEST_FILENAME} !-f
               RewriteRule ^(.*)$ index.php [QSA,L]
           </IfModule>
       </Directory>
     </VirtualHost>
Viewing all 3917 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>