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

Symfony update 4.3 to 4.4 The content-type is not supported

$
0
0

I have updated Symfony project (api platform) from 4.3 to 4.4, but now I receive this error in some POST/PUT requests:

Status Code: 415 Unsupported Media Type

The content-type “application/json” is not supported. Supported MIME types are “”.

Trace where broke:

../vendor/api-platform/core/src/EventListener/DeserializeListener.php

with the command:

php bin/console debug:config api_platform

api_platform:
    path_segment_name_generator: api_platform.path_segment_name_generator.dash
    enable_fos_user: true
    eager_loading:
        force_eager: false
        enabled: true
        fetch_partial: false
        max_joins: 30
    http_cache:
        max_age: 0
        shared_max_age: 3600
        vary:
            - Content-Type
            - Authorization
            - Origin
        public: true
        etag: true
        invalidation:
            enabled: false
            varnish_urls: {  }
            request_options: {  }
    oauth:
        enabled: true
        flow: password
        tokenUrl: /api/login
        clientId: ''
        clientSecret: ''
        type: oauth2
        authorizationUrl: /oauth/v2/auth
        scopes: {  }
    mapping:
        paths:
            - /var/www/x/config/packages/apiplatform/user.yml
            - /var/www/x/config/packages/apiplatform/business.yml
            - /var/www/x/config/packages/apiplatform/service.yml
            - /var/www/x/config/packages/apiplatform/customers.yml
            - /var/www/x/config/packages/apiplatform/worker.yml
            - /var/www/x/src/Entity
    title: ''
    description: ''
    version: 0.0.0
    show_webby: true
    default_operation_path_resolver: api_platform.operation_path_resolver.unders                                                  core
    name_converter: null
    allow_plain_identifiers: false
    validator:
        serialize_payload_fields: {  }
    enable_nelmio_api_doc: false
    enable_swagger: true
    enable_swagger_ui: true
    enable_re_doc: true
    enable_entrypoint: true
    enable_docs: true
    enable_profiler: true
    collection:
        exists_parameter_name: exists
        order: ASC
        order_parameter_name: order
        pagination:
            enabled: true
            partial: false
            client_enabled: false
            client_items_per_page: false
            client_partial: false
            items_per_page: 30
            maximum_items_per_page: null
            page_parameter_name: page
            enabled_parameter_name: pagination
            items_per_page_parameter_name: itemsPerPage
            partial_parameter_name: partial
    resource_class_directories: {  }
    doctrine:
        enabled: true
    doctrine_mongodb_odm:
        enabled: false
    graphql:
        enabled: false
        default_ide: graphiql
        graphiql:
            enabled: false
        graphql_playground:
            enabled: false
        nesting_separator: _
        collection:
            pagination:
                enabled: true
    swagger:
        versions:
            - 2
            - 3
        api_keys: {  }
    mercure:
        enabled: false
        hub_url: null
    messenger:
        enabled: false
    elasticsearch:
        enabled: false
        hosts: {  }
        mapping: {  }
    exception_to_status:
        Symfony\Component\Serializer\Exception\ExceptionInterface: 400
        ApiPlatform\Core\Exception\InvalidArgumentException: 400
        ApiPlatform\Core\Exception\FilterValidationException: 400
        Doctrine\ORM\OptimisticLockException: 409
    formats:
        jsonld:
            mime_types:
                - application/ld+json
        json:
            mime_types:
                - application/json
        html:
            mime_types:
                - text/html
    patch_formats: {  }
    error_formats:
        jsonproblem:
            mime_types:
                - application/problem+json
        jsonld:
            mime_types:
                - application/ld+json

Doctrine Add column onSchemaCreateTable Event

$
0
0

I have some ManyToMany table relations. I'd like those to have a "created_at" field set when INSERT INTO.

Following Symfony and Doctrine Documentation, i tired this :

app/config/services_dev.yaml

[...]
    App\Event\Listener\ManyToManyListener:
        tags:
            - { name: doctrine.event_listener, event: onSchemaCreateTable }

app/src/Event/Listener/ManyToManyListener.php


[.....]

class ManyToManyListener implements EventSubscriber
{
    public function getSubscribedEvents()
    {
        return ['onSchemaCreateTable'];
    }

    public function onSchemaCreateTable(SchemaCreateTableEventArgs  $event)
    {
        $columns = $event->getTable()->getColumns();

        if (count($columns) <= 2 && !array_key_exists("created_at", $columns)) {
            $tableName = $event->getTable()->getName();
            $sql = "ALTER TABLE $tableName ADD COLUMN created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP;";
            $event->addSql($sql);
              //dump($sql);
        }
    }
}

I can dump my SQL code inside, it works.

I also tried this code (inside the if statement)

$event->getTable()->addColumn(
                "created_at",
                "datetime",
                ["default" => "CURRENT_TIMESTAMP"]
            );

This never execute the SQL statement. For example, while php bin/console doctrine:schema:update --dump-sql, I can't see my query.

Symfony 4 console: Environment variable not found in prod env

$
0
0

Every time I run bin/console cache:clear --env=prod got an error Environment variable not found: "LOCALE" or any other variable. If a run it on the dev environment I wont see any error.

I can always run LOCALE=es_CO ./bin/console cache:clear --env=prod but I'll get an error for the next variable.

symfony/dotenv version is v4.3.2

It seems to be working when making requests via web server.

Not sure what else should be done.

symfony 4 build API GraphQL : overblog/GraphQLBundle vs ApiPlatform

$
0
0

I wish to set up a GraphQL API on a symfony 4 application, according to you between its two two solutions (overblog/GraphQLBundle vs ApiPlatform) which should I choose to build my API and why do you think?

Thanks

Symfony Functional Test on a controller with LoginFormAuthenticator

$
0
0

I have a Symfony4 app that is basically done and now am writing some tests for it. I'm trying to see if I can get a success http 200 from this controller route using this command vendor/bin/phpunit --debug tests/SampleTest.php

The page is protected by the default login form auth that symfony uses (debug below)


    /**
     * @IsGranted("ROLE_BRAND")
     * @Route("/user/dashboard", methods={"GET"}, name="user_index", condition="context.getHost() in ['mysite.test', 'www.mysite.test']")
     *
     */
    public function dashboard(Request $request ): Response {
             ...clipped....
    }

[2020-03-04 18:48:09] request.INFO: Matched route "user_index". {"route":"user_index","route_parameters":{"_route":"user_index","_controller":"App\\Controller\\Backend\\DashboardController::dashboard"},"request_uri":"https://mysite.test/user/dashboard","method":"GET"} []
[2020-03-04 18:48:10] security.DEBUG: Read existing security token from the session. {"key":"_security_main","token_class":"Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken"} []
[2020-03-04 18:48:10] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":1} []
[2020-03-04 18:48:10] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"main","authenticator":"App\\Security\\LoginFormAuthenticator"} []
[2020-03-04 18:48:10] security.DEBUG: Guard authenticator does not support the request. {"firewall_key":"main","authenticator":"App\\Security\\LoginFormAuthenticator"} []
[2020-03-04 18:48:10] security.DEBUG: Access denied, the user is neither anonymous, nor remember-me. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException(code: 403): Access Denied. at C:\\xampp\\htdocs\\mysite\\vendor\\symfony\\security-http\\Firewall\\AccessListener.php:99)"} []
[2020-03-04 18:48:10] request.ERROR: Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: "Access Denied." at C:\xampp\htdocs\mysite\vendor\symfony\security-http\Firewall\ExceptionListener.php line 137 {"exception":"[object] (Symfony\\Component\\HttpKernel\\Exception\\AccessDeniedHttpException(code: 0): Access Denied. at C:\\xampp\\htdocs\\mysite\\vendor\\symfony\\security-http\\Firewall\\ExceptionListener.php:137, Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException(code: 403): Access Denied. at C:\\xampp\\htdocs\\mysite\\vendor\\symfony\\security-http\\Firewall\\AccessListener.php:99)"} []

This is the test code from https://symfony.com/doc/4.4/testing/http_authentication.html


namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class SampleTest extends WebTestCase {
    private $client = null;

    public function setUp(): void {
        $this->client = static::createClient();
    }

    public function testSecuredHello() {
        $this->logIn();
        $crawler = $this->client->request('GET', 'https://mysite.test/user/dashboard');
        $this->assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
    }

    private function logIn() {
        $session = self::$container->get('session');

        $firewallName = 'main';
        // if you don't define multiple connected firewalls, the context defaults to the firewall name
        // See https://symfony.com/doc/current/reference/configuration/security.html#firewall-context
        $firewallContext = 'main';

        // you may need to use a different token class depending on your application.
        // for example, when using Guard authentication you must instantiate PostAuthenticationGuardToken
        $token = new UsernamePasswordToken('user@good.com', null, $firewallName, ['ROLE_ADMIN', 'ROLE_BRAND']);
        $session->set('_security_' . $firewallContext, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);
    }
}


bin/console debug:config security

Current configuration for extension with alias "security"
=========================================================

security:
    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email
                manager_name: null
    encoders:
        App\Entity\User:
            algorithm: auto
            migrate_from: {  }
            hash_algorithm: sha512
            key_length: 40
            ignore_case: false
            encode_as_base64: true
            iterations: 5000
            cost: null
            memory_cost: null
            time_cost: null
            threads: null
    role_hierarchy:
        ROLE_ADMIN:
            - ROLE_ALLOWED_TO_SWITCH
            - ROLE_BRAND
            - ROLE_ADVOCATES_VISIBLE
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
            methods: {  }
            user_checker: security.user_checker
            stateless: false
            logout_on_user_change: true
        main:
            anonymous:
                lazy: false
                secret: null
            switch_user:
                parameter: _switch_to_brand_login
                role: ROLE_ALLOWED_TO_SWITCH
                stateless: false
            guard:
                authenticators:
                    - App\Security\LoginFormAuthenticator
                entry_point: null
            logout:
                path: app_logout
                csrf_parameter: _csrf_token
                csrf_token_id: logout
                target: /
                invalidate_session: true
                delete_cookies: {  }
                handlers: {  }
            remember_me:
                remember_me_parameter: _remember_me
                secret: '%env(APP_SECRET)%'
                lifetime: 604800
                path: /
                user_providers: {  }
                catch_exceptions: true
                name: REMEMBERME
                domain: null
                secure: null
                httponly: true
                samesite: lax
                always_remember_me: false
            methods: {  }
            security: true
            user_checker: security.user_checker
            stateless: false
            logout_on_user_change: true
    access_control:
        -
            path: ^/user/account
            roles:
                - IS_AUTHENTICATED_FULLY
            requires_channel: null
            host: null
            port: null
            ips: {  }
            methods: {  }
            allow_if: null
        -
            path: ^/user
            roles:
                - ROLE_USER
            requires_channel: null
            host: null
            port: null
            ips: {  }
            methods: {  }
            allow_if: null
        -
            path: ^/admin
            roles:
                - ROLE_ADMIN
            requires_channel: null
            host: null
            port: null
            ips: {  }
            methods: {  }
            allow_if: null
    access_decision_manager:
        strategy: affirmative
        allow_if_all_abstain: false
        allow_if_equal_granted_denied: true
    access_denied_url: null
    session_fixation_strategy: migrate
    hide_user_not_found: true
    always_authenticate_before_granting: false
    erase_credentials: true

Using a PostAuthenticationGuardToken didn't work either. I'm all out of ideas

Symfony 4 - route : "The requested URL was not found on this server"

$
0
0

this is my first post so i'll try to be understandable.

I am starting with symfony, and there is a problem i can't resolve alone.

This is my controller, and I am working with WAMP. When my Url is "mysite.local", it work normally, and it show me what it should (thanks to the home() function). But when my Url is "mysite.local/hello", i have the following error.

Not Found

The requested URL was not found on this server.

Apache/2.4.41 (Win64) PHP/7.4.0 Server at mysite.local Port 80

I guess this is normal as i didn't created any file named "hello", but it's working in the formation i am following.

Could you help me please ? Thank you

<?php


namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class HomeController extends AbstractController
{
/**
 * @Route("/hello", name="hello")
 */

public function hello()
{
    return new Response("Bonjour ...");
}
/**
 *@Route("/", name="homepage");
 */

public function home(){
    $prenoms = ["Lior" => 17 , "Joseph" => 12, "Anne" => 55];
    return $this->render("home.html.twig",
        [
            'title' => "Bonjour a tous :)",
            'age' => "31 ",
            'tableau' => $prenoms,
        ]); 
}

}

?>

Doctrine fails with column can't be null error; Can't see how the value _can_ be null

$
0
0

I have a Symfony 4 application that uses Doctrine for all database access. The table in question has a number of columns that are defined with "NOT NULL".

All of the getter methods in the entity class are written such that they return an empty string if the current value is null

public function getApartment(): string
{
  return $this->apartment ?? '';
}

It is my understanding that Doctrine calls the entity's getter methods to retrieve the current values when persisting the object into the database.

I don't see how getters written like the one above can possibly result in null values, yet this error occasionally happens. Note that it doesn't happen all the time, only sometimes and I haven't spotted any sort of pattern yet.

In addition to the getters, several of the entity's field definitions are tagged with @Assert\NotBlank annotations so the Form component shouldn't return true from the isValid() method.

Here is a (slightly edited) example error from var/log/prod.log:

[2020-03-02 22:23:22] request.CRITICAL: Uncaught PHP Exception 
  Doctrine\DBAL\Exception\NotNullConstraintViolationException: 
  "An exception occurred while executing 
    'INSERT INTO FreeClassQueries 
    (apartment, city, comment, dateCreated, email, migrated, name, phone, state, street, zip, spamInfo) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' 
    with params [null, null, null, "2020-03-02 22:23:20", null, null, null, null, null, null, null, null]:  
  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'apartment' cannot be null" 
    at /var/www/prod/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php line 103 
    {"exception":"[object] (Doctrine\\DBAL\\Exception\\NotNullConstraintViolationException(code: 0): 
    An exception occurred while executing 
      'INSERT INTO FreeClassQueries 
      (apartment, city, comment, dateCreated, email, migrated, name, phone, state, street, zip, spamInfo) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' 
      with params [null, null, null, \"2020-03-02 22:23:20\", null, null, null, null, null, null, null, null]:
  SQLSTATE[23000]: Integrity constraint violation: 1048 
  Column 'apartment' cannot be null 
    at /var/www/prod/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:103, 
  Doctrine\\DBAL\\Driver\\PDOException(code: 23000): SQLSTATE[23000]: 
    Integrity constraint violation: 1048 Column 'apartment' cannot be null 
    at /var/www/prod/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:123, 
  PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1048
    Column 'apartment' cannot be null at /var/www/prod/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:121)"} []

As you can see, the only value that is not null is dateCreated. it is set via a method that is tagged with an @ORM\PrePersist annotation.

The action method only attempts to persist the object if the form has been submitted and is valid, meaning that all fields tagged with @Verify\NotBlank can not be blank.

$form->handleRequest( $request );
if( $form->isSubmitted() && $form->isValid())
{
  $em = $this->getEntityManager();
  $repository = $em->getRepository( FreeClassQuery::class );
  $em->persist( $classQuery );
  $em->flush();
  ...
}

FOS Rest bundle - Not able to use customized error controller

$
0
0

I have a project with Symfony 4.4 and FosRestBundle. I'm trying to customize the exception handling by changing the json output. In this particular case I have a controller that receives a query string language param and it validates it's correct (en_GB, it_IT, etc...). So when I pass an incorrect language code I want it to be handled by my own controller. The exception is thrown but is catched by it never goes to my custom controller, seems like its directly Symfony who does the output. My fos_rest.yaml:

fos_rest:
  param_fetcher_listener: force
  exception:
    enabled: true
    exception_controller: 'AppBundle\Action\ExceptionAction'

My action controller:

    /**
     * @Route(
     *     "/api/v1/categories/{id}",
     *     name="get_category",
     *     methods={"GET"},
     *     requirements={"id"="\d+"}
     * )
     *
     * @QueryParam(
     *     name="language",
     *     requirements=@Assert\LanguageCode,
     *     strict=false,
     *     description="Language code in ISO format, i.e. fr_FR"
     * )
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function __invoke(Request $request): JsonResponse
    {
        /**
     * @Route(
     *     "/api/v1/categories/{id}",
     *     name="get_category",
     *     methods={"GET"},
     *     requirements={"id"="\d+"}
     * )
     *
     * @QueryParam(
     *     name="language",
     *     requirements=@Assert\LanguageCode,
     *     strict=false,
     *     description="Language code in ISO format, i.e. fr_FR"
     * )
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function __invoke(Request $request): JsonResponse
    {

One thing that bothers me is I can write whatever I want in the exception_controller configuration option (like non-existent-controller) and the code doesn't fail witch makes me think that something is not plugged correctly. Any ideas why this is not working? Thanks a lot!


Notice: A non well formed numeric value encountered on authentication Symfony 4 [closed]

$
0
0

Hello devs when I try to connect with my login form ( when I submit the form ) it doesn't work and gives me the following error:

Notice: A non well formed numeric value encountered

so thank you in advance for your answers

so I use the symfony 4 security component for authentication.

Here's the code:

Controller:

<?php

namespace App\Controller ;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\User ;

//Class pour authentification
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils ;


class SecurityController extends AbstractController
{

  /**
  * @Route("/login" , name="login")
  */
  public function login(AuthenticationUtils $authentication)
  {
    $error = $authentication -> getLastAuthenticationError();

    $lastUsername = $authentication -> getLastUsername();

    return $this -> render('Authentification/login.html.twig' ,[

      'error'  => $error,
      'last_username' => $lastUsername,
      ]) ;

  }

}

Security.yaml :

security:
    encoders:
        App\Entity\User:
          algorithm: bcrypt
          cost :  14



    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: lazy

            form_login:

                remember_me: false

                check_path: /login


            logout :

                path: /logout

                target: /


            # activate different ways to authenticate
            # https://symfony.com/doc/current/security.html#firewalls-authentication

            # https://symfony.com/doc/current/security/impersonating_user.html
            # switch_user: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:

        - { path: ^/admin, roles: ROLE_ADMIN } 

and the login page :

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


{% block title %}Se Connecter{% endblock %}

{% block body %}
<div class="container">

  <br><br>

  <h3>Page de Connection de l'application CUMA le PROGRES</h3>

  <br><br>



  <p class="btn float-right color-br" onclick="window.history.back();">Retour</p>

  <br><br>

  {% if error %}

  <div class="alert alert-danger">

    {% if error %}

    {{ error.messageKey | trans(error.messagedata ,  'security') }}

    {% endif %}



  </div>

  {% endif %}

  <form  action="{{  path('login')}}" method="post">

    <div class="form-group">

      <label for="username">Nom d'utilisateur</label>

      <input type="text" id="username" name="_username" class="form-control" placeholder="Vôtre nom d'utilisateur est du style:    Prénom.Nom" value="{{ last_username }}">


    </div>

      <br>

      <div class="form-group">


          <label for="password">Mot de passe</label>

          <input type="password" id="password" name="_password" class="form-control" placeholder="Vôtre mot de passe ..... ( en cas d'oublie aller voir Fabien ABISUR )">


      </div>

      <br><br>

      <button type="submit" class="btn color-br">Se Connecter</button>

    </form>



</div>


{% endblock %}

thank you in advance for your help (^_^)

How to properly use '%' for escaping YAML configuration in Symfony?

$
0
0

When it comes to creating bundles, it's often necessary to support some configuration for the developers who'll use the bundle.

In this case, I need the configuration's value to support %someText%, without Symfony trying to resolve this value as parameter.

Example: Incorrect Configuration

my_bundle_name:
    my_configuration: '%someText%'

So, I figured, I'll have to escape the % (so it looks like %%) to make things work - resulting in the value %%someText%%.

If some parameter value includes the % character, you need to escape it by adding another % so Symfony doesn't consider it a reference to a parameter name [...]

Example: No Error, but Unexpected Result

my_bundle_name:
    my_configuration: '%%someText%%'

While this solves the You have requested a non-existent parameter[...] error, the actual value is now %%someText%%. I expected Symfony to return the unsecaped value instead, i.e., %someText%.

Sure I could str_replace('%%', '%', '%%someText%%'), but this feels hack-ish.

How would I change the value to actually get %someText% instead?

Here's where the configuration is loaded:

// Namespace and use statements omitted for brevity
class MyBundleNameExtension extends ConfigurableExtension
{
    /**
     * @inheritDoc
     */
    protected function loadInternal(array $mergedConfig, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('config.yml');

        p_r($mergedConfig["my_configuration"]); // Prints %%someText%%
    }
}

I've verified that using both ' and " yields the same result.

Ckeditor - using twig code within FOSCKEditor wysiwyg

$
0
0

I wanted to know if it was possible to put twig code in ckeditor and that it interprets correctly the code in order to generate the HTML code.

I've already seen some configurations (using "protectedSource") that allow to put twig code within ckeditor but when I do that, the twig code is still interpreted as a string.

My goal here is to create some twig functions that I could use inside CKEditor.

Example :

Let's say that the "my_complex_table_function" function return a complex table, i would like to be able to put

 {{ my_complex_table_function }}

in CKEditor and that it returns the table in the front page.

Is that possible ?

Thanks guys

Functional Testing Events and Subscribers in Symfony 4

$
0
0

I need to functionally test the a subscriber in Symfony 4 and I'm having problems finding how. The Subscriber has the following structure

/**
* Class ItemSubscriber
*/
class ItemSubscriber implements EventSubscriberInterface
{
    /**
     * @var CommandBus
     */
    protected $commandBus;

    /**
     * Subscriber constructor.
     *
     * @param CommandBus $commandBus
     */
    public function __construct(CommandBus $commandBus)
    {
        $this->commandBus = $commandBus;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            CommandFailedEvent::NAME => 'onCommandFailedEvent',
        ];
    }

    /**
     * @param CommandFailedEvent $event
     *
     * @throws Exception
     */
    public function onCommandFailedEvent(CommandFailedEvent $event)
    {
        $item = $event->getItem();
        $this->processFailed($item);
    }

    /**
     * Sends message 
     *
     * @param array $item
     *
     * @throws Exception
     */
    private function processFailed(array $item)
    {
        $this->commandBus->handle(new UpdateCommand($item));
    }
}

The flow of the subscriber is receiving an internal event and send a message by rabbit through the command bus to another project.

How can I test that dispatching the event CommandFailedEvent the line in processFailed(array $item) is executed?

Does anyone has documentation on best practices to test Events and Subscribers in Symfony 4?

Authentification probleme Symfony 4 (Security component )

$
0
0

I have a little problem with my Symfony 4 login page. When users submits the form, the following error appears:

Notice: A non well formed numeric value encountered

and yet when I go to the data base the login is there, the password is there too (hash it out of course) and despite this it doesn't work.

and sometimes it starts working but only when env=dev but when env=prod there is an error 500

this is the controller

<?php

namespace App\Controller ;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\User ;

//Class pour authentification
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils ;


class SecurityController extends AbstractController
{

  /**
  * @Route("/login" , name="login")
  */
  public function login(AuthenticationUtils $authentication)
  {
    $error = $authentication->getLastAuthenticationError();

    $lastUsername = $authentication->getLastUsername();

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

security.yaml file:

security:
    providers:
        from_database:
            entity:
                class: App\Entity\User
                property: username

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: lazy
            form_login:
                remember_me: true
                check_path: /login

            logout :
                path: /logout
                target: /

    access_control: 
        - { path: ^/admin, roles: ROLE_ADMIN }

    encoders:
        App\Entity\User:
          algorithm: bcrypt
          cost :  14

form login :

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

{% block title %}Se Connecter{% endblock %}

{% block body %}
<div class="container">

  <h3>Page de Connection de l'application CUMA le PROGRES</h3>

  <p class="btn float-right color-br" onclick="window.history.back();">Retour</p>

  {% if error %}

  <div class="alert alert-danger">

    {% if error %}

    {{ error.messageKey | trans(error.messagedata ,  'security') }}

    {% endif %}

  </div>

  {% endif %}

  <form  action="{{  path('login')}}" method="post">
    <div class="form-group">
      <label for="username">Nom d'utilisateur</label>
      <input type="text" id="username" name="_username" class="form-control" placeholder="Vôtre nom d'utilisateur est du style:    Prénom.Nom" value="{{ last_username }}">
    </div>
      <div class="form-group">

          <label for="password">Mot de passe</label>

          <input type="password" id="password" name="_password" class="form-control" placeholder="Vôtre mot de passe ..... ( en cas d'oublie aller voir Fabien ABISUR )">
      </div>
      <button type="submit" class="btn color-br">Se Connecter</button>
    </form>
</div>
{% endblock %}

Call to a member function guessExtension() on string with relation one to many

$
0
0

I'm trying to upload several pictures in Symfony 4.4 but I got this error:

Call to a member function guessExtension() on string

I have ManyToOne relation between Event and Picture. Each Event can be associated with many Pictures but, each picture can be associated with only one Event.

My entity Event :

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

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Picture", mappedBy="event")
     */
    private $pictures;

    /**
     * getter and setter for $this->title
     */

    public function __construct()
    {
        $this->pictures = new ArrayCollection();
    }

    /**
     * @return Collection|Picture[]
     */
    public function getPictures()
    {
        return $this->pictures;
    }

    public function addPicture(Picture $picture)
    {
        if (!$this->pictures->contains($picture)) {
            $this->pictures[] = $picture;
            $picture->setEvent($this);
        }

        return $this;
    }

    public function removePicture(Picture $picture)
    {
        if ($this->pictures->contains($picture)) {
            $this->pictures->removeElement($picture);
            // set the owning side to null (unless already changed)
            if ($picture->getEvent() === $this) {
                $picture->setEvent(null);
            }
        }

        return $this;
    }
}

My entity Picture :

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

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

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Event", inversedBy="pictures")
     * @ORM\JoinColumn(nullable=false)
     */
    private $event;

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

    /**
     * getter and setter for $this->name
     */

    public function getEvent()
    {
        return $this->event;
    }

    public function setEvent(?Event $event)
    {
        $this->event = $event;

        return $this;
    }
}

EventType Form :

    $builder
        ->add('title', TextType::class)
        ->add('pictures', CollectionType::class, [
            'entry_type' => PictureType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
            'by_reference' => false,
            'label' => false
        ])
    ;

PictureType Form

    $builder
        ->add('name', FileType::class, [
            'data_class' => null,
            'label' => ''
        ])
    ;

My controller

/**
 * @Route("/new", name="admin-spectacle-new")
 */
public function new(Request $request)
{
    $event = new Event();
    $form = $this->createForm(EventType::class, $event);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $images = $form->get('pictures')->getData();
        foreach ($images as $image) {
                $fileName = md5(uniqid()).'.'.$image->getName()->guessExtension();
                $image->move($this->getParameter('image_spectacle'), $fileName);
                $image->setName($fileName);
        }
        //...
    }
    return $this->render(...);
}

Any ideas why I am getting this error?

Error multiple insert Symfony5 with JSON field

$
0
0

I have a problem with EntityType Multiple a register in database a result is : [{}, {}] because type is json but this json is empty... I don't fond a solve, can you help me ?

Controller:

public function gestion_group(Request $request, EntityManagerInterface $manager)
    {
        $groups = new GroupsManager();
        $form = $this->createForm(AdminGroupType::class , $groups);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $groups->getU();
            $manager->persist($groups);
            $manager->flush();
            $this->addFlash(
                'success',
                "La personne à bien été ajouter au groupe !"
            );

            return $this->redirectToRoute('admin');
        }
        return $this->render('admin/groups/index.html.twig', [
            'form' => $form->createView()
        ]);
    }

entity :

class GroupsManager
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="groupsManagers")
     */
    private $manager;

    /**
     * @ORM\Column(type="json")
     */
    private $u = [];

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

    public function getManager(): ?User
    {
        return $this->manager;
    }

    public function setManager(?User $manager): self
    {
        $this->manager = $manager;

        return $this;
    }

    public function getU(): ?array
    {
        return $this->u;
    }

    public function setU(array $u): self
    {
        $this->u = $u;

        return $this;
    }
}

And form :

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('manager', EntityType::class, array(
                'label' => 'Choisir le manager',
                'class' => User::class,
                'choice_label' => function ($user) {
                    return $user->getLastname() . '' . $user->getFirstname();
                }
            ))
            ->add('u', EntityType::class, array(
                'label' => 'Choisir un utilisateur',
                'class' => User::class,
                'choice_label' => function ($user) {
                    return $user->getLastname() . '' . $user->getFirstname();
                },
                'multiple' => true
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => GroupsManager::class,
        ]);
    }

I would like add user with multiple choice for 1 manager to manage group of user i choice json type for it but is empty, can you help ?


Symfony 4 TypeForm submit dont update db with select id

$
0
0

Here I meet a small problem with my code.

What I do

In my application I have normal users and technicians users. A user must have a technician. When creating a new user: In my form type 'UserType.php' I get all Technicians Users from db to display in a select.

<?php

namespace App\Form;

use App\Entity\Users;
use App\Repository\UsersRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname')
            ->add('lastname')
            ->add('email')
            ->add('phone')
            ->add('city')
            ->add('status', ChoiceType::class, [
                'choices' => $this->getChoices()
            ])
            ->add('certification_phyto')
            ->add('technician', EntityType::class, array(
                'class' => Users::class,
                'query_builder' => function(UsersRepository $user) {
                    return $user->createQueryBuilder('u')
                        ->orderBy('u.firstname', 'ASC')
                        ->andWhere('u.status = :status')
                        ->setParameter('status', 'ROLE_TECHNICIAN');
                },
                'choice_label' => function(Users $user) {
                    return $user->getFirstname() . '' . $user->getLastname(); },
                'choice_value' => 'id'
            ))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Users::class,
            'translation_domain' => 'forms'
        ]);
    }

    private function getUsers(UsersRepository $user) {
        return $user->createQueryBuilder('u')
            ->orderBy('u.firstname', 'ASC')
            ->andWhere('u.status = :status')
            ->setParameter('status', 'ROLE_TECHNICIAN');
    }

    private function getChoices()
    {
        $choices = Users::STATUS;
        $output = [];
        foreach ($choices as $k => $v) {
            $output[$v] = $k;
        }
        return $output;
    }

}
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UsersRepository")
 * @UniqueEntity("email")
 */
class Users implements UserInterface, \Serializable
{
    const STATUS = [
        'ROLE_USER' => 'Client',
        'ROLE_TECHNICIAN' => 'Technicien',
        'ROLE_ADMIN' => 'Administrateur'
    ];

    const ISACTIVE = [
        1 => 'Activé',
        2 => 'En attente'
    ];

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

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

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

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

    /**
     * @ORM\Column(type="string", length=30, nullable=true)
     */
    private $city;

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

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

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $last_activity;

    /**
     * @ORM\Column(type="string", length=20, nullable=true)
     */
    private $technician;

    /**
     * @ORM\Column(type="boolean", nullable=true, options={"default": false})
     */
    private $isActive;

    /**
     * @ORM\Column(type="string", length=30, nullable=true)
     */
    private $certification_phyto;

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

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

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getFirstname(): ?string
    {
        return $this->firstname;
    }

    public function setFirstname(string $firstname): self
    {
        $this->firstname = $firstname;

        return $this;
    }

    public function getLastname(): ?string
    {
        return $this->lastname;
    }

    public function setLastname(string $lastname): self
    {
        $this->lastname = $lastname;

        return $this;
    }

    public function getPhone(): ?string
    {
        return $this->phone;
    }

    public function setPhone(string $phone): self
    {
        $this->phone = $phone;

        return $this;
    }

    public function getCity(): ?string
    {
        return $this->city;
    }

    public function setCity(?string $city): self
    {
        $this->city = $city;

        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    public function getStatus(): ?string
    {
        return $this->status;
    }

    public function setStatus(string $status): self
    {
        $this->status = $status;

        return $this;
    }

    public function getTechnician(): ?string
    {
        return $this->technician;
    }

    public function setTechnician(string $technician): self
    {
        $this->technician = $technician;

        return $this;
    }

    public function getLastActivity(): ?\DateTimeInterface
    {
        return $this->last_activity;
    }

    public function setLastActivity(?\DateTimeInterface $last_activity): self
    {
        $this->last_activity = $last_activity;

        return $this;
    }

    public function getCertificationPhyto(): ?string
{
    return $this->certification_phyto;
}

    public function setCertificationPhyto(?string $certification_phyto): self
    {
        $this->certification_phyto = $certification_phyto;

        return $this;
    }

    public function getIsActive(): ?bool
    {
        return $this->isActive;
    }

    public function setIsActive(?bool $isActive): self
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * @inheritDoc
     */
    public function getRoles()
    {
        return array($this->getStatus());
    }

    /**
     * @inheritDoc
     */
    public function getSalt()
    {
        return null;
    }

    /**
     * @inheritDoc
     */
    public function getUsername()
    {
        return $this->getEmail();
    }

    /**
     * @inheritDoc
     */
    public function eraseCredentials()
    {
    }

    /**
     * @inheritDoc
     */
    public function serialize()
    {
        return serialize([
            $this->id,
            $this->email,
            $this->password
        ]);
    }

    /**
     * @inheritDoc
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->email,
            $this->password
            ) = unserialize($serialized, ['allowed_classes' => false]);
    }
}

What I want

When I submit my form, my DB technician column should take the ID of the technician chosen.

What i get

But I come to this error: Expected argument of type "string", "App \ Entity \ Users" given. My column is declared in string and I send an id or 2 digits so I don't understand.

Thank you very much for your answers or help

Symfony 4.4 before create /{slug} check existing routes

$
0
0

I have the entity Page identified by slug. Also I have the action to view a page in the Page controler :

class PageController extends AbstractController
{
   /**
    * @Route("/{slug}", name="fronend_page")
    */
   public function show(Page $page)
   {
       return $this->render("font_end/page/show.html.twig", [
           "page" => $page,
       ]);
   }
}

I am looking for good practice to validate the slug ( check if exist in routes) before save it in the database without use prefixes Example :

route exist : @route ("/blog")

check if blog exist before create slug : /{slug} = /blog

I have created a solution but I am not sure it is the best solution: I Create a custom Validation Constraint

class ContainsCheckSlugValidator extends ConstraintValidator
{

   private $router;

   public function __construct(UrlGeneratorInterface $router)
   {
       $this->router = $router;
   }

   public function validate($value, Constraint $constraint)
   {
       if (!$constraint instanceof ContainsCheckSlug) {
           throw new UnexpectedTypeException($constraint, ContainsCheckSlug::class);
       }

       // custom constraints should ignore null and empty values to allow
       // other constraints (NotBlank, NotNull, etc.) take care of that
       if (null === $value || '' === $value) {
           return;
       }
       $drp = true;
       try {
           $url = $this->router->generate('fronend_page', [
               'slug' => $value,
           ]);
       } catch (RouteNotFoundException $e) {
           $drp = false;
       }
       if ($drp) {
           $this->context->buildViolation($constraint->message)
               ->setParameter('{{ string }}', $value)
               ->addViolation();
       }


   }
}

thanks

Authentification probleme Symfony 4

$
0
0

I have a little problem with my Symfony 4 login page. When users submits the form, the following error appears:

Notice: A non well formed numeric value encountered

and yet when I go to the data base the login is there, the password is there too (hash it out of course) and despite this it doesn't work.

this is the controller

<?php

namespace App\Controller ;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\User ;

//Class pour authentification
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils ;


class SecurityController extends AbstractController
{

  /**
  * @Route("/login" , name="login")
  */
  public function login(AuthenticationUtils $authentication)
  {
    $error = $authentication->getLastAuthenticationError();

    $lastUsername = $authentication->getLastUsername();

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

security.yaml file:

security:
    providers:
        from_database:
            entity:
                class: App\Entity\User
                property: username

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: lazy
            form_login:
                remember_me: true
                check_path: /login

            logout :
                path: /logout
                target: /

    access_control: 
        - { path: ^/admin, roles: ROLE_ADMIN } #cane_loader

    encoders:
        App\Entity\User:
          algorithm: bcrypt
          cost :  14

form login :

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

{% block title %}Se Connecter{% endblock %}

{% block body %}
<div class="container">

  <h3>Page de Connection de l'application CUMA le PROGRES</h3>

  <p class="btn float-right color-br" onclick="window.history.back();">Retour</p>

  {% if error %}

  <div class="alert alert-danger">

    {% if error %}

    {{ error.messageKey | trans(error.messagedata ,  'security') }}

    {% endif %}

  </div>

  {% endif %}

  <form  action="{{  path('login')}}" method="post">
    <div class="form-group">
      <label for="username">Nom d'utilisateur</label>
      <input type="text" id="username" name="_username" class="form-control" placeholder="Vôtre nom d'utilisateur est du style:    Prénom.Nom" value="{{ last_username }}">
    </div>
      <div class="form-group">

          <label for="password">Mot de passe</label>

          <input type="password" id="password" name="_password" class="form-control" placeholder="Vôtre mot de passe ..... ( en cas d'oublie aller voir Fabien ABISUR )">
      </div>
      <button type="submit" class="btn color-br">Se Connecter</button>
    </form>
</div>
{% endblock %}

API Platform Logging Headers from requests

$
0
0

I have an authentication issue on a production server, the issue is very likely to be non-code related but rather an IT configuration issue...

To prove this I would like to check if API Platform receives the Authorization header when trying to fetch data. I have not found anything about logs in the API Platform documentation. What is the right way of logging API requests and their headers using the Symfony logging systems, knowing that I don't have access to the actual controller code as it is purely configured using the APIRessource annotation on entities ?

To be clear, everything works fine in local, I'm not looking for a solution to my problem here, just a clean way to change the log format or add logs to incoming request using API Platform.

Symfony Cache Component configure persistent connection

$
0
0

I'm trying to figure it out how configure symfony + memcached adapter to use persistent connections.

In memcached documentation I found that it has a constructor argument

Memcached::__construct ([ string $persistent_id ] )

https://www.php.net/manual/en/memcached.construct.php

But by default in Symfony code I see it is set to null.

namespace Symfony\Component\Cache\Traits;

trait MemcachedTrait
{
    private static $defaultClientOptions = [
        'persistent_id' => null,
        'username' => null,
        'password' => null,
        \Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_PHP,
    ];

I've try to set it trough the default_memcached_provider config like this:

default_memcached_provider: memcached://localhost?tcp_keepalive=true&persistent_id=booking_website

Is it ok? How can I tell if it's working.

I'm monitoring the server with newrelic but I don't see any change time spent in memcached, perhaps because I don't have much traffic.

Viewing all 3925 articles
Browse latest View live


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