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

How to access the value of one attribute of one table from another table (One-to-One bi-directional relationship) in Symfony 4?

$
0
0

I have two classes (application and employee), which relate with a One-to-One directional relationship.

In my application class I have four attributes:

  • id_application
  • name_app
  • responsible_app
  • responsible_app_backup_1
  • responsible_app_backup_2
  • employee_id

In my employee table I have three attributes:

  • id_employee
  • uid_employee
  • first_name
  • last_name
  • application_id

Employee:

@ORM\OneToOne(targetEntity="App\Entity\Application", mappedBy="employee", cascade={"persist", "remove"})
private $application;

Application:

@ORM\OneToOne(targetEntity="App\Entity\Employee", inversedBy="application", cascade={"persist", "remove"})
@Groups("gdc_group_application")
private $employee;

How can I list out uid_employee, first_name, and last_name to each responsible_app, responsible_app_backup_1, responsible_app_backup_2?

Like this:

enter image description here


Infection Throws Exeption, but why, and how to handle it?

$
0
0

The Task is that the error does bot explain that problem right.

The Error:

Project tests must be in a passing state before running Infection.
Infection runs the test suite in a RANDOM order. Make sure your tests do not have hidden dependencies.

You can add these attributes to phpunit.xml to check it:

If you don't want to let Infection run tests in a random order, set the executionOrder to some value, for example

Check the executed command to identify the problem: '/usr/bin/php7.2''-d''zend_extension=xdebug.so''/mnt/e/dev/bin/phpunit''--configuration''/mnt/e/dev/var/infection/
infection/phpunitConfiguration.initial.infection.xml''-vvv'
PHPUnit reported an exit code of 143.
Refer to the PHPUnit's output below:
STDERR:

Cannot load Xdebug - it was already loaded

What i try is simple to execute follow statement:

vendor/bin/infection --threads=10 --only-covered

But when I try that statement that explained in that error, the tests will run successfully, but that is only my unit tests without the mutation-testing.

Here is an abstract of phpunit tag in my phpunit.xml.dist

<phpunit .... backupGlobals="false" colors="false" bootstrap="/mnt/e/dev/RESTler/config/bootstrap.php" executionOrder="random" resolveDependencies="true" cacheResult="false" stopOnFailure="true" stderr="false" .../>

The Versions are:

  • PHPUnit version: 7.5.15
  • PHP 7.2.22-1+ubuntu18.04.1+deb.sury.org+1
  • Infection - PHP Mutation Testing Framework 0.14.2
  • Symfony Framework 4.2

has anyone a hint of what I can try or where my error is?

Session based authentication in api-platform

$
0
0

I am trying to setup session based authentication instead of JWT that I have currently in use, because I don´t want to store JWT token in local storage.

I have managed to authenticate myself using this guide https://symfony.com/doc/current/security/json_login_setup.html and get response data about the user.

But further requests to any endpoint I get 401 unauthorized.

This is my security yaml

security:
encoders:
    App\Entity\User:
        algorithm: bcrypt
providers:
    app_user_provider:
        entity:
            class: App\Entity\User
            property: email
firewalls:
    dev:
        pattern: ^/_(profiler|wdt)
        security: false
    api:
        pattern: ^/api/
        stateless: true
        anonymous: true
        provider: app_user_provider
        json_login:
            check_path: /api/login
            username_path: email
            password_path: password
            #success_handler: lexik_jwt_authentication.handler.authentication_success
            #failure_handler: lexik_jwt_authentication.handler.authentication_failure

        #guard:
        #   authenticators:
        #      - lexik_jwt_authentication.jwt_token_authenticator
    main:
        anonymous: true
access_control:
    - { path: ^/api/authentication_token,   roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/graphql,                roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/form/,                  roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/,                       roles: IS_AUTHENTICATED_FULLY }
    - { path: ^/,                           roles: IS_AUTHENTICATED_ANONYMOUSLY }

On the official api-platform documentation there is no word of using session based login which I find odd.

Thank you

Symfony4 PHPUnit Testing Custom Validator

$
0
0

My goal is to test the custom validator with PHPUnit.

EmailValidation.php:

<?php

namespace App\Components\Validator\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 * @Target({"PROPERTY", "ANNOTATION"})
 */
class EmailValidation extends Constraint
{
    public $message = 'This email "{{ value }}" is not valid. Please enter another email again.';
}

EmailValidationValidator.php:

<?php

namespace App\Components\Validator\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use MMM\SingleValidation;

class EmailValidationValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $apikey = $_ENV['API_KEY'];
        $mbv = new SingleValidation($apikey);
        if ($apikey == '') {

        } else {
            $results = $mbv->ValidateEmail($value);
            if ($results === false) {
                return; //return "Error connecting to API."
            } else if (trim($results->error_code) == '') {
                if ($results->status == 'True') {
                    return;
                }
            } else if (trim($results->error_code) != '') {
                return;
            }

            // TODO: implement the validation here
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $value)
                ->addViolation();
        }
    }
}

Test.php:

<?php

namespace App\Tests;

use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
use MMM\SingleValidation;
use App\Components\Validator\Constraint\EmailValidationValidator;
use App\Components\Validator\Constraint\EmailValidation;
use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\ExecutionContextInterface;
use Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface;

class Test extends TestCase
{

/**
* @dataProvider validEmail
*/
public function testValidation($value)
{
$constraint = new EmailValidation();
/** @var ExecutionContextInterface|MockObject $context */
$context = $this->getMockExecutionContext();
$context->expects($this->never())
->method('buildViolation');
$validator = new EmailValidationValidator();
$validator->initialize($context);
$validator->validate($value, $constraint);
}

/**
* @dataProvider invalidEmail
*/
public function testValidationFail($value)
{
$constraint = new EmailValidation();
/** @var ExecutionContextInterface|MockObject $context */
$context = $this->getMockExecutionContext();
$context->expects($this->atLeast(1))
->method('buildViolation')
->with($constraint->message)
->willReturn($this->getMockConstraintViolationBuilder());
$validator = new EmailValidationValidator();
$validator->initialize($context);
$validator->validate($value, $constraint);
}

public function validEmail()
{
return [
['test@gmail.com'],
];
}

public function invalidEmail()
{
return [
['test@example.com'],
];
}

private function getMockExecutionContext()
{
$context = $this->getMockBuilder(Execution::class)
->disableOriginalConstructor()
->getMock();
return $context;
}

private function getMockConstraintViolationBuilder()
{
$constraintViolationBuilder = $this->getMockBuilder(ConstraintViolationBuilderInterface::class)
->getMock();
$constraintViolationBuilder
->method('setParameter')
->willReturn($constraintViolationBuilder);
$constraintViolationBuilder
->method('setValue')
->willReturn($constraintViolationBuilder);
$constraintViolationBuilder
->method('addViolation');
return $constraintViolationBuilder;
}
}

I have get some errors. Like this:

App\Tests\Test::testValidation with data set #0 ('test@gmail.com') Trying to configure method "buildViolation" which cannot be configured because it does not exist, has not been specified, is final, or is static

The test code I was referred to someone else, so I have no idea how to solve the code. Anyone has idea to help me ? Thanks

Symfony 4 make entity regenerate : no changes

$
0
0

I updated from symfony 4.3 to symfony 4.4 and since (i think), when i regenerate an entity, the new field added is not regenerated.

I add a $new_field in my entity:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * FondsInfos
 *
 * @ORM\Table(name="fonds_infos")
 * @ORM\Entity
 */
class FondsInfos
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     */
    private $pre_coche_arbitrage;

    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     */
    private $new_field;

}

After i do :

php bin/console make:entity --regenerate App\Entity\FondsInfos

Result :

updated: src/Entity/FondsInfos.php

  Success! 

At the end i have all my field except "new_field" generated and i don't understand why!

Somebody has an idea of the problem ? I try lot of things but don't find the problem.

Thanks for your help

Get most common value in SF4 [closed]

$
0
0

I have an article and categories entity, connected in manytoone (Symfony 4) And I would like to retrieve categories that have the most items in order. However, I do not see how to do it. Do you have any help so that I can solve my problem? thank you so much :)

Symfony Doctrine - Delete one of two sub-entities via Ajax and submit form afterwards doubles leftover one

$
0
0

I have a strange behaviour in symfony-doctrine and don't know the reason: I have a form with an entity A with sub-entities RESULT like this:

--ENTITY [A]

-- attr 1-x

-- ADD RESULT -> add Result(s)

Everything works like a charme. I can create entity A and add more sub-entities RESULT to it.

.

But when editing I got the following error:

Let's say, I have TWO sub-entities RESULT on my edit-form. I implemented some small AJAX-method to delete each by klicking on each trash icon:

public function deleteResult(Request $request, Repository\Result $resultRepo): JsonResponse
{
    $resultId = (integer)trim($request->get('result', false));
    $result = $resultRepo->find($resultId);
    $em = $this->getDoctrine()->getManager();
    $em->remove($result);
    $em->flush();

    return new JsonResponse('done');
}

Simple as it is: the method will delete the result, give back an JSON object, javascript deletes the result out of the form and the user can go on editing other stuff on the form.

BUT, if he/she now submits the form, the remaining result will be COPIED by doctrine with a new ID and all it's values.

Can anybody explain me this behaviour? I am guessing it is not smart to flush the EM during an open "form-session"? - Because without deleting, everyhting works on the edit-page, too. So the question is: how to avoid this behaviour in doctrine? Adding the result-id as hidden-field changes nothing, btw.

I am using symfony 4.3 with php 7.2 and would be happy for any answer Thank you very much in advance :)

Paxum credit card payment

$
0
0

I would like to integrate Paxum for credit card payment into a Symfony 4 application, however I could not find any guide for that. Could you provide some information how can I do that? Currently I'm trying with omnipay-symfony-bundle and hidev/omnipay-paxum but I can't see how can I use it for card payment.

Any tip would be appreciated.


Symfony 4 redirect after user authentication on IIS (sf_redirect cookie)

$
0
0

I'm using Symfony 4 and need users to be authenticated before accessing any page. These are my firewall-settings:

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: ~
        access_denied_handler: App\Security\AccessDeniedHandler
        guard:
            authenticators:
                - App\Security\UserAuthenticator
        logout:
            path: app_logout        # logout-route
            target: app_loggedout   # where to go after successful logout

And this is the access_control (also in security.yaml):

access_control:
    - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/loggedout, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/, roles: ROLE_USER }

The class UserAuthenticator is called, users are authenticated automatically (because of the username that is provided in the $_SERVER-variable).

But now: I want the user to be redirected to the original URL after the authentication. E.g. if the user wants to go to SITE/test, this should happen automatically after they pass through the UserAuthenticator. I have managed to achieve this by using the sf_redirect-cookie which Symfony seems to set automatically, it contains something like this:

{"token":"b2282c","route":"app_some_url","method":"GET","controller":{"class":"App\\Controller\\SecurityController","method":"some_method","file":"<PATH>\\src\\Controller\\SecurityController.php","line":23},"status_code":302,"status_text":"Found"}

In my UserAuthenticator I check if the cookie is there, is filled and has a route set and then return a RedirectRespone leading to the route in onAuthenticationSuccess().

The problem is: While this works fine on Apache (dev-system), the sf_redirect-cookie is missing completely on IIS (prod-system). It's not that IIS would not set cookies at all ($_COOKIE['PHPSESSID'] is there), it's just that sf_redirect is missing.

I've been experimenting with a custom subscriber to the redirect-to-login-event, but I'd rather not use a workaround, so the question is: How can I tell Symfony to set the sf_redirect-cookie on IIS, or how do I need to configure IIS to set it?

Symfony version up-gradation from 3.4 to 4.3 using old folder structure and ERROR

$
0
0

I am trying to upgrade the Symfony version from 3.4 to 4.3 but the requirement is to keep the same folder structure as it was in 3.4 because of namespaces and other dependencies.

enter image description here

My Findings: 1. Part of the setup is done. Need to configure for completion. 2. In the new version, we need to inject other classes or service as like an Argument in method

But the problem is that while I install / update composer it always returns:

Script Symfony-cmd handling the auto-scripts event returned with error code 127
Script @auto-scripts was called via post-install-cmd

and Another Big problem is there in app.php or app_dev.php

Here is my JSON:

        {
        "name": "web",
        "license": "proprietary",
        "type": "project",
        "description": " Web",
    "autoload": {
        "psr-4": { "": "src/" },
        "classmap": [ "app/AppKernel.php", "app/AppCache.php" ]
    },
    "require": {
        "php": ">=7.1",
        "symfony/symfony": "^3.4",
        "twig/twig": "^1.35",
        "symfony/monolog-bundle": "^3",
        "sensio/distribution-bundle": "~5.0",
        "sensio/framework-extra-bundle": "^3.0.2",
        "incenteev/composer-parameter-handler": "~2.0",
        "leaseweb/api-caller-bundle": "1.2.*",
        "twig/extensions": "^1.3",
        "jms/serializer-bundle": "^1.0.0",
        "lexik/jwt-authentication-bundle": "^1.7",
        "stof/doctrine-extensions-bundle": "^1.2",
        "knplabs/knp-menu-bundle": "^2.0",
        "misd/phone-number-bundle": "1.1.*",
        "snilius/twig-sort-by-field": "^0.1.5",
        "suncat/mobile-detect-bundle": "1.0.*",
        "predis/predis":                        "^1.0",
        "snc/redis-bundle":                     "^2",
        "guzzlehttp/guzzle": "^6",
        "leafo/scssphp": "^0.6.7",
        "symfony/assetic-bundle": "^2.8",
        "eightpoints/guzzle-bundle": "dev-master",
        "friendsofsymfony/jsrouting-bundle": "^1.6",
        "jms/security-extra-bundle": "^1.6",
        "gpslab/geoip2": "^1.1",
        "ext-json" : "*",
        "alcaeus/mongo-php-adapter": "^1.1"

    },
    "require-dev": {
        "sensio/generator-bundle": "~3.0",
        "symfony/phpunit-bridge": "~2.7"
    },
        "scripts": {
            "post-install-cmd": [
                "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget",
                "WebBundle\\Composer\\ScriptHandler::createProfilePicDirectory"
            ],
            "post-update-cmd": [
                "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget",
                "WebBundle\\Composer\\ScriptHandler::createProfilePicDirectory"
            ]
        },
        "config": {
            "bin-dir": "bin"
        },
    "minimum-stability": "stable",
        "extra": {
            "symfony-app-dir": "app",
            "symfony-web-dir": "web",
            "symfony-assets-install": "relative",
            "incenteev-parameters": {
                "file": "app/config/parameters.yml"
            },
        "branch-alias": {
            "dev-master": "1.2-dev"
        }
        }
    }

in APP.PHP

<?php

    use Symfony\Component\HttpFoundation\Request;

    /**
    * @var Composer\Autoload\ClassLoader
    */
    $loader = require __DIR__.'/../app/autoload.php';
    include_once __DIR__.'/../app/bootstrap.php.cache';

    // Enable APC for autoloading to improve performance.
    // You should change the ApcClassLoader first argument to a unique prefix
    // in order to prevent cache key conflicts with other applications
    // also using APC.
    /*
    $apcLoader = new Symfony\Component\ClassLoader\ApcClassLoader(sha1(__FILE__), $loader);
    $loader->unregister();
    $apcLoader->register(true);
    */

    $kernel = new AppKernel('prod', false);
    $kernel->loadClassCache();
    //$kernel = new AppCache($kernel);

    // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
    //Request::enableHttpMethodParameterOverride();
    $request = Request::createFromGlobals();
    Request::setTrustedHeaderName(Request::HEADER_FORWARDED, null);
    $response = $kernel->handle($request);
    $response->send();
    $kernel->terminate($request, $response);

ERRORS are getting :

ERROR 1. while composer install ->Script Symfony-cmd handling the auto-scripts event returned with error code 127

ERROR 2. $response = $kernel->handle($request); in app.php

Other API routes are working but for the handler, I am getting the error for app.php file.

Symfony Weekday Select

$
0
0

this is my first question, so sorry if I miss some information.

In my project I try to create a FormType with a ChoiceType. The ChoiceType should contain the weekdays (eg. monday, tuesday, etc).

Now I was wondering how I should deal with this exactly? First things which came in my mind are: - create a new weekday entity and store the weekdays in the database - put the weekdays in the choices as static array - somehow define a global array with the weekdays

I do not really like any solution though. So i was wondering if there is a general PHP way to get all weekday names for my ChoiceType. Also I'd like to reuse the same array multiple times (thats why I dont want to use a static array). The database solution could work, but that means I would have to define each weekday in every instance of my project - which also seems not ideal.

Thanks for any help

Does Symfony 4 loads the environment variables on every request in the "prod" environment?

$
0
0

Does Symfony 4 somehow save or cache the environment variable parameters in the "prod" environment or does it retrieve them on every request?

My problem is that when I host my Symfony application using Apache, I need to list all the environment variables by defining them all in the VirtualHost configuration using SetEnv directives; and I would prefer not having to do that.

I would expect that when using the PHP CLI, I could "compile" the Symfony project by capturing or caching the parameters so that when the application is run through Apache, it uses these "cached" parameters.

Is it doable or the SetEnv approach is the only one?

How to fix Composer\Exception\NoSslException in Symfony4

$
0
0

I have a problem when i create a new project in Symfony4.

i use this command for start a new project:

C:\Users\Chris\code> composer create-project symfony/website-skeleton api-test

And composer answers me :

[Composer\Exception\NoSslException]                                      
  The openssl extension is required for SSL/TLS protection but is not av   
  ailable. If you can not enable the openssl extension, you can disable    
  this error, at your own risk, by setting the 'disable-tls' option to t   
  rue.   

i check php.ini in wamperserver64 :

...
extension=exif      ; Must be after mbstring as it depends on it
extension=mysqli
;extension=odbc
extension=openssl
;extension=pdo_firebird
extension=pdo_mysql
;extension=pdo_oci
;extension=oci8_12c  ;
...

How i can fix this problem ?

Thanks all

Symfony Validate TimeType

$
0
0

So I am using TimeType fields in my FormType and was wondering how the validation might work there.

To be more precise, I have two TimeTypes and I want to check that the second one is after the first one.

I've used the Validation constraint GreaterThan, which correctly validates my field. However I have 2 problems which come in my mind:

  • should I also use LessThan on the first field?
  • the validation message outputs that my field has to be greather than "01.01.1970 05:00" which is not the error message I expect (date should be removed) how do I achieve this? Also translations should work for that.

Thanks

Check if entity property exists

$
0
0

I have an URL like example.org/overview/<column>/<value> (example: example.org/overview/color/red) which will cause a search in a column "color" for the value "red". This is the entity:

<?php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

// @ORM\Entity(repositoryClass="App\Repository\CarRepository")
class Car
{
    // @ORM\Column(type="string", length=255)
    private $name;
    private $color;

    [...]

I think I should check if an entity property exists before I start a db query. How can I check when someone calls example.org/overview/foo/bar if foo is a valid db column (= entity property)? Does Symfony offer a simple solution here? If this might not be the case I think I have to use a hard coded white list.


Symfony 4 : How to customize fos user bundle authentication controller

$
0
0

I'm working on symfony 4 api and angular for frontend side project and I want to develop mail confirmation action to confirm user's account. can some one guide me where to find the login and mail confirmation actions to refactor and how to edit the response of my api and send to angular side.

Symfony 4 JWT authentication - Pre login event listener

$
0
0

Is it possible to trigger pre-login event listener to check if user status is enabled with JWT authentication ?

I want something like that in my listener:

if (!$user->getStatus()) {
   return new JsonResponse(['message': 'Your account is not activated'],403)
}

The default config of jwt in my security.yaml is:

firewalls:        
       login:
            pattern: ^/api/1.0/login
            stateless: true
            anonymous: true
            json_login:
                check_path: /api/1.0/login_check
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
                require_previous_session: false

Symfony 4 | Load custom configuration block from YAML file

$
0
0

It's me again, Hi.

Today I need to load a custom block from a configuration file located in a custom bundle, I have the following code in my bundle:

class ExampleAdminExtension extends Extension {

    /**
     * Loads a specific configuration.
     *
     * @throws \InvalidArgumentException When provided tag is not defined in this extension
     */
    public function load(array $configs, ContainerBuilder $container) {
        $loader = new YamlFileLoader( $container, new FileLocator(__DIR__.'/../Resources/config') );
        $loader->load('custom.yaml');
    }
}

Then the custom.yaml:

parameters:
  allowTraps: 
    - 'Eeeeh?'
    - 'Easy modo??'
    - 'How lame!'

This does works, having everything inside parameters I can go to a random controller and then print its records with:

$trapsAllowed = $this->getParameter('allowTraps');
dump($trapsAllowed);

The question here is, when I add a custom block outside parameters like this:

parameters:
  allowTraps: 
    - 'Eeeeh?'
    - 'Easy modo??'
    - 'How lame!'

items:
  - 'Maruchan'
  - 'How to turn off my chainsaw??'
  - 'Heelppplp'

it throws an error that says:

There is no extension able to load the configuration for "items". Looked for namespace "items", found none

I wish to know how can I achieve this, have a custom configuration block a load it successfully like when I put it inside the parameters block.

Thank you for reading me.

nelmio-api-doc/swagger-ui how overwrite displayRequestDuration

$
0
0

The Problem is easy to describe, i want to show the request duration on the swagger-ui from the nelmio\api-doc-bundle.

In the documentation from https://api-platform.com/ i cant find something about this topic.

The Documentation of Swagger-ui it self says it work by set the js variable "displayRequestDuration" on true->https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/

when i overwrite the hole swagger.ui.js then its not more update safe. When i overwrite the generatet file in public folder, then its still overwriting, after a change. When i try to set it in "nelmio_api_doc.yaml" nothing happens

nelmio_api_doc:
    documentation:
        displayRequestDuration: true

Someone a hint or knows why how i can make display that request duration?

using group-css-media-queries with webpack Encore

$
0
0

i'm using Webpack Encore in a Symfony 4 project.

As css preprocessor, i use SCSS.

I use @media directly in the properties, so my compilated css is full of redondant @media declaration.

I want to add group-css-media-queries in the Webpack Encore configuration to group all same @media declaration.

I can't find anything about modifying a loader in the Webpack Encore Documentation.

I think, group-css-media-queries must be added in the postCompilation, just before minimisation (for prodution).

Someone has an way to do that ?

This is my Webpack Encore Configuration :

var Encore = require('@symfony/webpack-encore');
const SVGSpritemapPlugin = require('svg-spritemap-webpack-plugin');

if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .addStyleEntry('css/styles', './assets/scss/styles.scss')
    .addStyleEntry('css/partial', './assets/scss/partial.scss')
    .addEntry('js/app', './assets/js/app.js')
    .splitEntryChunks()
    .enableSingleRuntimeChunk()
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction())
    .configureBabel(() => {}, {
        useBuiltIns: 'usage',
        corejs: 3
    })
    .enableSassLoader()
    .enablePostCssLoader()
    .enableIntegrityHashes(Encore.isProduction())
    .copyFiles({
      from: './assets/images',
      to: Encore.isProduction() ? 'images/[path][name].[hash:8].[ext]' : 'images/[path][name].[ext]',
      pattern: /\.(png|jpg|jpeg|gif|svg)$/
    })
    .copyFiles({
      from: './assets/fonts',
      to: Encore.isProduction() ? 'fonts/[path][name].[hash:8].[ext]' : 'fonts/[path][name].[ext]',
      pattern: /\.(ttf|woff(2)|eot|svg)$/
    })
    .addPlugin(new SVGSpritemapPlugin(
      'assets/icons/*.svg', {
        output: {
          filename: Encore.isProduction() ? 'icons/sprite.svg' : 'icons/sprite.svg',
          svg4everybody: true,
          svgo: true
        }
      }
    ))
;
module.exports = Encore.getWebpackConfig();
Viewing all 3916 articles
Browse latest View live