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

Vich Bundle - Symfony 4.4 - ApiPlatform - Flysystem - OVH S3 object store - guessMimeType PHP Exception on create and update

$
0
0

Vich version : 1.15.0
Symfony version : 4.4.13PHP version : 7.4API Platform version : 2.5.7flysystem-bundle version : 1.5.0flysystem-aws-s3-v3 version : 1.0.28

Summary

When creating or updating the object containing a file on a remote repository, an error occurs because it tries to read the MimeType of the file with its path while the file is not present on the server . I don't get any error when using local storage.

the error

request.CRITICAL: Uncaught PHP Exception Symfony\Component\Mime\Exception\InvalidArgumentException: "The "5f5b6d18c6671164117604.png" file does not exist or is not readable." at /var/www/html/vendor/symfony/mime/FileinfoMimeTypeGuesser.php line 50 {"exception":"[object] (Symfony\\Component\\Mime\\Exception\\InvalidArgumentException(code: 0): The \"5f5b6d18c6671164117604.png\" file does not exist or is not readable. at /var/www/html/vendor/symfony/mime/FileinfoMimeTypeGuesser.php:50)"} []

inFileinfoMimeTypeGuesser.php

namespace Symfony\Component\Mime;use Symfony\Component\Mime\Exception\InvalidArgumentException;use Symfony\Component\Mime\Exception\LogicException;/** * Guesses the MIME type using the PECL extension FileInfo. * * @author Bernhard Schussek <bschussek@gmail.com> */class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface{....public function guessMimeType(string $path): ?string    {        if (!is_file($path) || !is_readable($path)) {            throw new InvalidArgumentException(sprintf('The "%s" file does not exist or is not readable.', $path));        }        if (!$this->isGuesserSupported()) {            throw new LogicException(sprintf('The "%s" guesser is not supported.', __CLASS__));        }        if (false === $finfo = new \finfo(FILEINFO_MIME_TYPE, $this->magicFile)) {            return null;        }        $mimeType = $finfo->file($path);        if ($mimeType && 0 === (\strlen($mimeType) % 2)) {            $mimeStart = substr($mimeType, 0, \strlen($mimeType) >> 1);            $mimeType = $mimeStart.$mimeStart === $mimeType ? $mimeStart : $mimeType;        }        return $mimeType;    }}

I know the file is sent to the repository because it can be recovered with GET request.

How to reproduce

flysystem.yaml

flysystem:    storages:        uploads.storage.ovh:            adapter: "aws"            options:                client: "Aws\S3\S3Client"                bucket: "%env(OVH_BUCKET)%"        uploads.storage.local:            adapter: 'local'            options:                directory: "%kernel.project_dir%/var/storage/uploads"        uploads.storage.memory:            adapter: "memory"# switch with env        uploads.storage:            adapter: "lazy"            options:                source: "%env(APP_UPLOADS_SOURCE)%"

vich_uploader.yaml:

vich_uploader:    db_driver: orm    storage: flysystem    metadata:        auto_detection: true    mappings:        userAvatar:            upload_destination: uploads.storage            namer:                service: Vich\UploaderBundle\Naming\UniqidNamer            delete_on_remove: true  # determine whether to delete file upon removal of entity            delete_on_update: true  # determine wheter to delete the file upon update of entity            inject_on_load: false        productionCenterLogo:            upload_destination: uploads.storage            namer:                service: Vich\UploaderBundle\Naming\UniqidNamer            delete_on_remove: true            delete_on_update: true            inject_on_load: false        donneurOrdreLogo:            upload_destination: uploads.storage            namer:                service: Vich\UploaderBundle\Naming\UniqidNamer            delete_on_remove: true            delete_on_update: true            inject_on_load: false

service.yaml:

services:  Aws\S3\S3Client:    arguments:      - version: 'latest'        credentials:          key: '%env(OVH_ACCESS_KEY_ID)%'          secret: '%env(OVH_SECRET_ACCESS_KEY)%'        endpoint: '%env(OVH_ENDPOINT)%'        region: '%env(OVH_REGION)%'        S3:          version: '2006-03-01'          endpoint_url: '%env(OVH_ENDPOINT)%'          signature_version: 's3v4'          addressing_style: 'virtual'        S3API:          endpoint_url: '%env(OVH_ENDPOINT)%'

exemple of one entity:

<?phpnamespace App\Entity;use ApiPlatform\Core\Annotation\ApiResource;use Doctrine\ORM\Mapping as ORM;use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;use Symfony\Component\HttpFoundation\File\File;use Symfony\Component\Serializer\Annotation\Groups;use Symfony\Component\Validator\Constraints as Assert;use Vich\UploaderBundle\Mapping\Annotation as Vich;/** * @ORM\Entity(repositoryClass="App\Repository\UserAvatarRepository") * @ApiResource() * @Vich\Uploadable * @UniqueEntity(fields={"user"}, message="unique.userAvatar.user") */class UserAvatar extends FileUpload{    /**     * @Assert\File(     *     maxSize = "1980k",     *     mimeTypes = {     *      "image/jpeg",     *      "image/png",     *      "image/svg+xml",     *      }     * )     * @Assert\NotNull()     *     * @var File|null     * @Groups({     *     "file",     *     })     * @Vich\UploadableField(     *     mapping="userAvatar",     *     fileNameProperty="filePath",     *     size="imageSize",     *     originalName="originalName",     *     mimeType="mimeType",     *     dimensions="dimensions",     * )     */    public $imageFile;    /**     * @ORM\OneToOne(targetEntity=User::class, inversedBy="avatar")     * @ORM\JoinColumn(nullable=false, unique=true)     */    private User $user;    public function getUser(): User    {        return $this->user;    }    public function setUser(User $user): self    {        $this->user = $user;        return $this;    }    /**     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance     * of 'UploadedFile' is injected into this setter to trigger the update. If this     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter     * must be able to accept an instance of 'File' as the bundle will inject one here     * during Doctrine hydration.     *     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile|null $imageFile     */    public function setImageFile($imageFile = null): void    {        $this->imageFile = $imageFile;        if (null !== $imageFile) {            // It is required that at least one field changes if you are using doctrine            // otherwise the event listeners won't be called and the file is lost            $this->setUpdatedAt(new \DateTime());        }    }    public function getImageFile(): ?File    {        return $this->imageFile;    }}
<?phpnamespace App\Entity;use ApiPlatform\Core\Annotation\ApiProperty;use ApiPlatform\Core\Annotation\ApiResource;use App\Entity\Traits\UpdatedAtTrait;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\Serializer\Annotation\Groups;/** * @ORM\Entity(repositoryClass="App\Repository\FileUploadRepository") * @ApiResource() * @ORM\InheritanceType("JOINED") * @ORM\DiscriminatorColumn(name="type", type="string") * @ORM\DiscriminatorMap({ *     "userAvatar" = "App\Entity\UserAvatar", *     "productionCenterLogo" = "App\Entity\ProductionCenterLogo", *     "donneurOrdreLogo" = "App\Entity\DonneurOrdreLogo", * }) */abstract class FileUpload{    use UpdatedAtTrait;    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     * @ApiProperty(identifier=true)     */    private int $id;    /**     * @ORM\Column(type="string")     *     * @var string|null     * @Groups({     *     "file",     *     "user_read",     *     "production_center_read",     *     "donneur_ordre_read",     *     })     */    private $filePath;    /**     * @ORM\Column(type="string")     *     * @var string|null     * @Groups({     *     "file",     *     "user_read",     *     "production_center_read",     *     "donneur_ordre_read",     *     })     */    private $originalName;    /**     * @ORM\Column(type="string")     *     * @var string|null     * @Groups({     *     "file",     *     "user_read",     *     "production_center_read",     *     "donneur_ordre_read",     *     })     */    private $mimeType;    /**     * @ORM\Column(type="json", nullable=true)     *     * @var array|null     * @Groups({     *     "file",     *     "user_read",     *     "production_center_read",     *     "donneur_ordre_read",     *     })     */    private $dimensions;    /**     * @ORM\Column(type="integer", nullable=true)     *     * @var int|null     * @Groups({     *     "file",     *     "user_read",     *     "production_center_read",     *     "donneur_ordre_read",     *     })     */    private $imageSize;    public function setFilePath(?string $filePath): self    {        $this->filePath = $filePath;        return $this;    }    public function getFilePath(): ?string    {        return $this->filePath;    }    public function setImageSize(?int $imageSize): self    {        $this->imageSize = $imageSize;        return $this;    }    public function getImageSize(): ?int    {        return $this->imageSize;    }    public function getId(): int    {        return $this->id;    }    public function setId(int $id): self    {        $this->id = $id;        return $this;    }    public function getOriginalName(): ?string    {        return $this->originalName;    }    public function setOriginalName(?string $originalName): self    {        $this->originalName = $originalName;        return $this;    }    public function getMimeType(): ?string    {        return $this->mimeType;    }    public function setMimeType(?string $mimeType): self    {        $this->mimeType = $mimeType;        return $this;    }    public function getDimensions(): ?array    {        return $this->dimensions;    }    public function setDimensions(?array $dimensions): self    {        $this->dimensions = $dimensions;        return $this;    }}

Symfony 4 Tests

$
0
0

I want to inject ParameterBagInterface and EntityManagerInterface inside my unit tests (WebTestCase and KernelTestCase), but i couldn't find a method which returns their namespace and name correctly (Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface). is there a way for doing that?

what i have tried is:

$this->parameterBag = self::$container->get(ParameterBagInterface::class);

returns Symfony\Component\DependencyInjection\ParameterBag\ContainerBag

$this->parameterBag = $this->prophesize(ParameterBagInterface::class)->reveal();

returns Double\ParameterBagInterface\P1

$this->parameterBag = $this->createMock(ParameterBagInterface::class);

returns Mock_ParameterBagInterface_fccf09f9

All my classes are using ParameterBagInterface and are type-hinted as such.

Here is example test class:

/** * * @package App\Tests\Entity */class LogCollectTest extends WebTestCase{    use CronManagerCron;    /**     * @var EntityManager     */    private $em;    /**     * {@inheritDoc}     */    protected function setUp()    {        self::bootKernel();        $this->parameterBag = self::$container->get(ParameterBagInterface::class);    }    /**     * Test saving click     */    public function testSavingClick()    {        // truncate the log collect table to be sure to get the right click        $this->truncateLogCollectTable();        $userAgents = [...];        foreach ($userAgents as $agent => $expectedResult) {            // we make fake client requests and record them in database (test enviropment)            $clientStatus = $this->sendClientData($agent);            // the controller is resulting properly            $this->assertEquals(200, $clientStatus);            /**             * @var LogCollect $logCollectEntry             */            $logCollectEntry = $this->em->getRepository(LogCollect::class)->getLast(); <--         ...        // later we process this client requests with cron and later assert the data        $logCollectorCron = new LogCollectorCron(            $this->container,            $this->em,            $this->parameterBag,'test'        );        $logCollectorCron->run();        ...   }

Any suggestions?

Why my symfony captcha always return valid?

$
0
0

I followed this tutorial to add a captcha to my form.

First I install it using

composer require captcha-com/symfony-captcha-bundle:"4.*"

After I Install it, I got an error on a file called captcha.html.twigError:

captcha Unexpected "spaceless" tag (expecting closing tag for the"block" tag defined near line 2).

So I changed {% spaceless %} to {% apply spaceless %}And the error is gone.

But My captcha bot always returns True (even when I don't even fill it.Here is the ->add() function of my form:

->add('captchaCode', CaptchaType::class, ['captchaConfig' => 'ExampleCaptchaUserRegistration','constraints' => [        new ValidCaptcha(['message' => 'Invalid captcha, please try again',        ]),    ],]);

Code of Routes.yaml :

captcha_routing:    resource: "@CaptchaBundle/Resources/config/routing.yml"

Code of captcha.php :

<?php // app/config/packages/captcha.phpif (!class_exists('CaptchaConfiguration')) { return; }// BotDetect PHP Captcha configuration optionsreturn [    // Captcha configuration for example form'ExampleCaptchaUserRegistration' => ['UserInputID' => 'captchaCode','ImageWidth' => 250,'ImageHeight' => 50,    ],];

Captcha field on the User.php entity:

protected $captchaCode;public function getCaptchaCode(){  return $this->captchaCode;}public function setCaptchaCode($captchaCode){  $this->captchaCode = $captchaCode;}

Code in the View (twig)

<span class="txt1 p-b-11">    Are You a Robot?</span><div class="wrap-input100 m-b-36">    {{ form_widget(form.captchaCode, {'attr': {'class': 'input100'} }) }}       <span class="focus-input100"></span></div><div class="error">{{ form_errors(form.captchaCode) }} </div>

How to get products from the product stream ID in Shopware 6?

$
0
0

I am trying to create a custom command in which I want to utilize the Dynamic Product Group feature of Shopware 6 to fetch the products which match the filters in a specific product group (a.k.a product streams).

I am doing this to fetch the streams initially, but I am lost as to how to apply the filters to fetch the products.

            $streamCriteria = new Criteria($productStreamIds);            $streamCriteria->addAssociation('productCrossSellings');            $streamCriteria->addAssociation('productExports');            $streamCriteria->addAssociation('filters');            $streams = $this->streamRepository->search($streamCriteria, $context)->getEntities();            /** @var ProductStreamEntity $stream */            foreach ($streams as $stream) {                foreach ($stream->getFilters() as $filter) {                    $productCriteria->addAggregation($filter); // DOES NOT WORK                    $productCriteria->addFilter($filter); // DOES NOT WORK EITHER                }            }

I tried to get the filters which gives me the array of filters that are applied in the product stream, but it is not directly applicable to the criteria->addFilter() due to different expected types.

This is the filters array that I get:

Shopware\Core\Content\ProductStream\Aggregate\ProductStreamFilter\ProductStreamFilterCollection^ {#10304  #elements: array:5 ["2c6a8a44d9c544f2812024f6414d56f9" => Shopware\Core\Content\ProductStream\Aggregate\ProductStreamFilter\ProductStreamFilterEntity^ {#11014      #type: "multi"      #field: null      #operator: "OR"      #value: null      #productStreamId: "160274948d684a73afad0bde6aee19e8"      #parentId: null      #productStream: null      #queries: null      #parent: null      #position: 0      #parameters: null      #customFields: null      #_uniqueIdentifier: "2c6a8a44d9c544f2812024f6414d56f9"      #versionId: null      #translated: []      #createdAt: DateTimeImmutable @1600069477 {#3113        date: 2020-09-14 07:44:37.521 UTC (+00:00)      }      #updatedAt: null      #_entityName: "product_stream_filter"      #extensions: array:1 ["foreignKeys" => Shopware\Core\Framework\Struct\ArrayStruct^ {#11007          #data: []          #apiAlias: null          #extensions: []        }      ]      #id: "2c6a8a44d9c544f2812024f6414d56f9"    }"6dff7581e91a477ea2eca564a099eb90" => Shopware\Core\Content\ProductStream\Aggregate\ProductStreamFilter\ProductStreamFilterEntity^ {#10832      #type: "range"      #field: "width"      #operator: null      #value: null      #productStreamId: "160274948d684a73afad0bde6aee19e8"      #parentId: "2c6a8a44d9c544f2812024f6414d56f9"      #productStream: null      #queries: null      #parent: null      #position: 1      #parameters: array:1 ["lte" => 749      ]      #customFields: null      #_uniqueIdentifier: "6dff7581e91a477ea2eca564a099eb90"      #versionId: null      #translated: []      #createdAt: DateTimeImmutable @1600069477 {#2958        date: 2020-09-14 07:44:37.523 UTC (+00:00)      }      #updatedAt: null      #_entityName: "product_stream_filter"      #extensions: array:1 ["foreignKeys" => Shopware\Core\Framework\Struct\ArrayStruct^ {#10871          #data: []          #apiAlias: null          #extensions: []        }      ]      #id: "6dff7581e91a477ea2eca564a099eb90"    }"754b78c4ec74492bb96dc724f3e7ba6a" => Shopware\Core\Content\ProductStream\Aggregate\ProductStreamFilter\ProductStreamFilterEntity^ {#10766      #type: "range"      #field: "weight"      #operator: null      #value: null      #productStreamId: "160274948d684a73afad0bde6aee19e8"      #parentId: "2c6a8a44d9c544f2812024f6414d56f9"      #productStream: null      #queries: null      #parent: null      #position: 2      #parameters: array:1 ["gte" => 293      ]      #customFields: null      #_uniqueIdentifier: "754b78c4ec74492bb96dc724f3e7ba6a"      #versionId: null      #translated: []      #createdAt: DateTimeImmutable @1600069477 {#10274        date: 2020-09-14 07:44:37.525 UTC (+00:00)      }      #updatedAt: null      #_entityName: "product_stream_filter"      #extensions: array:1 ["foreignKeys" => Shopware\Core\Framework\Struct\ArrayStruct^ {#10774          #data: []          #apiAlias: null          #extensions: []        }      ]      #id: "754b78c4ec74492bb96dc724f3e7ba6a"    }"86d2c2bd8df14f8684c8f4c801e5a19a" => Shopware\Core\Content\ProductStream\Aggregate\ProductStreamFilter\ProductStreamFilterEntity^ {#10272      #type: "range"      #field: "height"      #operator: null      #value: null      #productStreamId: "160274948d684a73afad0bde6aee19e8"      #parentId: "2c6a8a44d9c544f2812024f6414d56f9"      #productStream: null      #queries: null      #parent: null      #position: 3      #parameters: array:1 ["gte" => 746      ]      #customFields: null      #_uniqueIdentifier: "86d2c2bd8df14f8684c8f4c801e5a19a"      #versionId: null      #translated: []      #createdAt: DateTimeImmutable @1600069477 {#10313        date: 2020-09-14 07:44:37.526 UTC (+00:00)      }      #updatedAt: null      #_entityName: "product_stream_filter"      #extensions: array:1 ["foreignKeys" => Shopware\Core\Framework\Struct\ArrayStruct^ {#11009          #data: []          #apiAlias: null          #extensions: []        }      ]      #id: "86d2c2bd8df14f8684c8f4c801e5a19a"    }"9b763069551244179dbc1f285290b673" => Shopware\Core\Content\ProductStream\Aggregate\ProductStreamFilter\ProductStreamFilterEntity^ {#10283      #type: "equalsAny"      #field: "id"      #operator: null      #value: "c01c974a89eb4f17ab78c48251864eb7|5c0e5bc5f03d42a6980c11bf8ab67428"      #productStreamId: "160274948d684a73afad0bde6aee19e8"      #parentId: "2c6a8a44d9c544f2812024f6414d56f9"      #productStream: null      #queries: null      #parent: null      #position: 0      #parameters: null      #customFields: null      #_uniqueIdentifier: "9b763069551244179dbc1f285290b673"      #versionId: null      #translated: []      #createdAt: DateTimeImmutable @1600069477 {#12983        date: 2020-09-14 07:44:37.522 UTC (+00:00)      }      #updatedAt: null      #_entityName: "product_stream_filter"      #extensions: array:1 ["foreignKeys" => Shopware\Core\Framework\Struct\ArrayStruct^ {#10356          #data: []          #apiAlias: null          #extensions: []        }      ]      #id: "9b763069551244179dbc1f285290b673"    }  ]  #extensions: []}

The productCrossSellings and productExports associations are all returning null as well (although I do not know what is the use of these variables, but I thought maybe it is being used somehow internally to get the associated products for that group).

So my question is, that how do we get the products that match the filters in a product group ?

whiteoctober/breadcrumbs-bundle incompatible with twig/twig 3.0

$
0
0

I've upgraded to new version of twig/twig 3.x.x. As of twig version 3.0 Twig_Extension is deprecated. So I'm getting next with "whiteoctober/breadcrumbs-bundle"

!!  In BreadcrumbsExtension.php line 12:!!                                                                         !!    Attempted to load class "Twig_Extension" from the global namespace.  !!    Did you forget a "use" statement?                                    

Any suggestion how to fix this?

Symfony 4 Test Issues

$
0
0

I have updated my symfony installation from 3.4 to 4.4 and encountered strange issue with the tests...

class TrackingChannelsControllerTest extends WebTestCase{    /**     * @var EntityManager     */    private $em;    private KernelBrowser $client;    /**     * @var object|ContainerBag|null     */    private $parameterBag;    /**     * {@inheritDoc}     */    public function setUp()    {        $this->client = self::createClient();        $this->em = self::$container->get('doctrine.orm.default_entity_manager');        $this->parameterBag = self::$container->get('parameter_bag');    }    /**     * {@inheritDoc}     */    protected function tearDown()    {        parent::tearDown();        $this->em->close();        $this->em = null; // avoid memory leaks        // clean global $_REQUEST method        $_REQUEST = [];    }    /**     * Test adding of the right channels for paid search without parameters     */    public function testChannelPaidSearchWithoutUtmParameters()    {        //////////////////        /// CLICK 1        //////////////////        // set there some default data, because this data is empty and is causing exceptions        $_SERVER[...] = ...         // send the request and save to click entity in database        $this->client->request('GET','/clka?...',            array(),            array(),            array('HTTP_HOST' => 'adv1.example.com','HTTP_USER_AGENT' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',            )        );        // the controller is resulting properly        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());        // get the last inserted Click        /**         * @var Click $click         */        $click = $this->em            ->getRepository(Click::class)            ->getLast();        // when i do check here with $this->em->contains($click); --> returns TRUE        //////////////////        /// CLICK 2        //////////////////        // set there some default data, because this data is empty and is causing exceptions        $_SERVER[...] = ...         // send the request and save to click entity in database        $this->client->request('GET','/clka?...',            array(),            array(),            array('HTTP_HOST' => 'adv1.example.com','HTTP_USER_AGENT' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',            )        );        // when i do check here with $this->em->contains($click); --> returns FALSE        // the controller is resulting properly        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());

Later if i try $this->em->remove($click) it says that my entity is detached and can't be deleted...

Did i missed something how Test clients started working?

Specs: Symfony 4.4 and doctrine-bundle doctrine/doctrine-bundle 1.12.10

Any suggestions are welcome!

Symfony 4 - Error 500 thrown instead of 403

$
0
0

I'm running Symfony 4/5, and for all my controllers in order to be able to execute the method I have an EventSubscriber that checks for the right permissions.

If the user is not granted, then it throws an AccessDeniedHttpException.This works fine as the method is binded to a route.But when rendering inside a twig template manually a controller action as :

{{ render( controller('App\ExampleBundle\Controller\ChartsController::renderChart' ) }}

I got a 500 error instead of a 403.

I've debugged the app and checked that the exception as actually thrown, but the browser shows a 500 exception.

Is this a bug, or do I have to handle in another way the exception when it is for manually rendered methods from a twig template ?

Material-ui dark theme in react with symfony

$
0
0

I am working with react 16.13 & symfony 4.4.13.

I have some issues putting my app in dark mode. The strange thing is that i can easily change some parameters in my const theme like the primary and secondary color but type:'dark' have no effects (no black background color for exemple).

enter image description here

my App.js :

import ReactDOM from "react-dom";import DefaultThemeProvider from "./Theme/theme";import React from "react";import Button from "@material-ui/core/Button";const App = () => {    return (<Button variant="contained" color="primary" href="#contained-buttons">            Link</Button>    )};const rootElement = document.querySelector('#app');ReactDOM.render(<DefaultThemeProvider><App/></DefaultThemeProvider>    , rootElement);

my theme.js :

import {createMuiTheme } from '@material-ui/core/styles';import green from '@material-ui/core/colors/green';import React from "react";import {MuiThemeProvider} from "@material-ui/core";const theme = createMuiTheme({    palette: {        type: 'dark',        primary: {            main: '#4444',        },        secondary: {            main: green[700],        },    },});const DefaultThemeProvider = (props) => {    return (<MuiThemeProvider theme={theme}>            {props.children}</MuiThemeProvider>    );};export default DefaultThemeProvider;

my package.json

{"devDependencies": {"@babel/preset-react": "^7.10.4","@symfony/webpack-encore": "^0.30.0","core-js": "^3.0.0","node-sass": "^4.14.1","regenerator-runtime": "^0.13.2","sass-loader": "^8.0.2","webpack-notifier": "^1.6.0"    },"license": "UNLICENSED","private": true,"scripts": {"dev-server": "encore dev-server --port 8080","dev": "encore dev","watch": "encore dev --watch","build": "encore production --progress"    },"dependencies": {"@material-ui/core": "^4.10.2","@material-ui/icons": "^4.9.1","@material-ui/lab": "^4.0.0-alpha.56","@material-ui/styles": "^4.10.0","@material-ui/system": "^4.9.14","axios": "^0.20.0","bootstrap": "^4.5.2","react": "^16.13.1","react-dom": "^16.13.1","react-router-dom": "^5.2.0"    }}

my webpack.config.js

var Encore = require('@symfony/webpack-encore');// Manually configure the runtime environment if not already configured yet by the "encore" command.// It's useful when you use tools that rely on webpack.config.js file.if (!Encore.isRuntimeEnvironmentConfigured()) {    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');}Encore    // directory where compiled assets will be stored    .setOutputPath('public/build/')    // public path used by the web server to access the output path    .setPublicPath('/build')    // only needed for CDN's or sub-directory deploy    //.setManifestKeyPrefix('build/')    /*     * ENTRY CONFIG     *     * Add 1 entry for each "page" of your app     * (including one that's included on every page - e.g. "app")     *     * Each entry will result in one JavaScript file (e.g. app.js)     * and one CSS file (e.g. app.css) if your JavaScript imports CSS.     */    .addEntry('app', './assets/js/app.js')    //.addEntry('page1', './assets/js/page1.js')    //.addEntry('page2', './assets/js/page2.js')    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.    .splitEntryChunks()    // will require an extra script tag for runtime.js    // but, you probably want this, unless you're building a single-page app    .enableSingleRuntimeChunk()    /*     * FEATURE CONFIG     *     * Enable & configure other features below. For a full     * list of features, see:     * https://symfony.com/doc/current/frontend.html#adding-more-features     */    .cleanupOutputBeforeBuild()    .enableBuildNotifications()    .enableSourceMaps(!Encore.isProduction())    // enables hashed filenames (e.g. app.abc123.css)    .enableVersioning(Encore.isProduction())    // enables @babel/preset-env polyfills    .configureBabelPresetEnv((config) => {        config.useBuiltIns = 'usage';        config.corejs = 3;    })    // enables Sass/SCSS support    .enableSassLoader()    // uncomment if you use TypeScript    //.enableTypeScriptLoader()    // uncomment to get integrity="..." attributes on your script & link tags    // requires WebpackEncoreBundle 1.4 or higher    //.enableIntegrityHashes(Encore.isProduction())    // uncomment if you're having problems with a jQuery plugin    //.autoProvidejQuery()    // uncomment if you use API Platform Admin (composer req api-admin)    .enableReactPreset()    //.addEntry('admin', './assets/js/admin.js');

module.exports = Encore.getWebpackConfig();

like i am working with symfony i wonder if there is something to do with my webpack.config.js ?


Symfony 4 Custom login form

$
0
0

I currently have a basic login system on my Symfony (4.4) application.Now, I need a special login system that does not use a username and a password but two custom fields. (called sn and key)

I tried to do it with another guard authenticator but without success.Then I found out that it was possible to create a form_login in security.yaml that would handle all of this automatically. But without success either.

Can you help me please? I'm lost. (not an english speaker, sorry for the mistakes)

Here is my security.yaml file:

security:    encoders:        App\Entity\User:            algorithm: auto    # 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        app_kit_provider:            entity:                class: App\Entity\Kit                property: serial_number    firewalls:        dev:            pattern: ^/(_(profiler|wdt)|css|images|js)/            security: false        main:            pattern: ^/security            anonymous: lazy            provider: app_user_provider            guard:                authenticators:                    - App\Security\LoginFormAuthenticator            logout:                path: app_logout                # where to redirect after logout                target: security_home        ecert:            anonymous: lazy            provider: app_kit_provider#            form_login:#                login_path: home#                check_path: home#                username_parameter: serial_number#                password_parameter: random_key            guard:                authenticators:                    - App\Security\EcertFormAuthenticator            logout:                path: ecert_logout                target: home

My login form:

{% extends 'base.html.twig' %}{% block body %}<h1>{% trans %}Welcome to your E-cert portal{% endtrans %}</h1><hr><div class="jumbotron jumbotron-fluid"><div class="container"><h2>This is a title</h2><p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam architecto atque autem consectetur cum dolorem dolorum, ducimus eius facere id illum libero, nobis officiis quae quis quos repudiandae velit voluptatibus.</p></div></div><form action="{{ path('home') }}" method="post"><h2 class="h3 mb-3 font-weight-normal">{% trans %}Please enter your E-cert credentials{% endtrans %}</h2><div class="row"><div class="col-lg-6"><label for="inputSn">{% trans %}Serial Number{% endtrans %}</label><input type="text" name="serial_number" id="inputSn" class="form-control" required autofocus></div><div class="col-lg-6"><label for="inputKey">{% trans %}Secret Key{% endtrans %}</label><input type="text" name="random_key" id="inputKey" class="form-control" required></div></div>{#        <input type="hidden" name="_csrf_token"#}{#               value="{{ csrf_token('authenticate') }}"#}{#        >#}<button class="mt-3 btn btn-success" type="submit">            {% trans %}Access my E-cert space{% endtrans %}</button></form>{% endblock %}

Symfony 4 - password saved in argon2i instead of bcrypt only on prod server

$
0
0

In my yaml security config file :

security:    encoders:        App\Entity\Tenant\User:          algorithm: 'bcrypt'

In my user controller to modify password for user edit page :

$user->setPassword($passwordEncoder->encodePassword($user,$plain_password));

On my developpement server in prod and dev environnement everythings work.But on my prod server symfony convert password in argon2i instead of bcrypt. I dont know why....So in my database for exemple stocked hashed password is "$argon2i$v=19$m=65536,t=4,p=1$aFRHTC5sQTZESXpOOVlFTA$NZvz/a0EkjL00cf9ZbYzuhiT+nMq13Dvr2Xp/lU78Lc" instead of bcrypt.

Someone would have any idea why UserPasswordEncoderInterface force argon2I only on my prod server instead of bcrypt which is set in the yaml security file?

Dev server : PHP 7.3.12.

Prod server : PHP 7.3.19

Symfony 4.4.5

Previously executed migration are not registered migrations

$
0
0

I'm trying to update my database with those commands

php bin/console make:migration

this return success

But when I try

php bin/console doctrine:migrations:migrate

I have this error:

WARNING! You have 5 previously executed migrations in the database >>that are not registered migrations.

>> 2018-12-17 10:42:04 (20181217104204)>> 2018-12-17 13:19:24 (20181217131924)>> 2018-12-17 13:40:58 (20181217134058)>> 2018-12-18 10:41:38 (20181218104138)>> 2018-12-18 13:15:49 (20181218131549)

Thing is, the database listed here are not in my migrations table from my database and they are not in my Migrations folder either.

How can I remove those wrong migrations ? Thanks.

Symfony 4 MongoDB ODM One to ONe relationship is not working

$
0
0

I am facing an error with symfony and mongoDB odm on one to one relationshipfor example i have a user that has Work .

User Class:

/** * @MongoDB\Document * @MongoDBUnique(fields="email") */class User implements UserInterface{    /**     * @MongoDB\Id     */    private $id;    /**     * @MongoDB\Field(type="string")     */    private $firstName;    /**     * @MongoDB\Field(type="string")     */    private $lastName;    /**     * @MongoDB\Field(type="string")     * @Assert\NotBlank()     * @Assert\Email()     */    private $email;    /**     * @MongoDB\ReferenceOne(targetDocument=Work::class)     */    private $work;    //getter setter

Work Class:

class Work{    /**     * @MongoDB\Id()     */    private $id;    /**     * @MongoDB\ReferenceOne(targetDocument=User::class)     */    private $user;   //getter setter}

Controller:

class TestingController extends AbstractController{    /**     * @Route("/testing", name="testing")     * @param DocumentManager $documentManager     * @return Response     * @throws MongoDBException     */    public function index(DocumentManager $documentManager)    {        $user = new User();        $user->setFirstName('test1');        $user->setLastName('test2');        $user->setEmail('test123@gmail.com');        $documentManager->persist($user);        $work= new Work();        $work->setUser($user);        $documentManager->persist($work);        $documentManager->flush();        return new Response("test");    }    /**     * @Route("/test", name="test")     * @param DocumentManager $documentManager     * @return Response     */    public function test(DocumentManager $documentManager){        $user = $documentManager->getRepository(User::class)->findAll();        dump($user);        return new Response("test test");    }}

So I created 2 classes one as user that has one work, I created the user , then I created a work and i assigned the user from the work class.in MongoDB compass I got under Work collection a reference for the user.

now in the test method in the controller i try to find the users and dump the data.The problem is whenever i want to find $user->getWork() i get a null value, while the user exists. but the inverse is working fine . whenever i try $work->getUser() i can find the user.

is there anything wrong in my code ? I want to use both methods : $user->getWork() and $work->getUser(),I have tried adding to the ReferenceOne mappedBy and inversedBy but its always one of the two methods returns null value.

Symfony 4 Doctrine using setter getter fuction to store different data in same field

$
0
0

I am working in a web application developed by PHP framework Symfony 4. I am not really familiar with Doctrine. So i need help in this case.In existing database, there is a entity called "type". Now from one field from Form data directly saved in "type".I need to store the data from 2 different input field, "type" and "key", from Form to "type" and store it in database, using third bracket, like this type[key]. And need to separately access the data from database.
I can not change the database, so i have to do it in this manner. Could you please tell me how to do this?Previous code was this ~

    /**     * @ORM\Column(type="string", length=255, nullable=true)     * @Assert\Length(     *      min = 0,     *      max = 255,     *      minMessage = "ジャンルを入力して下さい。",     *      maxMessage = "ジャンルを255文字以内に抑えて下さい。"     * )     */    private $type; public function getType()    {        return $this->type;    }    public function setType($type)    {        $this->type = $type;        return $this;    }

Now i changed the code like the following manner ~

  public function getType()    {        return $this->type;    }    public function setType($type,$key)    {        $this->type = $type + [$key];        return $this;    }    public function getKey()    {        return $this->type;    }

Chekc if the given time slot falls under the range?

$
0
0

I want to verify if the given two times are available in the table for booking.

I have fields timeFrom& timeTo

|timeFrom| |timeTo|12:00:00   14:00:00

This is the query I have written in Symfony:

    $qb = $this->createQueryBuilder('booking')                ->select();    $qb->andWhere($qb->expr()->andX("booking.timeFrom BETWEEN :timeFrom AND :timeTo",        $qb->expr()->orX(            $qb->expr()->andX("booking.timeTo BETWEEN :timeFrom AND :timeTo"),            $qb->expr()->andX("booking.timeFrom <= :timeFrom AND booking.timeTo >= :timeFrom")        )    ))    ->setParameters(['timeFrom' => $timeFrom,'timeTo' => $timeTo,    ]);

Its raw SQL is like this:

SELECT booking FROM booking WHERE (booking.timeFrom BETWEEN :timeFrom AND :timeTo) AND ((booking.timeTo BETWEEN :timeFrom AND :timeTo) OR (booking.timeFrom <= :timeFrom AND booking.timeTo >= :timeFrom))

Problem is when I pass two values 13:00 & 14:00; my query is not working.

Can anybody please help me fix this problem.

Thank You.

Check if the given time slot falls under the range?

$
0
0

I want to verify if the given two times are available in the table for booking.

I have fields timeFrom& timeTo

|timeFrom| |timeTo|12:00:00   14:00:00

This is the query I have written in Symfony:

    $qb = $this->createQueryBuilder('booking')                ->select();    $qb->andWhere($qb->expr()->andX("booking.timeFrom BETWEEN :timeFrom AND :timeTo",        $qb->expr()->orX(            $qb->expr()->andX("booking.timeTo BETWEEN :timeFrom AND :timeTo"),            $qb->expr()->andX("booking.timeFrom <= :timeFrom AND booking.timeTo >= :timeFrom")        )    ))    ->setParameters(['timeFrom' => $timeFrom,'timeTo' => $timeTo,    ]);

Its raw SQL is like this:

SELECT booking FROM booking WHERE    (booking.timeFrom BETWEEN :timeFrom AND :timeTo) AND    (      (booking.timeTo BETWEEN :timeFrom AND :timeTo) OR      (booking.timeFrom <= :timeFrom AND booking.timeTo >= :timeFrom)    )

Problem is when I pass two values 13:00 & 14:00; my query is not working.

Can anybody please help me fix this problem.

Thank You.


How to do functional test with authentication in Symfony 4 with phpUnit, to access a url?

$
0
0

I am trying to follow the documentation below:

I want to test a view, which is only accessible if I am authenticated.My problem is that I can't get it to work. It constantly returns a 301 redirect to the login page. I show you the code following the previous documentation:

class DefaultControllerTest extends WebTestCase {private $client = null;public function setUp(){    $this->client = static::createClient();}public function testSecuredHello(){    $this->logIn();    $crawler = $this->client->request('GET', 'panel/');    self::assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());    self::assertSame('Mi Panel', $crawler->filter('h1')->text());}private function logIn(){    $session = self::$container->get('session');    // somehow fetch the user (e.g. using the user repository) *MOCKUP    $user = new User();    $user->setId(1);    $user->setEmail('sefhi@gmail.com');    $user->setPassword('qwerty');    $user->setRoles($user->getRoles());    $user->setName('Sefhi');    $user->setActive(true);    $user->setFlgClientBlocked(true);    $user->setDocumentOnline('asdsadasd');    $user->setIdAtenea(123213);    $user->setPhone('600000000');    $user->setIdTypeDocument(1);    $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, null, $firewallName, $user->getRoles());    $session->set('_security_' . $firewallContext, serialize($token));    $session->save();    $cookie = new Cookie($session->getName(), $session->getId());    $this->client->getCookieJar()->set($cookie);}}

I show you the config I have from the security.yml

security:# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providersproviders:    app_user_provider:        id: App\Security\UserProviderencoders:    App\Security\User:        algorithm: argon2ifirewalls:    dev:        pattern: ^/(_(profiler|wdt)|css|images|js)/        security: false    main:        anonymous: true        json_login:            check_path: login_ajax            remember_me: true        form_login:            provider: app_user_provider            csrf_token_generator: security.csrf.token_manager            login_path: /login        logout:            path:   app_logout            target: main        remember_me:            secret:   '%kernel.secret%'            lifetime: 604800 # 1 week in seconds            path:     /            user_providers: [app_user_provider]        guard:            authenticators:                - App\Security\LoginFormAuthenticator                - App\Security\TokenAuthenticator            entry_point: App\Security\LoginFormAuthenticator        # activate different ways to authenticate        # http_basic: true        # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate        # form_login: true        # https://symfony.com/doc/current/security/form_login_setup.htmlrole_hierarchy:    ROLE_ADMIN:       ROLE_USER    ROLE_SUPER_ADMIN: [ ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]# Easy way to control access for large sections of your site# Note: Only the *first* access control that matches will be usedaccess_control:   #- { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }   #- { path: ^/main, roles: IS_AUTHENTICATED_ANONYMOUSLY }   - { path: ^/panel, roles: ROLE_USER }   - { path: ^/propuesta, roles: ROLE_USER }   - { path: ^/cliente, roles: ROLE_USER }   - { path: ^/cita, roles: ROLE_USER }

The crawler always returns a 301 to me, so the authentication is not working. I don't know how to solve it the truth. I don't think it's a routes problem, because if it were a routes problem, it would return a 404.

TypeError DoctrineParamConverter.php (line 46)

$
0
0

i'm new to symfony framework.I've installed it by following the tutorial in the official documentation Setup.And i've created a new project with the following commande symfony new portfolio2 --full, i ran the commande symfony server:start and every think was as suspected a default page showed up with the header * Welcome to Symfony 4.4.13 .....*.I faced the problem when i was triying to create my first page by following the official documentation Create your First Page in Symfony.

I've configured the routes.yml file:

#index:#    path: /#    controller: App\Controller\DefaultController::index# config/routes.yaml# the "app_lucky_number" route name is not important yetapp_lucky_number:    path: /lucky/number    controller: App\Controller\LuckyController::number

i've added the LuckyController.php

<?php// src/Controller/LuckyController.phpnamespace App\Controller;use Symfony\Component\HttpFoundation\Response;class LuckyController{    public function number()    {        $number = random_int(0, 100);        return new Response('<html><body>Lucky number: '.$number.'</body></html>'        );    }}

but when i run the server and try to access http://localhost:8000/lucky/number, the following TypeError is shown

        Argument 1 passed toSensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter::__construct() must be an instance of Doctrine\Common\Persistence\ManagerRegistry or null, instance of Doctrine\Bundle\DoctrineBundle\Registry given, called in F:\projects\portfolio2\var\cache\dev\ContainerEnYgzlJ\srcApp_KernelDevDebugContainer.php on line 4306

TypeError

in F:\projects\portfolio2\vendor\sensio\framework-extra-bundle\src\Request\ParamConverter\DoctrineParamConverter.php (line 46)

41 /**     42 * @var array     43 */44 private $defaultOptions;  45  46 public function __construct(ManagerRegistry $registry = null, ExpressionLanguage $expressionLanguage = null, array $options = [])    47 {        48 $this->registry = $registry;        49 $this->language = $expressionLanguage;        5051 $defaultValues = [

i did exactly what the documentation says, also i tried to clear the var\cache but it didn't work.

i'm using PHP 7.2.4, symfony 4.4 and here is my composer.json:

{"type": "project","license": "proprietary","require": {"php": ">=7.1.3","ext-ctype": "*","ext-iconv": "*","composer/package-versions-deprecated": "^1.11","doctrine/annotations": "^1.0","doctrine/doctrine-bundle": "^2.1","doctrine/doctrine-migrations-bundle": "^3.0","doctrine/orm": "^2.7","phpdocumentor/reflection-docblock": "^5.2","sensio/framework-extra-bundle": "^5.1","symfony/asset": "4.4.*","symfony/console": "4.4.*","symfony/dotenv": "4.4.*","symfony/expression-language": "4.4.*","symfony/flex": "^1.3.1","symfony/form": "4.4.*","symfony/framework-bundle": "4.4.*","symfony/http-client": "4.4.*","symfony/intl": "4.4.*","symfony/mailer": "4.4.*","symfony/monolog-bundle": "^3.1","symfony/process": "4.4.*","symfony/property-access": "4.4.*","symfony/property-info": "4.4.*","symfony/security-bundle": "4.4.*","symfony/serializer": "4.4.*","symfony/translation": "4.4.*","symfony/twig-bundle": "4.4.*","symfony/validator": "4.4.*","symfony/web-link": "4.4.*","symfony/yaml": "4.4.*","twig/extra-bundle": "^2.12|^3.0","twig/twig": "^2.12|^3.0"    },"require-dev": {"symfony/browser-kit": "^4.4","symfony/css-selector": "^4.4","symfony/debug-bundle": "^4.4","symfony/maker-bundle": "^1.0","symfony/phpunit-bridge": "^5.1","symfony/var-dumper": "^4.4"    },"config": {"preferred-install": {"*": "dist"        },"sort-packages": true    },"autoload": {"psr-4": {"App\\": "src/"        }    },"autoload-dev": {"psr-4": {"App\\Tests\\": "tests/"        }    },"replace": {"paragonie/random_compat": "2.*","symfony/polyfill-ctype": "*","symfony/polyfill-iconv": "*","symfony/polyfill-php71": "*","symfony/polyfill-php70": "*","symfony/polyfill-php56": "*"    },"scripts": {"auto-scripts": {"cache:clear": "symfony-cmd","assets:install %PUBLIC_DIR%": "symfony-cmd"        },"post-install-cmd": ["@auto-scripts"        ],"post-update-cmd": ["@auto-scripts"        ]    },"conflict": {"symfony/symfony": "*"    },"extra": {"symfony": {"allow-contrib": false,"require": "4.4.*"        }    }}

Can you help me fix this issue? (if it possible with details about what causes the problem)

And thank you in advance.

How to select all users who are registered in all the same events as current user

$
0
0

I'm using Symfony 4. I have 3 entities , User, Event, EventRegistration.

class User { /** * @ORM\OneToMany(targetEntity="App\Entity\EventRegistration", mappedBy="user", cascade={"persist","remove"}) */public $eventsRegistrations;}class Event{/** * @ORM\OneToMany(targetEntity="App\Entity\EventRegistration ", mappedBy="event") * @ORM\JoinColumn(nullable=false) */private $registrations;}class EventRegistration {/** * @ORM\ManyToOne(targetEntity="App\Entity\Event", inversedBy="registrations") * @ORM\JoinColumn(nullable=false) */private $event;/** * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="eventsRegistrations") * @ORM\JoinColumn(nullable=false) */private $user;}

I'd like to know how to select all users who are registered in all the same events as current user using one query not two as I did.

Right now I have created two queries:

EventRegistrationRepository:

// select all events ids in where the current user has been registeredpublic function myEventsIds($user){    $arrayEventssIds = array();    $qb = $this->createQueryBuilder('e')        ->where('e.user = :user')        ->setParameter('user', $user)        ->getQuery()        ->getResult();    foreach ($qb as $registration) {        array_push($arrayEventssIds , $registration->getEvent()->getId());    }    return $registration;}

then in UserRepository :

public function usersRegistredInTheSameEvents($user, $arrayEventsIds){  //arrayEventsIds contains the events ids selected in the query above    $qb = $this->createQueryBuilder('u')        ->innerJoin('u.eventsRegistrations', 'er')        ->where('er.event IN (:arrayEventsIds)')        ->andWhere('er.user != :user')        ->setParameter('arrayEventsIds', $arrayEventsIds)        ->setParameter('user', $user)        ->addGroupBy('u.id');    return $qb->getQuery()->getResult();}}

How to combine combine these two queries in just one ?

TypeError DoctrineParamConverter.php (line 46)

$
0
0

i'm new to symfony framework.I've installed it by following the tutorial in the official documentation Setup.And i've created a new project with the following commande symfony new portfolio2 --full, i ran the commande symfony server:start and every think was as suspected a default page showed up with the header * Welcome to Symfony 4.4.13 .....*.I faced the problem when i was triying to create my first page by following the official documentation Create your First Page in Symfony.

I've configured the routes.yml file:

#index:#    path: /#    controller: App\Controller\DefaultController::index# config/routes.yaml# the "app_lucky_number" route name is not important yetapp_lucky_number:    path: /lucky/number    controller: App\Controller\LuckyController::number

i've added the LuckyController.php

<?php// src/Controller/LuckyController.phpnamespace App\Controller;use Symfony\Component\HttpFoundation\Response;class LuckyController{    public function number()    {        $number = random_int(0, 100);        return new Response('<html><body>Lucky number: '.$number.'</body></html>'        );    }}

but when i run the server and try to access http://localhost:8000/lucky/number, the following TypeError is shown

        Argument 1 passed toSensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter::__construct() must be an instance of Doctrine\Common\Persistence\ManagerRegistry or null, instance of Doctrine\Bundle\DoctrineBundle\Registry given, called in F:\projects\portfolio2\var\cache\dev\ContainerEnYgzlJ\srcApp_KernelDevDebugContainer.php on line 4306

TypeError

in F:\projects\portfolio2\vendor\sensio\framework-extra-bundle\src\Request\ParamConverter\DoctrineParamConverter.php (line 46)

41 /**     42 * @var array     43 */44 private $defaultOptions;  45  46 public function __construct(ManagerRegistry $registry = null, ExpressionLanguage $expressionLanguage = null, array $options = [])    47 {        48 $this->registry = $registry;        49 $this->language = $expressionLanguage;        5051 $defaultValues = [

i did exactly what the documentation says, also i tried to clear the var\cache but it didn't work.

i'm using PHP 7.2.4, symfony 4.4 and here is my composer.json:

{"type": "project","license": "proprietary","require": {"php": ">=7.1.3","ext-ctype": "*","ext-iconv": "*","composer/package-versions-deprecated": "^1.11","doctrine/annotations": "^1.0","doctrine/doctrine-bundle": "^2.1","doctrine/doctrine-migrations-bundle": "^3.0","doctrine/orm": "^2.7","phpdocumentor/reflection-docblock": "^5.2","sensio/framework-extra-bundle": "^5.1","symfony/asset": "4.4.*","symfony/console": "4.4.*","symfony/dotenv": "4.4.*","symfony/expression-language": "4.4.*","symfony/flex": "^1.3.1","symfony/form": "4.4.*","symfony/framework-bundle": "4.4.*","symfony/http-client": "4.4.*","symfony/intl": "4.4.*","symfony/mailer": "4.4.*","symfony/monolog-bundle": "^3.1","symfony/process": "4.4.*","symfony/property-access": "4.4.*","symfony/property-info": "4.4.*","symfony/security-bundle": "4.4.*","symfony/serializer": "4.4.*","symfony/translation": "4.4.*","symfony/twig-bundle": "4.4.*","symfony/validator": "4.4.*","symfony/web-link": "4.4.*","symfony/yaml": "4.4.*","twig/extra-bundle": "^2.12|^3.0","twig/twig": "^2.12|^3.0"    },"require-dev": {"symfony/browser-kit": "^4.4","symfony/css-selector": "^4.4","symfony/debug-bundle": "^4.4","symfony/maker-bundle": "^1.0","symfony/phpunit-bridge": "^5.1","symfony/var-dumper": "^4.4"    },"config": {"preferred-install": {"*": "dist"        },"sort-packages": true    },"autoload": {"psr-4": {"App\\": "src/"        }    },"autoload-dev": {"psr-4": {"App\\Tests\\": "tests/"        }    },"replace": {"paragonie/random_compat": "2.*","symfony/polyfill-ctype": "*","symfony/polyfill-iconv": "*","symfony/polyfill-php71": "*","symfony/polyfill-php70": "*","symfony/polyfill-php56": "*"    },"scripts": {"auto-scripts": {"cache:clear": "symfony-cmd","assets:install %PUBLIC_DIR%": "symfony-cmd"        },"post-install-cmd": ["@auto-scripts"        ],"post-update-cmd": ["@auto-scripts"        ]    },"conflict": {"symfony/symfony": "*"    },"extra": {"symfony": {"allow-contrib": false,"require": "4.4.*"        }    }}

Can you help me fix this issue? (if it possible with details about what causes the problem)

And thank you in advance.

Symfony 4: Conflict between two firewalls

$
0
0

I currently have two login systems on my Symfony (4.4) application.

Separately (when I comment on one of the two associated firewalls), the two forms work well. But when they are together, the second one doesn't work. (nothing happens, the page simply reloads after submitting the form)

Here is my security.yaml file :

security:    encoders:        App\Entity\User:            algorithm: auto    # 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        app_kit_provider:            entity:                class: App\Entity\Kit                property: serial_number    firewalls:        dev:            pattern: ^/(_(profiler|wdt)|css|images|js)/            security: false        ecert:            pattern: ^/(en|fr)/            anonymous: lazy            provider: app_kit_provider            guard:                authenticators:                    - App\Security\EcertAuthenticator            logout:                path: ecert_logout                target: ecert_login        main:            pattern: ^/(en|fr)/security/            anonymous: lazy            provider: app_user_provider            guard:                authenticators:                    - App\Security\LoginFormAuthenticator            logout:                path: app_logout                target: security_home

LoginFormAuthenticator:

<?phpnamespace App\Security;use App\Entity\User;use Doctrine\ORM\EntityManagerInterface;use Symfony\Component\HttpFoundation\RedirectResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\Routing\Generator\UrlGeneratorInterface;use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;use Symfony\Component\Security\Core\Security;use Symfony\Component\Security\Core\User\UserInterface;use Symfony\Component\Security\Core\User\UserProviderInterface;use Symfony\Component\Security\Csrf\CsrfToken;use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;use Symfony\Component\Security\Http\Util\TargetPathTrait;class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface{    use TargetPathTrait;    public const LOGIN_ROUTE = 'app_login';    private $entityManager;    private $urlGenerator;    private $csrfTokenManager;    private $passwordEncoder;    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)    {        $this->entityManager = $entityManager;        $this->urlGenerator = $urlGenerator;        $this->csrfTokenManager = $csrfTokenManager;        $this->passwordEncoder = $passwordEncoder;    }    public function supports(Request $request)    {        return self::LOGIN_ROUTE === $request->attributes->get('_route')&& $request->isMethod('POST');    }    public function getCredentials(Request $request)    {        $credentials = ['username' => $request->request->get('username'),'password' => $request->request->get('password'),'csrf_token' => $request->request->get('_csrf_token'),        ];        $request->getSession()->set(            Security::LAST_USERNAME,            $credentials['username']        );        return $credentials;    }    public function getUser($credentials, UserProviderInterface $userProvider)    {        $token = new CsrfToken('authenticate', $credentials['csrf_token']);        if (!$this->csrfTokenManager->isTokenValid($token)) {            throw new InvalidCsrfTokenException();        }        $user = $this->entityManager->getRepository(User::class)->findOneBy(['username' => $credentials['username']]);        if (!$user) {            // fail authentication with a custom error            throw new CustomUserMessageAuthenticationException('Username could not be found.');        }        return $user;    }    public function checkCredentials($credentials, UserInterface $user)    {        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);    }    /**     * Used to upgrade (rehash) the user's password automatically over time.     */    public function getPassword($credentials): ?string    {        return $credentials['password'];    }    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)    {        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {            return new RedirectResponse($targetPath);        }        return new RedirectResponse($this->urlGenerator->generate('create_kit'));    }    protected function getLoginUrl()    {        return $this->urlGenerator->generate(self::LOGIN_ROUTE);    }}

EcertAuthenticator:

<?phpnamespace App\Security;use App\Entity\Kit;use Doctrine\ORM\EntityManagerInterface;use Symfony\Component\HttpFoundation\RedirectResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\Routing\Generator\UrlGeneratorInterface;use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;use Symfony\Component\Security\Core\Security;use Symfony\Component\Security\Core\User\UserInterface;use Symfony\Component\Security\Core\User\UserProviderInterface;use Symfony\Component\Security\Csrf\CsrfToken;use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;use Symfony\Component\Security\Http\Util\TargetPathTrait;class EcertAuthenticator extends AbstractFormLoginAuthenticator{    use TargetPathTrait;    public const LOGIN_ROUTE = 'ecert_login';    private $entityManager;    private $urlGenerator;    private $csrfTokenManager;    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager)    {        $this->entityManager = $entityManager;        $this->urlGenerator = $urlGenerator;        $this->csrfTokenManager = $csrfTokenManager;    }    public function supports(Request $request)    {        return self::LOGIN_ROUTE === $request->attributes->get('_route')&& $request->isMethod('POST');    }    public function getCredentials(Request $request)    {        $credentials = ['serial_number' => $request->request->get('serial_number'),'random_key' => $request->request->get('random_key'),'csrf_token' => $request->request->get('_csrf_token'),        ];        $request->getSession()->set(            Security::LAST_USERNAME,            $credentials['serial_number']        );        return $credentials;    }    public function getUser($credentials, UserProviderInterface $userProvider)    {        $token = new CsrfToken('authenticate', $credentials['csrf_token']);        if (!$this->csrfTokenManager->isTokenValid($token)) {            throw new InvalidCsrfTokenException();        }        $user = $this->entityManager->getRepository(Kit::class)->findOneBy(['serial_number' => $credentials['serial_number']]);        if (!$user) {            // fail authentication with a custom error            throw new CustomUserMessageAuthenticationException('Serial_number could not be found.');        }        return $user;    }    public function checkCredentials($credentials, UserInterface $user)    {        if ($this->entityManager->getRepository(Kit::class)->findOneBy(['serial_number' => $credentials['serial_number'], 'random_key' => $credentials['random_key']])) {            return true;        }        return false;    }    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)    {        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {            return new RedirectResponse($targetPath);        }        return new RedirectResponse($this->urlGenerator->generate('ecert'));    }    protected function getLoginUrl()    {        return $this->urlGenerator->generate(self::LOGIN_ROUTE);    }}

Do you know why?

Thanks

Viewing all 3927 articles
Browse latest View live


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