Explore all Symfony open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Symfony

symfony

v6.0.7

composer

2.3.4

fetch

bower

grav

Popular Libraries in Symfony

symfony

by symfony doticonphpdoticon

star image 26732 doticonMIT

The Symfony PHP framework

composer

by composer doticonphpdoticon

star image 26405 doticonMIT

Dependency Manager for PHP

fetch

by github doticonjavascriptdoticon

star image 25051 doticonMIT

A window.fetch JavaScript polyfill.

bower

by bower doticonjavascriptdoticon

star image 15076 doticonMIT

A package manager for the web

grav

by getgrav doticonphpdoticon

star image 13208 doticonMIT

Modern, Crazy Fast, Ridiculously Easy and Amazingly Powerful Flat-File CMS powered by PHP, Markdown, Twig, and Symfony

inflector

by doctrine doticonphpdoticon

star image 10486 doticonMIT

Doctrine Inflector is a small library that can perform string manipulations with regard to uppercase/lowercase and singular/plural forms of words.

deployer

by deployphp doticonphpdoticon

star image 9147 doticonMIT

A deployment tool written in PHP with support for popular frameworks out of the box

console

by symfony doticonphpdoticon

star image 9096 doticonMIT

The Console component eases the creation of beautiful and testable command line interfaces.

http-foundation

by symfony doticonphpdoticon

star image 8127 doticonMIT

The HttpFoundation component defines an object-oriented layer for the HTTP specification.

Trending New libraries in Symfony

clutch

by lyft doticongodoticon

star image 1307 doticonApache-2.0

Extensible platform for infrastructure management

deprecation-contracts

by symfony doticonphpdoticon

star image 1305 doticonMIT

A generic function and convention to trigger deprecation notices

polyfill-php80

by symfony doticonphpdoticon

star image 1232 doticonMIT

This component provides functions unavailable in releases prior to PHP 8.0.

browser-fs-access

by GoogleChromeLabs doticonjavascriptdoticon

star image 828 doticonApache-2.0

File System Access API with legacy fallback in the browser

SeetaFace6

by seetafaceengine doticonc++doticon

star image 533 doticon

SeetaFace 6: Newest open and free, full stack face recognization toolkit.

ketch

by shipa-corp doticongodoticon

star image 522 doticonApache-2.0

Ketch is an application delivery framework that facilitates the deployment and management of applications on Kubernetes using a simple command line interface

ux

by symfony doticonphpdoticon

star image 461 doticonMIT

Symfony UX initiative: a new JavaScript ecosystem for Symfony

terminal

by TitasGailius doticonphpdoticon

star image 451 doticon

An Elegent wrapper around Symfony's Process component.

polyfill-php81

by symfony doticonphpdoticon

star image 443 doticonMIT

This component provides functions unavailable in releases prior to PHP 8.1.

Top Authors in Symfony

1

symfony

165 Libraries

star icon279180

2

Sylius

78 Libraries

star icon8671

3

sonata-project

35 Libraries

star icon7287

4

fxpio

34 Libraries

star icon131

5

KnpLabs

33 Libraries

star icon10633

6

liip

28 Libraries

star icon2306

7

doctrine

27 Libraries

star icon50053

8

symfony-cmf

26 Libraries

star icon1227

9

Setono

25 Libraries

star icon230

10

oroinc

22 Libraries

star icon2893

1

165 Libraries

star icon279180

2

78 Libraries

star icon8671

3

35 Libraries

star icon7287

4

34 Libraries

star icon131

5

33 Libraries

star icon10633

6

28 Libraries

star icon2306

7

27 Libraries

star icon50053

8

26 Libraries

star icon1227

9

25 Libraries

star icon230

10

22 Libraries

star icon2893

Trending Kits in Symfony

No Trending Kits are available at this moment for Symfony

Trending Discussions on Symfony

Error: While updating laravel 8 to 9. Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Symfony Doctrine EntityManager not refreshing properly

PHPStan and Doctrine: $id is never written, only read

Laravel 9 - laravel new command has error: Deprecated: Return type of Symfony\Component\Process\Process::getIterator(int $flags = 0)

Localhost refused to connect on WSL2 when accessed via https://localhost:8000/ but works when using internal WSL IP adress

How to handle Symfony 5.3 deprecations?

How to Validate huge data using LazyCollection Laravel

Wrong PHP Version/Executable in VSCode terminal but works perfectly in Mac terminal

Symfony #[CurrentUser] attribute returns null

Symfony 5.3 empty collection with a OneToMany relation

QUESTION

Error: While updating laravel 8 to 9. Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Asked 2022-Mar-29 at 06:51

Nothing to install, update or remove Generating optimized autoload files Class App\Helpers\Helper located in C:/wamp64/www/vuexylaravel/app\Helpers\helpers.php does not comply with psr-4 autoloading standard. Skipping. > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi

1   Error 
2
3  Undefined constant Illuminate\Http\Request::HEADER_X_FORWARDED_ALL
4  at C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php:48
5     44▕      * - 'HEADER_X_FORWARDED_AWS_ELB' (If you are using AWS Elastic Load Balancer)
6     45▕      *
7     46▕      * @link https://symfony.com/doc/current/deployment/proxies.html
8     47▕      */
9  ➜  48▕     'headers' => Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,
10     49▕
11     50▕ ];
12     51▕
13
14  1   C:\wamp64\www\vuexylaravel\vendor\laravel\framework\src\Illuminate\Support\ServiceProvider.php:138
15      require()
16
17  2   C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\src\TrustedProxyServiceProvider.php:28
18      Illuminate\Support\ServiceProvider::mergeConfigFrom("C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php", "trustedproxy")
19Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
20

ANSWER

Answered 2022-Feb-13 at 17:35

If you are upgrading your Laravel 8 project to Laravel 9 by importing your existing application code into a totally new Laravel 9 application skeleton, you may need to update your application's "trusted proxy" middleware.

Within your app/Http/Middleware/TrustProxies.php file, update use Fideloper\Proxy\TrustProxies as Middleware to use Illuminate\Http\Middleware\TrustProxies as Middleware.

Next, within app/Http/Middleware/TrustProxies.php, you should update the $headers property definition:

// Before...

protected $headers = Request::HEADER_X_FORWARDED_ALL;

// After...

1   Error 
2
3  Undefined constant Illuminate\Http\Request::HEADER_X_FORWARDED_ALL
4  at C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php:48
5     44▕      * - 'HEADER_X_FORWARDED_AWS_ELB' (If you are using AWS Elastic Load Balancer)
6     45▕      *
7     46▕      * @link https://symfony.com/doc/current/deployment/proxies.html
8     47▕      */
9  ➜  48▕     'headers' => Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,
10     49▕
11     50▕ ];
12     51▕
13
14  1   C:\wamp64\www\vuexylaravel\vendor\laravel\framework\src\Illuminate\Support\ServiceProvider.php:138
15      require()
16
17  2   C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\src\TrustedProxyServiceProvider.php:28
18      Illuminate\Support\ServiceProvider::mergeConfigFrom("C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php", "trustedproxy")
19Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
20protected $headers =
21    Request::HEADER_X_FORWARDED_FOR |
22    Request::HEADER_X_FORWARDED_HOST |
23    Request::HEADER_X_FORWARDED_PORT |
24    Request::HEADER_X_FORWARDED_PROTO |
25    Request::HEADER_X_FORWARDED_AWS_ELB;
26

then run composer update

Make sure you are using PHP 8.0

Source https://stackoverflow.com/questions/71103241

QUESTION

Symfony Doctrine EntityManager not refreshing properly

Asked 2022-Mar-14 at 13:18

I have a ratchet WebSocket server, whose entityManager is initialized from the backend. However, if some changes happen from one of the front-ends since the state of the entityManager of the WebSocket server is different from the backend, the new changes are not reflected in the data that is served by the WebSocket server.

For this purpose, I wrote some listeners on the backend that listen for changes in these entities in and then send a request to the server like so:

1public function postUpdate(Room $entity, LifecycleEventArgs $_)
2{
3    try {
4        Loop::run(function() use ($entityName, $id) {
5        $conn = yield connect('ws://localhost:8080');
6        yield $conn->send(json_encode(['message' => $entityName, 'data' => ['duid' => $id]]));
7        $conn->close();});
8    } catch (Exception $e) {}
9}
10

I then fetch the entity in the WebSocket server and simply refresh it, like so:

1public function postUpdate(Room $entity, LifecycleEventArgs $_)
2{
3    try {
4        Loop::run(function() use ($entityName, $id) {
5        $conn = yield connect('ws://localhost:8080');
6        yield $conn->send(json_encode(['message' => $entityName, 'data' => ['duid' => $id]]));
7        $conn->close();});
8    } catch (Exception $e) {}
9}
10function onMessage(ConnectionInterface $from, $msg)
11{
12    try {
13        $messageData = json_decode($msg);
14        switch ($messageData->message) {
15            case BookingSocketActions::ROOM_CHANGED_EVENT:
16//                $room = $this->entityManager->getRepository('ResourcesBundle:Room')
17//                                            ->find(['id' => $id]);
18                $room = $this->entityManager->getRepository('ResourcesBundle:Room')
19                                            ->findRoomDetailById($messageData->data->duid);
20                // $this->entityManager->clear();
21                $this->entityManager->refresh($room);
22                break;
23        }
24    } catch (Exception $ex) {
25        $from->send($ex);
26    }
27}
28

Now here is the strange bug: The state of the $entity that is refreshed in the WebSocket server is always one behind the real changes of the entity. Suppose I change $entity->name from "1" to "2".

After the refresh $entity->name is still "1" on the WebSocket server. Only if I change it again to sth else, e.g. "3", will it change to "2" (after the refresh). If I change it to "4", it will go to "3" and so on.

The event is firing correctly from the backend and the entity is being fetched correctly on the server. It's just that refresh() works only on a second request (and therefore a second refresh) to the WebSocket server but not on the first.

I have tried even things like $entityManager->merge($entity); but no results.

I am on symfony 3.4, doctrine 2.7, and ratchet 0.4.3.

ANSWER

Answered 2022-Mar-08 at 15:30

Doctrine uses the identity map

The websocket server is a daemon and all cleanup tasks are the responsibility of the developer

Use

\Doctrine\ORM\EntityManager::find with the $lockMode argument = \Doctrine\DBAL\LockMode::NONE

OR

Call the \Doctrine\ORM\EntityManager::clean method before \Doctrine\ORM\EntityManager::find

Source https://stackoverflow.com/questions/71337399

QUESTION

PHPStan and Doctrine: $id is never written, only read

Asked 2022-Feb-21 at 14:15

I am using PHP8, symfony5 and doctrine2 with phpstan and getting these errors:

1Property App\Entity\User::$id is never written, only read.  
2

The code:

1Property App\Entity\User::$id is never written, only read.  
2<?php
3
4namespace App\Entity;
5
6use App\Repository\UserRepository;
7use Doctrine\Common\Collections\ArrayCollection;
8use Doctrine\Common\Collections\Collection;
9use Doctrine\ORM\Mapping as ORM;
10use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
11use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
12use Symfony\Component\Security\Core\User\UserInterface;
13
14/**
15 * @ORM\Table(name="`user`")
16 * @ORM\Entity(repositoryClass=UserRepository::class)
17 * @UniqueEntity(fields={"email"}, message="There is already an account with this email")
18 */
19class User implements UserInterface, PasswordAuthenticatedUserInterface
20{
21    public const ROLE_USER = 'ROLE_USER';
22    public const ROLE_ADMIN = 'ROLE_ADMIN';
23
24    /**
25     * @ORM\Id
26     * @ORM\GeneratedValue
27     * @ORM\Column(type="integer")
28     */
29    private $id;
30
31    /**
32     * @ORM\Column(type="string", length=180, unique=true)
33     */
34    private $email;
35
36    /**
37     * @ORM\Column(type="json")
38     */
39    private $roles = [];
40
41    /**
42     * @var string The hashed password
43     * @ORM\Column(type="string")
44     */
45    private $password;
46
47    /**
48     * @ORM\Column(type="boolean")
49     */
50    private $isVerified = false;
51
52    public function __construct()
53    {
54        $this->audioSessions = new ArrayCollection();
55    }
56
57    public function getId(): ?int
58    {
59        return $this->id;
60    }
61
62    public function getEmail(): ?string
63    {
64        return $this->email;
65    }
66
67    public function setEmail(string $email): self
68    {
69        $this->email = $email;
70
71        return $this;
72    }
73
74    /**
75     * A visual identifier that represents this user.
76     *
77     * @see UserInterface
78     */
79    public function getUserIdentifier(): string
80    {
81        return (string) $this->email;
82    }
83
84    /**
85     * @see UserInterface
86     */
87    public function getRoles(): array
88    {
89        $roles = $this->roles;
90        // guarantee every user at least has ROLE_USER
91        $roles[] = 'ROLE_USER';
92
93        return array_unique($roles);
94    }
95
96    public function setRoles(array $roles): self
97    {
98        $this->roles = $roles;
99
100        return $this;
101    }
102
103    /**
104     * @see PasswordAuthenticatedUserInterface
105     */
106    public function getPassword(): string
107    {
108        return $this->password;
109    }
110
111    public function setPassword(string $password): self
112    {
113        $this->password = $password;
114
115        return $this;
116    }
117
118    public function isVerified(): bool
119    {
120        return $this->isVerified;
121    }
122
123    public function setIsVerified(bool $isVerified): self
124    {
125        $this->isVerified = $isVerified;
126
127        return $this;
128    }
129}
130

The code is correct which is also acknowledged by PHPStan as described here: https://phpstan.org/blog/detecting-unused-private-properties-methods-constants#what-if-my-code-is-%E2%80%9Cspecial%E2%80%9D%3F

So how can i solve these error message in PHPStan?

I tried installing https://github.com/phpstan/phpstan-doctrine and enabled this in my phpstan.neon file:

1Property App\Entity\User::$id is never written, only read.  
2<?php
3
4namespace App\Entity;
5
6use App\Repository\UserRepository;
7use Doctrine\Common\Collections\ArrayCollection;
8use Doctrine\Common\Collections\Collection;
9use Doctrine\ORM\Mapping as ORM;
10use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
11use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
12use Symfony\Component\Security\Core\User\UserInterface;
13
14/**
15 * @ORM\Table(name="`user`")
16 * @ORM\Entity(repositoryClass=UserRepository::class)
17 * @UniqueEntity(fields={"email"}, message="There is already an account with this email")
18 */
19class User implements UserInterface, PasswordAuthenticatedUserInterface
20{
21    public const ROLE_USER = 'ROLE_USER';
22    public const ROLE_ADMIN = 'ROLE_ADMIN';
23
24    /**
25     * @ORM\Id
26     * @ORM\GeneratedValue
27     * @ORM\Column(type="integer")
28     */
29    private $id;
30
31    /**
32     * @ORM\Column(type="string", length=180, unique=true)
33     */
34    private $email;
35
36    /**
37     * @ORM\Column(type="json")
38     */
39    private $roles = [];
40
41    /**
42     * @var string The hashed password
43     * @ORM\Column(type="string")
44     */
45    private $password;
46
47    /**
48     * @ORM\Column(type="boolean")
49     */
50    private $isVerified = false;
51
52    public function __construct()
53    {
54        $this->audioSessions = new ArrayCollection();
55    }
56
57    public function getId(): ?int
58    {
59        return $this->id;
60    }
61
62    public function getEmail(): ?string
63    {
64        return $this->email;
65    }
66
67    public function setEmail(string $email): self
68    {
69        $this->email = $email;
70
71        return $this;
72    }
73
74    /**
75     * A visual identifier that represents this user.
76     *
77     * @see UserInterface
78     */
79    public function getUserIdentifier(): string
80    {
81        return (string) $this->email;
82    }
83
84    /**
85     * @see UserInterface
86     */
87    public function getRoles(): array
88    {
89        $roles = $this->roles;
90        // guarantee every user at least has ROLE_USER
91        $roles[] = 'ROLE_USER';
92
93        return array_unique($roles);
94    }
95
96    public function setRoles(array $roles): self
97    {
98        $this->roles = $roles;
99
100        return $this;
101    }
102
103    /**
104     * @see PasswordAuthenticatedUserInterface
105     */
106    public function getPassword(): string
107    {
108        return $this->password;
109    }
110
111    public function setPassword(string $password): self
112    {
113        $this->password = $password;
114
115        return $this;
116    }
117
118    public function isVerified(): bool
119    {
120        return $this->isVerified;
121    }
122
123    public function setIsVerified(bool $isVerified): self
124    {
125        $this->isVerified = $isVerified;
126
127        return $this;
128    }
129}
130includes:
131    - vendor/phpstan/phpstan-doctrine/extension.neon
132    - vendor/phpstan/phpstan-doctrine/rules.neon
133

But the error still persists.

ANSWER

Answered 2021-Nov-23 at 09:55

You need to configure objectManagerLoader so that the extension can see the entity metadata. This will allow DQL validation, and the correct entity repositoryClass to be inferred when accessing $entityManager->getRepository(). Add to your phpstan.neon:

1Property App\Entity\User::$id is never written, only read.  
2<?php
3
4namespace App\Entity;
5
6use App\Repository\UserRepository;
7use Doctrine\Common\Collections\ArrayCollection;
8use Doctrine\Common\Collections\Collection;
9use Doctrine\ORM\Mapping as ORM;
10use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
11use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
12use Symfony\Component\Security\Core\User\UserInterface;
13
14/**
15 * @ORM\Table(name="`user`")
16 * @ORM\Entity(repositoryClass=UserRepository::class)
17 * @UniqueEntity(fields={"email"}, message="There is already an account with this email")
18 */
19class User implements UserInterface, PasswordAuthenticatedUserInterface
20{
21    public const ROLE_USER = 'ROLE_USER';
22    public const ROLE_ADMIN = 'ROLE_ADMIN';
23
24    /**
25     * @ORM\Id
26     * @ORM\GeneratedValue
27     * @ORM\Column(type="integer")
28     */
29    private $id;
30
31    /**
32     * @ORM\Column(type="string", length=180, unique=true)
33     */
34    private $email;
35
36    /**
37     * @ORM\Column(type="json")
38     */
39    private $roles = [];
40
41    /**
42     * @var string The hashed password
43     * @ORM\Column(type="string")
44     */
45    private $password;
46
47    /**
48     * @ORM\Column(type="boolean")
49     */
50    private $isVerified = false;
51
52    public function __construct()
53    {
54        $this->audioSessions = new ArrayCollection();
55    }
56
57    public function getId(): ?int
58    {
59        return $this->id;
60    }
61
62    public function getEmail(): ?string
63    {
64        return $this->email;
65    }
66
67    public function setEmail(string $email): self
68    {
69        $this->email = $email;
70
71        return $this;
72    }
73
74    /**
75     * A visual identifier that represents this user.
76     *
77     * @see UserInterface
78     */
79    public function getUserIdentifier(): string
80    {
81        return (string) $this->email;
82    }
83
84    /**
85     * @see UserInterface
86     */
87    public function getRoles(): array
88    {
89        $roles = $this->roles;
90        // guarantee every user at least has ROLE_USER
91        $roles[] = 'ROLE_USER';
92
93        return array_unique($roles);
94    }
95
96    public function setRoles(array $roles): self
97    {
98        $this->roles = $roles;
99
100        return $this;
101    }
102
103    /**
104     * @see PasswordAuthenticatedUserInterface
105     */
106    public function getPassword(): string
107    {
108        return $this->password;
109    }
110
111    public function setPassword(string $password): self
112    {
113        $this->password = $password;
114
115        return $this;
116    }
117
118    public function isVerified(): bool
119    {
120        return $this->isVerified;
121    }
122
123    public function setIsVerified(bool $isVerified): self
124    {
125        $this->isVerified = $isVerified;
126
127        return $this;
128    }
129}
130includes:
131    - vendor/phpstan/phpstan-doctrine/extension.neon
132    - vendor/phpstan/phpstan-doctrine/rules.neon
133parameters:
134    doctrine:
135        objectManagerLoader: tests/object-manager.php
136

Example for Symfony 5:

1Property App\Entity\User::$id is never written, only read.  
2<?php
3
4namespace App\Entity;
5
6use App\Repository\UserRepository;
7use Doctrine\Common\Collections\ArrayCollection;
8use Doctrine\Common\Collections\Collection;
9use Doctrine\ORM\Mapping as ORM;
10use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
11use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
12use Symfony\Component\Security\Core\User\UserInterface;
13
14/**
15 * @ORM\Table(name="`user`")
16 * @ORM\Entity(repositoryClass=UserRepository::class)
17 * @UniqueEntity(fields={"email"}, message="There is already an account with this email")
18 */
19class User implements UserInterface, PasswordAuthenticatedUserInterface
20{
21    public const ROLE_USER = 'ROLE_USER';
22    public const ROLE_ADMIN = 'ROLE_ADMIN';
23
24    /**
25     * @ORM\Id
26     * @ORM\GeneratedValue
27     * @ORM\Column(type="integer")
28     */
29    private $id;
30
31    /**
32     * @ORM\Column(type="string", length=180, unique=true)
33     */
34    private $email;
35
36    /**
37     * @ORM\Column(type="json")
38     */
39    private $roles = [];
40
41    /**
42     * @var string The hashed password
43     * @ORM\Column(type="string")
44     */
45    private $password;
46
47    /**
48     * @ORM\Column(type="boolean")
49     */
50    private $isVerified = false;
51
52    public function __construct()
53    {
54        $this->audioSessions = new ArrayCollection();
55    }
56
57    public function getId(): ?int
58    {
59        return $this->id;
60    }
61
62    public function getEmail(): ?string
63    {
64        return $this->email;
65    }
66
67    public function setEmail(string $email): self
68    {
69        $this->email = $email;
70
71        return $this;
72    }
73
74    /**
75     * A visual identifier that represents this user.
76     *
77     * @see UserInterface
78     */
79    public function getUserIdentifier(): string
80    {
81        return (string) $this->email;
82    }
83
84    /**
85     * @see UserInterface
86     */
87    public function getRoles(): array
88    {
89        $roles = $this->roles;
90        // guarantee every user at least has ROLE_USER
91        $roles[] = 'ROLE_USER';
92
93        return array_unique($roles);
94    }
95
96    public function setRoles(array $roles): self
97    {
98        $this->roles = $roles;
99
100        return $this;
101    }
102
103    /**
104     * @see PasswordAuthenticatedUserInterface
105     */
106    public function getPassword(): string
107    {
108        return $this->password;
109    }
110
111    public function setPassword(string $password): self
112    {
113        $this->password = $password;
114
115        return $this;
116    }
117
118    public function isVerified(): bool
119    {
120        return $this->isVerified;
121    }
122
123    public function setIsVerified(bool $isVerified): self
124    {
125        $this->isVerified = $isVerified;
126
127        return $this;
128    }
129}
130includes:
131    - vendor/phpstan/phpstan-doctrine/extension.neon
132    - vendor/phpstan/phpstan-doctrine/rules.neon
133parameters:
134    doctrine:
135        objectManagerLoader: tests/object-manager.php
136// tests/object-manager.php
137
138use App\Kernel;
139use Symfony\Component\Dotenv\Dotenv;
140
141require __DIR__ . '/../vendor/autoload.php';
142
143(new Dotenv())->bootEnv(__DIR__ . '/../.env');
144
145$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
146$kernel->boot();
147return $kernel->getContainer()->get('doctrine')->getManager();
148

Source https://stackoverflow.com/questions/69851516

QUESTION

Laravel 9 - laravel new command has error: Deprecated: Return type of Symfony\Component\Process\Process::getIterator(int $flags = 0)

Asked 2022-Feb-16 at 12:34

I want to try to install Laravel 9 for the first time... so, I update my PHP to the latest one (version 8.1.2) and composer to latest one also (version 2.2.6)...

and when i call laravel new my-project command, it shows error

1Deprecated: Return type of Symfony\Component\Process\Process::getIterator(int $flags = 0) should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\Users\LAPTOP-SYAMSOUL\AppData\Roaming\Composer\vendor\symfony\process\Process.php on line 620
2
3Deprecated: Return type of Symfony\Component\Console\Helper\HelperSet::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\Users\LAPTOP-SYAMSOUL\AppData\Roaming\Composer\vendor\symfony\console\Helper\HelperSet.php on line 94
4

how to solve this error?

ANSWER

Answered 2022-Feb-16 at 12:34

Sounds like you should run composer global update to update the packages that you've installed globally.

Source https://stackoverflow.com/questions/71141918

QUESTION

Localhost refused to connect on WSL2 when accessed via https://localhost:8000/ but works when using internal WSL IP adress

Asked 2022-Feb-02 at 19:40
What I'm Trying to Achieve

To access localhost from my local machine during the development of a Symfony web app.

My Environment
  • WSL2 running on Windows 10
  • Linux, Apache2, MySQL, PHP-7.4 stack (with Xdebug3 intalled)
  • Debian 10
  • Symfony 5.4 (although not sure on if relevant to this problem)
Steps I've Taken
1#!/bin/sh
2REMOTEIP=`cat /etc/resolv.conf | grep nameserver | sed 's/nameserver\s//'` 
3sed -i -E "s/client_host=[0-9\.]+/client_host=$REMOTEIP/g" /etc/php/7.4/mods-available/xdebug.ini
4service php7.4-fpm start
5service apache2 start
6service mysql start  
7
  • Run my Symfony project on the development server using symfony serve -d (Symfony then tells me "The Web server is using PHP FPM 7.4.23 https://127.0.0.1:8000")
  • Go to https://localhost:8000/ in Chrome where the app is running
What I Expect to Happen
  • My Symfony web app to be running on https://localhost:8000/ when I visit the URL in my Chrome browser
What Actually Happens
  • I get "This site can't be reached localhost refused to connect." in the Chrome browser
What I've Tried
  • This used to happen less frequently and I would give my laptop a restart, repeat the process above, and I could connect via https://localhost:8000/. However, it refuses to connect more regularly now (like 8/10 times I start up for the day)
  • Connecting to https://127.0.0.1:8000 yields the same result.
  • Connecting to the site using the internal WSL IP address, found using hostname -I and replacing localhost with this IP (still on port 8000). This is an adequate workaround to use my app, however I am unable to interact with my database via MySQL Workbench without having to set up a new connection, therefore a fix where I can use localhost would be very helpful!
  • (Based off comments) Only ran symfony serve -d without starting apache and PHP services separately - still sometimes allows connections to localhost but sometimes doesn't work.
Conclusion

The behaviour is odd as it works sometimes but other times it doesn't when the exact same steps are carried out. I am unsure where else to look for answers and I can't seem to find anything online with this same problem. Please let me know if any config files, etc would be helpful. Thank you so much for your help! :)

ANSWER

Answered 2021-Nov-11 at 11:03

Try to run command netstat -nltp. It shows active addresses and ports. Your nginx process should be run at 0.0.0.0:8000. 0.0.0.0 means the nginx process is available from anywhere.

If your nginx process is ran by any specific ip address, you should access it by that ip address, e.g http://192.168.4.2:8000.

Source https://stackoverflow.com/questions/69926941

QUESTION

How to handle Symfony 5.3 deprecations?

Asked 2022-Feb-02 at 11:23

After upgrading Symfony from 4.4 -> 5.3 i get some deprecations which I cant located to solve.

Here are 3 deprecations as example:

1User Deprecated: Since symfony/framework-bundle 5.3: The "session.storage.factory.service" service is deprecated, use "session.storage.factory.native", "session.storage.factory.php_bridge" or "session.storage.factory.mock_file" instead.
2User Deprecated: Since symfony/security-core 5.3: The "Symfony\Component\Security\Core\Event\AuthenticationFailureEvent" class is deprecated, use "Symfony\Component\Security\Http\Event\LoginFailureEvent"
3User Deprecated: Since symfony/http-kernel 5.3: "Symfony\Component\HttpKernel\Event\KernelEvent::isMasterRequest()" is deprecated, use "isMainRequest()" instead.
4

It's only 3 of more as 30 deprecations. My question is: How is the correct way to solve this warnings. (I need to solve, because I have many Requests/minute and every time this warnings get wrote in dev.log - this file is exploding)

I want to start with the 3rd warning. Here is the trace:

1User Deprecated: Since symfony/framework-bundle 5.3: The "session.storage.factory.service" service is deprecated, use "session.storage.factory.native", "session.storage.factory.php_bridge" or "session.storage.factory.mock_file" instead.
2User Deprecated: Since symfony/security-core 5.3: The "Symfony\Component\Security\Core\Event\AuthenticationFailureEvent" class is deprecated, use "Symfony\Component\Security\Http\Event\LoginFailureEvent"
3User Deprecated: Since symfony/http-kernel 5.3: "Symfony\Component\HttpKernel\Event\KernelEvent::isMasterRequest()" is deprecated, use "isMainRequest()" instead.
4../vendor/symfony/http-kernel/Event/KernelEvent.php:88 {▶}
5../vendor/symfony/web-link/EventListener/AddLinkHeaderListener.php:41 {▶}
6../vendor/symfony/event-dispatcher/Debug/WrappedListener.php:117 {▶}
7../vendor/symfony/event-dispatcher/EventDispatcher.php:230 {▶}
8../vendor/symfony/event-dispatcher/EventDispatcher.php:59 {▶}
9../vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php:151 {▶}
10../vendor/symfony/http-kernel/HttpKernel.php:190 {▶}
11../vendor/symfony/http-kernel/HttpKernel.php:178 {▶}
12../vendor/symfony/http-kernel/HttpKernel.php:79 {▶}
13../vendor/symfony/http-kernel/EventListener/ErrorListener.php:60 {▶}
14../vendor/symfony/event-dispatcher/Debug/WrappedListener.php:117 {▶}
15../vendor/symfony/event-dispatcher/EventDispatcher.php:230 {▶}
16../vendor/symfony/event-dispatcher/EventDispatcher.php:59 {▶}
17../vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php:151 {▶}
18../vendor/symfony/http-kernel/HttpKernel.php:218 {▶}
19../vendor/symfony/http-kernel/HttpKernel.php:90 {▶}
20../vendor/symfony/http-kernel/Kernel.php:199 {▶}
21../public/index.php:25 {▶}
22

All files comes directly from symfony, nothing from me, thats why my question where to start to solve this warnings.

ANSWER

Answered 2022-Feb-02 at 11:23

Ok, now im deprecation free but there are some things to now after upgrading from 4.4 to 5.3

To find all warnings I created a new symfony project to compare different files

  1. KernelEvent::isMasterRequest()" is deprecated, use "isMainRequest()

    take a look into your file src/Kernel.php - there u can find the deprecated method

  2. The "session.storage.factory.service" service is deprecated

    open your framework.yaml and compare with the following code. Maybe it could help you:

1User Deprecated: Since symfony/framework-bundle 5.3: The "session.storage.factory.service" service is deprecated, use "session.storage.factory.native", "session.storage.factory.php_bridge" or "session.storage.factory.mock_file" instead.
2User Deprecated: Since symfony/security-core 5.3: The "Symfony\Component\Security\Core\Event\AuthenticationFailureEvent" class is deprecated, use "Symfony\Component\Security\Http\Event\LoginFailureEvent"
3User Deprecated: Since symfony/http-kernel 5.3: "Symfony\Component\HttpKernel\Event\KernelEvent::isMasterRequest()" is deprecated, use "isMainRequest()" instead.
4../vendor/symfony/http-kernel/Event/KernelEvent.php:88 {▶}
5../vendor/symfony/web-link/EventListener/AddLinkHeaderListener.php:41 {▶}
6../vendor/symfony/event-dispatcher/Debug/WrappedListener.php:117 {▶}
7../vendor/symfony/event-dispatcher/EventDispatcher.php:230 {▶}
8../vendor/symfony/event-dispatcher/EventDispatcher.php:59 {▶}
9../vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php:151 {▶}
10../vendor/symfony/http-kernel/HttpKernel.php:190 {▶}
11../vendor/symfony/http-kernel/HttpKernel.php:178 {▶}
12../vendor/symfony/http-kernel/HttpKernel.php:79 {▶}
13../vendor/symfony/http-kernel/EventListener/ErrorListener.php:60 {▶}
14../vendor/symfony/event-dispatcher/Debug/WrappedListener.php:117 {▶}
15../vendor/symfony/event-dispatcher/EventDispatcher.php:230 {▶}
16../vendor/symfony/event-dispatcher/EventDispatcher.php:59 {▶}
17../vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php:151 {▶}
18../vendor/symfony/http-kernel/HttpKernel.php:218 {▶}
19../vendor/symfony/http-kernel/HttpKernel.php:90 {▶}
20../vendor/symfony/http-kernel/Kernel.php:199 {▶}
21../public/index.php:25 {▶}
22session:
23  handler_id: session.handler.native_file
24  save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
25  # 2 Days lifetime (172800 seconds)
26  cookie_lifetime: 172800
27  cookie_secure: 'auto'
28  cookie_samesite: 'lax'
29  #storage_id: session.storage.mock_file
30  storage_factory_id: session.storage.factory.native  
31
  • The "Symfony\Component\HttpFoundation\Session\SessionInterface are deprecated

    I found this in my old LoginAuthenticator ('App\Security...' by default). Replace it with use Symfony\Component\HttpFoundation\RequestStack; Now u can inject it and make it available as $this->requestStack and then change all $this->session with $this->requestStack->getSession() Done!

  • Most of all other deprecations are in connection with the new authenticator-based system which was introduced in symfony 5.1. U have to edit your security.yaml. I show you my changes:

  • 1User Deprecated: Since symfony/framework-bundle 5.3: The "session.storage.factory.service" service is deprecated, use "session.storage.factory.native", "session.storage.factory.php_bridge" or "session.storage.factory.mock_file" instead.
    2User Deprecated: Since symfony/security-core 5.3: The "Symfony\Component\Security\Core\Event\AuthenticationFailureEvent" class is deprecated, use "Symfony\Component\Security\Http\Event\LoginFailureEvent"
    3User Deprecated: Since symfony/http-kernel 5.3: "Symfony\Component\HttpKernel\Event\KernelEvent::isMasterRequest()" is deprecated, use "isMainRequest()" instead.
    4../vendor/symfony/http-kernel/Event/KernelEvent.php:88 {▶}
    5../vendor/symfony/web-link/EventListener/AddLinkHeaderListener.php:41 {▶}
    6../vendor/symfony/event-dispatcher/Debug/WrappedListener.php:117 {▶}
    7../vendor/symfony/event-dispatcher/EventDispatcher.php:230 {▶}
    8../vendor/symfony/event-dispatcher/EventDispatcher.php:59 {▶}
    9../vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php:151 {▶}
    10../vendor/symfony/http-kernel/HttpKernel.php:190 {▶}
    11../vendor/symfony/http-kernel/HttpKernel.php:178 {▶}
    12../vendor/symfony/http-kernel/HttpKernel.php:79 {▶}
    13../vendor/symfony/http-kernel/EventListener/ErrorListener.php:60 {▶}
    14../vendor/symfony/event-dispatcher/Debug/WrappedListener.php:117 {▶}
    15../vendor/symfony/event-dispatcher/EventDispatcher.php:230 {▶}
    16../vendor/symfony/event-dispatcher/EventDispatcher.php:59 {▶}
    17../vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php:151 {▶}
    18../vendor/symfony/http-kernel/HttpKernel.php:218 {▶}
    19../vendor/symfony/http-kernel/HttpKernel.php:90 {▶}
    20../vendor/symfony/http-kernel/Kernel.php:199 {▶}
    21../public/index.php:25 {▶}
    22session:
    23  handler_id: session.handler.native_file
    24  save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
    25  # 2 Days lifetime (172800 seconds)
    26  cookie_lifetime: 172800
    27  cookie_secure: 'auto'
    28  cookie_samesite: 'lax'
    29  #storage_id: session.storage.mock_file
    30  storage_factory_id: session.storage.factory.native  
    31security:
    32    enable_authenticator_manager: true
    33    password_hashers:
    34       Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
    35    providers:
    36        users_in_memory: { memory: null }
    37        app_user_provider:
    38           entity:
    39             class: App\Entity\User
    40             property: username
    41    firewalls:
    42        main: 
    43            # default stuff
    44            provider: app_user_provider
    45            http_basic: ~
    46            form_login:
    47                default_target_path: mission 
    48                use_referer: true
    49                target_path_parameter: redirect_url
    50                login_path: login
    51                check_path: login
    52            entry_point: form_login
    53            access_denied_handler: App\Security\AccessDeniedHandler
    54            custom_authenticator: App\Security\CustomAuthenticator
    55

    To make the auth warnings more understandable create a new CustomAuthenticator with the maker bundle. Now you can compare your old Authenticator with the new one and put the new methods into your old Authenticator. There are some changes that you need to make.

    Thats it. Most of deprecations should solve now.

    Source https://stackoverflow.com/questions/68870687

    QUESTION

    How to Validate huge data using LazyCollection Laravel

    Asked 2022-Jan-27 at 17:25

    I'm trying to validate huge amount of data using Laravel LazyCollection, I test the code with 15 thousands rows each contains 9 columns to be validated.

    The scenario is user upload the excel file, then convert it to array, after that the validation of data begins

    The Controller :

    1class ImportBudget extends Controller
    2{
    3    use SpreadsheetTrait;
    4
    5    public function import(Request $request) 
    6    {
    7        // File format validation
    8        $validatedFile = SpreadsheetTrait::fileHandler($request);
    9        
    10        if (!is_array($validatedFile)) return $validatedFile;
    11
    12        $messages = [
    13            'required' => 'This field is required, please input.',
    14            'numeric' => 'Please input number value only.',
    15            'integer' => 'Please input integer value only.',
    16            'min' => 'Minimal input value is :min.',
    17            'required_if' => 'This field is required, please input.',
    18        ];
    19        
    20        // Cars data which contain 30k++ of arrays
    21        $car = Cache::get('car')->pluck('slug')->toArray();
    22
    23        // Start Data Validation
    24        $validatedData = LazyCollection::make(function () use($validatedFile) {
    25            $data = collect($validatedFile);
    26            yield $data;
    27        })->chunk(1000)->each(function ($rows) use ($car, $messages) {
    28            return Validator::make($rows->toArray(), [
    29                '*.0' => ['required', function ($attribute, $value, $fail) {
    30                    if (!in_array($value , config('constants.purposes'))) {
    31                        $fail('The purpose field is invalid.');
    32                    }
    33                }],
    34                '*.1' => 'required_if:*.0,PRODUCTION-PROJECT',
    35                '*.2' => 'required',
    36                '*.3' => 'required',
    37                '*.4' => 'required',
    38                '*.5' => 'required',
    39                '*.6' => 'required',
    40                '*.7' => ['required', function ($attribute, $value, $fail) use($car) {
    41                    if (!in_array($value, $curr)) {
    42                        $fail('The car is invalid.');
    43                    }
    44                }],
    45                '*.8' => 'required|numeric|min:0',
    46                '*.9' => 'required|integer|min:1',
    47            ], $messages);
    48        });
    49    }
    50}
    51

    The code above resulting error max executing times :

    1class ImportBudget extends Controller
    2{
    3    use SpreadsheetTrait;
    4
    5    public function import(Request $request) 
    6    {
    7        // File format validation
    8        $validatedFile = SpreadsheetTrait::fileHandler($request);
    9        
    10        if (!is_array($validatedFile)) return $validatedFile;
    11
    12        $messages = [
    13            'required' => 'This field is required, please input.',
    14            'numeric' => 'Please input number value only.',
    15            'integer' => 'Please input integer value only.',
    16            'min' => 'Minimal input value is :min.',
    17            'required_if' => 'This field is required, please input.',
    18        ];
    19        
    20        // Cars data which contain 30k++ of arrays
    21        $car = Cache::get('car')->pluck('slug')->toArray();
    22
    23        // Start Data Validation
    24        $validatedData = LazyCollection::make(function () use($validatedFile) {
    25            $data = collect($validatedFile);
    26            yield $data;
    27        })->chunk(1000)->each(function ($rows) use ($car, $messages) {
    28            return Validator::make($rows->toArray(), [
    29                '*.0' => ['required', function ($attribute, $value, $fail) {
    30                    if (!in_array($value , config('constants.purposes'))) {
    31                        $fail('The purpose field is invalid.');
    32                    }
    33                }],
    34                '*.1' => 'required_if:*.0,PRODUCTION-PROJECT',
    35                '*.2' => 'required',
    36                '*.3' => 'required',
    37                '*.4' => 'required',
    38                '*.5' => 'required',
    39                '*.6' => 'required',
    40                '*.7' => ['required', function ($attribute, $value, $fail) use($car) {
    41                    if (!in_array($value, $curr)) {
    42                        $fail('The car is invalid.');
    43                    }
    44                }],
    45                '*.8' => 'required|numeric|min:0',
    46                '*.9' => 'required|integer|min:1',
    47            ], $messages);
    48        });
    49    }
    50}
    51{
    52    "message": "Maximum execution time of 60 seconds exceeded",
    53    "exception": "Symfony\\Component\\ErrorHandler\\Error\\FatalError",
    54    "file": "C:\\laragon\\www\\bulus-jai\\vendor\\laravel\\framework\\src\\Illuminate\\Collections\\Arr.php",
    55    "line": 115,
    56    "trace": []
    57}
    58

    Even i add the execution time to 120, the result remain the same

    Note that the $car variable contains 30k++ arrays, i think this also make this validation slower aswell, but i don't have any idea how to make it more simpler.

    What is the best solution for this ?

    Update 1

    I tried to switch using my own validation script by create the services , and the result is pretty good (around 5 ~ 10 seconds for 15k rows) :

    1class ImportBudget extends Controller
    2{
    3    use SpreadsheetTrait;
    4
    5    public function import(Request $request) 
    6    {
    7        // File format validation
    8        $validatedFile = SpreadsheetTrait::fileHandler($request);
    9        
    10        if (!is_array($validatedFile)) return $validatedFile;
    11
    12        $messages = [
    13            'required' => 'This field is required, please input.',
    14            'numeric' => 'Please input number value only.',
    15            'integer' => 'Please input integer value only.',
    16            'min' => 'Minimal input value is :min.',
    17            'required_if' => 'This field is required, please input.',
    18        ];
    19        
    20        // Cars data which contain 30k++ of arrays
    21        $car = Cache::get('car')->pluck('slug')->toArray();
    22
    23        // Start Data Validation
    24        $validatedData = LazyCollection::make(function () use($validatedFile) {
    25            $data = collect($validatedFile);
    26            yield $data;
    27        })->chunk(1000)->each(function ($rows) use ($car, $messages) {
    28            return Validator::make($rows->toArray(), [
    29                '*.0' => ['required', function ($attribute, $value, $fail) {
    30                    if (!in_array($value , config('constants.purposes'))) {
    31                        $fail('The purpose field is invalid.');
    32                    }
    33                }],
    34                '*.1' => 'required_if:*.0,PRODUCTION-PROJECT',
    35                '*.2' => 'required',
    36                '*.3' => 'required',
    37                '*.4' => 'required',
    38                '*.5' => 'required',
    39                '*.6' => 'required',
    40                '*.7' => ['required', function ($attribute, $value, $fail) use($car) {
    41                    if (!in_array($value, $curr)) {
    42                        $fail('The car is invalid.');
    43                    }
    44                }],
    45                '*.8' => 'required|numeric|min:0',
    46                '*.9' => 'required|integer|min:1',
    47            ], $messages);
    48        });
    49    }
    50}
    51{
    52    "message": "Maximum execution time of 60 seconds exceeded",
    53    "exception": "Symfony\\Component\\ErrorHandler\\Error\\FatalError",
    54    "file": "C:\\laragon\\www\\bulus-jai\\vendor\\laravel\\framework\\src\\Illuminate\\Collections\\Arr.php",
    55    "line": 115,
    56    "trace": []
    57}
    58
    59class BatchValidationServices {
    60
    61    public static function budgetValidation($validatedFile)
    62    {
    63        $requiredFields = [
    64            0 => true,
    65            1 => false,
    66            2 => true,
    67            3 => true,
    68            4 => true,
    69            5 => true,
    70            6 => true,
    71            7 => true,
    72            8 => true,
    73            9 => true,
    74            10 => false
    75        ];
    76
    77        $curr = collect(Cache::get('curr'))
    78            ->where('term.status','BUDGETING')
    79            ->pluck('name')
    80            ->toArray();
    81        $item = Cache::get('item')->pluck('item_code')->toArray();
    82        $car = Cache::get('car')->pluck('slug')->toArray();
    83        $deliveryPlan = Cache::get('delivery');
    84        $orderPlan = Cache::get('order');
    85
    86        $collectedData = LazyCollection::make(function () use($validatedFile) {
    87            $data = collect($validatedFile);
    88            yield $data;
    89        }); 
    90
    91        $errors = [];
    92
    93        $collectedData->chunk(1000)
    94            ->each(function ($collection)  use (
    95                $orderPlan,
    96                $deliveryPlan,
    97                $car,
    98                $curr,
    99                $item,
    100                $requiredFields, &$errors){
    101                foreach ($collection->toArray() as $array) {
    102                    foreach ($array as $key => $row) {
    103    
    104                        // Validate blank rows
    105                        for ($i=0; $i < count($requiredFields); $i++) {
    106                            if ($row[$i] === null &&
    107                            $requiredFields[$i] === true) {
    108                                array_push($errors, [$key.'.'.$i => 'This field is required.']);
    109                            }
    110                        }
    111    
    112                        // Validate purpose validity
    113                        if (!in_array($row[0], config('constants.purposes'))) array_push($errors, [$key.'.0' => 'Purpose is invalid.']);
    114    
    115                        // Validate required preparation item
    116                        $preparationItems = array_column(config('constants.preparations'), 'item');
    117    
    118                        if ($row[0] === 'PRODUCTION-PROJECT' && $row[1] === null) {
    119                            array_push($errors, [$key.'.1' => 'This field is required if the purpose is PRODUCTION-PROJECT.']);  
    120                        } elseif ($row[0] === 'PRODUCTION-PROJECT' && $row[1] !== null) {
    121                            if (!in_array($row[1], $preparationItems)) array_push($errors, [$key.'.1' => 'Production preparation item is invalid.']);
    122                        }
    123    
    124                        // Validate order plan & delivery plan 
    125                        if (!in_array($row[2], $orderPlan)) array_push($errors, [$key.'.2' => 'Order plan is invalid.']);
    126                        
    127                        if (!in_array($row[3], $deliveryPlan)) {
    128                            array_push($errors, [$key.'.3' => 'Delivery plan is invalid.']);
    129                        } else {
    130                            if ($row[3] < $row[2]) array_push($errors, [$key.'.3' => 'Delivery plan should be after or at least in the same period as order plan.']);
    131                        }
    132                        
    133                        // Validate destination-carline
    134                        if (!in_array($row[4], $car)) array_push($errors, [$key.'.4' => 'Destination-carline is invalid.']);
    135
    136                        // Validate Origin
    137                        if (!in_array($row[5], ['DOMESTIC', 'IMPORT'])) array_push($errors, [$key.'.5' => 'Origin supplier is invalid, please choose between DOMESTIC or IMPORT only.']);
    138
    139                        // Validate Item
    140                        if(!in_array($row[6], $item)) array_push($errors, [$key.'.6' => 'Item code is invalid.']);
    141
    142                        // Validate Currency
    143                        if (!in_array($row[7], $curr)) {
    144                            array_push($errors, [$key.'.7' => 'Currency is invalid.']);
    145                        } else {
    146                            if ($row[5] === 'IMPORT' && $row[7] === 'IDR') array_push($errors, [$key.'.7' => 'IDR currency shouldn\'t be used for IMPORT.']);
    147                        }
    148
    149                        // Validate Price
    150                        if (!is_numeric($row[8])) {
    151                            array_push($errors, [$key.'.8' => 'Please only input numerical value.']);
    152                        } else {
    153                            if ($row[8] <= 0) array_push($errors, [$key.'.8' => 'Value must be greater than 0.']);
    154                        }
    155
    156                        // Validate Qty
    157                        if (!is_integer($row[9])) {
    158                            array_push($errors, [$key.'.9' => 'Please only input numerical value.']);
    159                        } else {
    160                            if ($row[9] <= 0) array_push($errors, [$key.'.9' => 'Value must be greater than 0.']);
    161                        }
    162                    }
    163                }
    164
    165                return $errors;
    166            });
    167
    168        if (count($errors) > 0) {
    169            return $errors;
    170        } else {
    171            return true;
    172        }
    173    }
    174}
    175

    However I am still wondering why, when i use the built in Laravel validation, it's taking so long? I'd prefer using the Laravel validation because the code is more readable.

    ANSWER

    Answered 2022-Jan-27 at 17:25

    Since you have already loaded the entire contents of the spreadsheet into the $validatedFile variable, why make a LazyCollection object? Their only purpose is to save memory by not loading large data sets into memory. Your validation rules using closures can also be cleaned up. This isn't just a cosmetic change: in_array() is notoriously slow.

    1class ImportBudget extends Controller
    2{
    3    use SpreadsheetTrait;
    4
    5    public function import(Request $request) 
    6    {
    7        // File format validation
    8        $validatedFile = SpreadsheetTrait::fileHandler($request);
    9        
    10        if (!is_array($validatedFile)) return $validatedFile;
    11
    12        $messages = [
    13            'required' => 'This field is required, please input.',
    14            'numeric' => 'Please input number value only.',
    15            'integer' => 'Please input integer value only.',
    16            'min' => 'Minimal input value is :min.',
    17            'required_if' => 'This field is required, please input.',
    18        ];
    19        
    20        // Cars data which contain 30k++ of arrays
    21        $car = Cache::get('car')->pluck('slug')->toArray();
    22
    23        // Start Data Validation
    24        $validatedData = LazyCollection::make(function () use($validatedFile) {
    25            $data = collect($validatedFile);
    26            yield $data;
    27        })->chunk(1000)->each(function ($rows) use ($car, $messages) {
    28            return Validator::make($rows->toArray(), [
    29                '*.0' => ['required', function ($attribute, $value, $fail) {
    30                    if (!in_array($value , config('constants.purposes'))) {
    31                        $fail('The purpose field is invalid.');
    32                    }
    33                }],
    34                '*.1' => 'required_if:*.0,PRODUCTION-PROJECT',
    35                '*.2' => 'required',
    36                '*.3' => 'required',
    37                '*.4' => 'required',
    38                '*.5' => 'required',
    39                '*.6' => 'required',
    40                '*.7' => ['required', function ($attribute, $value, $fail) use($car) {
    41                    if (!in_array($value, $curr)) {
    42                        $fail('The car is invalid.');
    43                    }
    44                }],
    45                '*.8' => 'required|numeric|min:0',
    46                '*.9' => 'required|integer|min:1',
    47            ], $messages);
    48        });
    49    }
    50}
    51{
    52    "message": "Maximum execution time of 60 seconds exceeded",
    53    "exception": "Symfony\\Component\\ErrorHandler\\Error\\FatalError",
    54    "file": "C:\\laragon\\www\\bulus-jai\\vendor\\laravel\\framework\\src\\Illuminate\\Collections\\Arr.php",
    55    "line": 115,
    56    "trace": []
    57}
    58
    59class BatchValidationServices {
    60
    61    public static function budgetValidation($validatedFile)
    62    {
    63        $requiredFields = [
    64            0 => true,
    65            1 => false,
    66            2 => true,
    67            3 => true,
    68            4 => true,
    69            5 => true,
    70            6 => true,
    71            7 => true,
    72            8 => true,
    73            9 => true,
    74            10 => false
    75        ];
    76
    77        $curr = collect(Cache::get('curr'))
    78            ->where('term.status','BUDGETING')
    79            ->pluck('name')
    80            ->toArray();
    81        $item = Cache::get('item')->pluck('item_code')->toArray();
    82        $car = Cache::get('car')->pluck('slug')->toArray();
    83        $deliveryPlan = Cache::get('delivery');
    84        $orderPlan = Cache::get('order');
    85
    86        $collectedData = LazyCollection::make(function () use($validatedFile) {
    87            $data = collect($validatedFile);
    88            yield $data;
    89        }); 
    90
    91        $errors = [];
    92
    93        $collectedData->chunk(1000)
    94            ->each(function ($collection)  use (
    95                $orderPlan,
    96                $deliveryPlan,
    97                $car,
    98                $curr,
    99                $item,
    100                $requiredFields, &$errors){
    101                foreach ($collection->toArray() as $array) {
    102                    foreach ($array as $key => $row) {
    103    
    104                        // Validate blank rows
    105                        for ($i=0; $i < count($requiredFields); $i++) {
    106                            if ($row[$i] === null &&
    107                            $requiredFields[$i] === true) {
    108                                array_push($errors, [$key.'.'.$i => 'This field is required.']);
    109                            }
    110                        }
    111    
    112                        // Validate purpose validity
    113                        if (!in_array($row[0], config('constants.purposes'))) array_push($errors, [$key.'.0' => 'Purpose is invalid.']);
    114    
    115                        // Validate required preparation item
    116                        $preparationItems = array_column(config('constants.preparations'), 'item');
    117    
    118                        if ($row[0] === 'PRODUCTION-PROJECT' && $row[1] === null) {
    119                            array_push($errors, [$key.'.1' => 'This field is required if the purpose is PRODUCTION-PROJECT.']);  
    120                        } elseif ($row[0] === 'PRODUCTION-PROJECT' && $row[1] !== null) {
    121                            if (!in_array($row[1], $preparationItems)) array_push($errors, [$key.'.1' => 'Production preparation item is invalid.']);
    122                        }
    123    
    124                        // Validate order plan & delivery plan 
    125                        if (!in_array($row[2], $orderPlan)) array_push($errors, [$key.'.2' => 'Order plan is invalid.']);
    126                        
    127                        if (!in_array($row[3], $deliveryPlan)) {
    128                            array_push($errors, [$key.'.3' => 'Delivery plan is invalid.']);
    129                        } else {
    130                            if ($row[3] < $row[2]) array_push($errors, [$key.'.3' => 'Delivery plan should be after or at least in the same period as order plan.']);
    131                        }
    132                        
    133                        // Validate destination-carline
    134                        if (!in_array($row[4], $car)) array_push($errors, [$key.'.4' => 'Destination-carline is invalid.']);
    135
    136                        // Validate Origin
    137                        if (!in_array($row[5], ['DOMESTIC', 'IMPORT'])) array_push($errors, [$key.'.5' => 'Origin supplier is invalid, please choose between DOMESTIC or IMPORT only.']);
    138
    139                        // Validate Item
    140                        if(!in_array($row[6], $item)) array_push($errors, [$key.'.6' => 'Item code is invalid.']);
    141
    142                        // Validate Currency
    143                        if (!in_array($row[7], $curr)) {
    144                            array_push($errors, [$key.'.7' => 'Currency is invalid.']);
    145                        } else {
    146                            if ($row[5] === 'IMPORT' && $row[7] === 'IDR') array_push($errors, [$key.'.7' => 'IDR currency shouldn\'t be used for IMPORT.']);
    147                        }
    148
    149                        // Validate Price
    150                        if (!is_numeric($row[8])) {
    151                            array_push($errors, [$key.'.8' => 'Please only input numerical value.']);
    152                        } else {
    153                            if ($row[8] <= 0) array_push($errors, [$key.'.8' => 'Value must be greater than 0.']);
    154                        }
    155
    156                        // Validate Qty
    157                        if (!is_integer($row[9])) {
    158                            array_push($errors, [$key.'.9' => 'Please only input numerical value.']);
    159                        } else {
    160                            if ($row[9] <= 0) array_push($errors, [$key.'.9' => 'Value must be greater than 0.']);
    161                        }
    162                    }
    163                }
    164
    165                return $errors;
    166            });
    167
    168        if (count($errors) > 0) {
    169            return $errors;
    170        } else {
    171            return true;
    172        }
    173    }
    174}
    175class ImportBudget extends Controller
    176{
    177    use SpreadsheetTrait;
    178
    179    public function import(Request $request) 
    180    {
    181        // File format validation
    182        $validatedFile = SpreadsheetTrait::fileHandler($request);
    183        
    184        if (!is_array($validatedFile)) {
    185            // this should be throwing an exception of some kind
    186            return $validatedFile;
    187        }
    188
    189        $purposes = config('constants.purposes');
    190
    191        // Cars data which contain 30k++ of arrays
    192        $car = Cache::get('car')->pluck('slug');
    193
    194        $rules = [
    195            '*.0' => ['required', Rule::in($purposes)],
    196            '*.1' => ['required_if:*.0,PRODUCTION-PROJECT'],
    197            '*.2' => ['required'],
    198            '*.3' => ['required'],
    199            '*.4' => ['required'],
    200            '*.5' => ['required'],
    201            '*.6' => ['required'],
    202            '*.7' => ['required', Rule::in($car)],
    203            '*.8' => ['required', 'numeric', 'min:0'],
    204            '*.9' => ['required', 'integer', 'min:1'],
    205        ];
    206
    207        $messages = [
    208            'required' => 'This field is required, please input.',
    209            'numeric' => 'Please input number value only.',
    210            'integer' => 'Please input integer value only.',
    211            'min' => 'Minimal input value is :min.',
    212            'required_if' => 'This field is required, please input.',
    213        ];
    214
    215        // Start Data Validation
    216        $validatedData = Validator::make($validatedFile, $rules, $messages));
    217    }
    218}
    219

    If slug is guaranteed to be unique, speed could be improved by using it as the index of the array:

    1class ImportBudget extends Controller
    2{
    3    use SpreadsheetTrait;
    4
    5    public function import(Request $request) 
    6    {
    7        // File format validation
    8        $validatedFile = SpreadsheetTrait::fileHandler($request);
    9        
    10        if (!is_array($validatedFile)) return $validatedFile;
    11
    12        $messages = [
    13            'required' => 'This field is required, please input.',
    14            'numeric' => 'Please input number value only.',
    15            'integer' => 'Please input integer value only.',
    16            'min' => 'Minimal input value is :min.',
    17            'required_if' => 'This field is required, please input.',
    18        ];
    19        
    20        // Cars data which contain 30k++ of arrays
    21        $car = Cache::get('car')->pluck('slug')->toArray();
    22
    23        // Start Data Validation
    24        $validatedData = LazyCollection::make(function () use($validatedFile) {
    25            $data = collect($validatedFile);
    26            yield $data;
    27        })->chunk(1000)->each(function ($rows) use ($car, $messages) {
    28            return Validator::make($rows->toArray(), [
    29                '*.0' => ['required', function ($attribute, $value, $fail) {
    30                    if (!in_array($value , config('constants.purposes'))) {
    31                        $fail('The purpose field is invalid.');
    32                    }
    33                }],
    34                '*.1' => 'required_if:*.0,PRODUCTION-PROJECT',
    35                '*.2' => 'required',
    36                '*.3' => 'required',
    37                '*.4' => 'required',
    38                '*.5' => 'required',
    39                '*.6' => 'required',
    40                '*.7' => ['required', function ($attribute, $value, $fail) use($car) {
    41                    if (!in_array($value, $curr)) {
    42                        $fail('The car is invalid.');
    43                    }
    44                }],
    45                '*.8' => 'required|numeric|min:0',
    46                '*.9' => 'required|integer|min:1',
    47            ], $messages);
    48        });
    49    }
    50}
    51{
    52    "message": "Maximum execution time of 60 seconds exceeded",
    53    "exception": "Symfony\\Component\\ErrorHandler\\Error\\FatalError",
    54    "file": "C:\\laragon\\www\\bulus-jai\\vendor\\laravel\\framework\\src\\Illuminate\\Collections\\Arr.php",
    55    "line": 115,
    56    "trace": []
    57}
    58
    59class BatchValidationServices {
    60
    61    public static function budgetValidation($validatedFile)
    62    {
    63        $requiredFields = [
    64            0 => true,
    65            1 => false,
    66            2 => true,
    67            3 => true,
    68            4 => true,
    69            5 => true,
    70            6 => true,
    71            7 => true,
    72            8 => true,
    73            9 => true,
    74            10 => false
    75        ];
    76
    77        $curr = collect(Cache::get('curr'))
    78            ->where('term.status','BUDGETING')
    79            ->pluck('name')
    80            ->toArray();
    81        $item = Cache::get('item')->pluck('item_code')->toArray();
    82        $car = Cache::get('car')->pluck('slug')->toArray();
    83        $deliveryPlan = Cache::get('delivery');
    84        $orderPlan = Cache::get('order');
    85
    86        $collectedData = LazyCollection::make(function () use($validatedFile) {
    87            $data = collect($validatedFile);
    88            yield $data;
    89        }); 
    90
    91        $errors = [];
    92
    93        $collectedData->chunk(1000)
    94            ->each(function ($collection)  use (
    95                $orderPlan,
    96                $deliveryPlan,
    97                $car,
    98                $curr,
    99                $item,
    100                $requiredFields, &$errors){
    101                foreach ($collection->toArray() as $array) {
    102                    foreach ($array as $key => $row) {
    103    
    104                        // Validate blank rows
    105                        for ($i=0; $i < count($requiredFields); $i++) {
    106                            if ($row[$i] === null &&
    107                            $requiredFields[$i] === true) {
    108                                array_push($errors, [$key.'.'.$i => 'This field is required.']);
    109                            }
    110                        }
    111    
    112                        // Validate purpose validity
    113                        if (!in_array($row[0], config('constants.purposes'))) array_push($errors, [$key.'.0' => 'Purpose is invalid.']);
    114    
    115                        // Validate required preparation item
    116                        $preparationItems = array_column(config('constants.preparations'), 'item');
    117    
    118                        if ($row[0] === 'PRODUCTION-PROJECT' && $row[1] === null) {
    119                            array_push($errors, [$key.'.1' => 'This field is required if the purpose is PRODUCTION-PROJECT.']);  
    120                        } elseif ($row[0] === 'PRODUCTION-PROJECT' && $row[1] !== null) {
    121                            if (!in_array($row[1], $preparationItems)) array_push($errors, [$key.'.1' => 'Production preparation item is invalid.']);
    122                        }
    123    
    124                        // Validate order plan & delivery plan 
    125                        if (!in_array($row[2], $orderPlan)) array_push($errors, [$key.'.2' => 'Order plan is invalid.']);
    126                        
    127                        if (!in_array($row[3], $deliveryPlan)) {
    128                            array_push($errors, [$key.'.3' => 'Delivery plan is invalid.']);
    129                        } else {
    130                            if ($row[3] < $row[2]) array_push($errors, [$key.'.3' => 'Delivery plan should be after or at least in the same period as order plan.']);
    131                        }
    132                        
    133                        // Validate destination-carline
    134                        if (!in_array($row[4], $car)) array_push($errors, [$key.'.4' => 'Destination-carline is invalid.']);
    135
    136                        // Validate Origin
    137                        if (!in_array($row[5], ['DOMESTIC', 'IMPORT'])) array_push($errors, [$key.'.5' => 'Origin supplier is invalid, please choose between DOMESTIC or IMPORT only.']);
    138
    139                        // Validate Item
    140                        if(!in_array($row[6], $item)) array_push($errors, [$key.'.6' => 'Item code is invalid.']);
    141
    142                        // Validate Currency
    143                        if (!in_array($row[7], $curr)) {
    144                            array_push($errors, [$key.'.7' => 'Currency is invalid.']);
    145                        } else {
    146                            if ($row[5] === 'IMPORT' && $row[7] === 'IDR') array_push($errors, [$key.'.7' => 'IDR currency shouldn\'t be used for IMPORT.']);
    147                        }
    148
    149                        // Validate Price
    150                        if (!is_numeric($row[8])) {
    151                            array_push($errors, [$key.'.8' => 'Please only input numerical value.']);
    152                        } else {
    153                            if ($row[8] <= 0) array_push($errors, [$key.'.8' => 'Value must be greater than 0.']);
    154                        }
    155
    156                        // Validate Qty
    157                        if (!is_integer($row[9])) {
    158                            array_push($errors, [$key.'.9' => 'Please only input numerical value.']);
    159                        } else {
    160                            if ($row[9] <= 0) array_push($errors, [$key.'.9' => 'Value must be greater than 0.']);
    161                        }
    162                    }
    163                }
    164
    165                return $errors;
    166            });
    167
    168        if (count($errors) > 0) {
    169            return $errors;
    170        } else {
    171            return true;
    172        }
    173    }
    174}
    175class ImportBudget extends Controller
    176{
    177    use SpreadsheetTrait;
    178
    179    public function import(Request $request) 
    180    {
    181        // File format validation
    182        $validatedFile = SpreadsheetTrait::fileHandler($request);
    183        
    184        if (!is_array($validatedFile)) {
    185            // this should be throwing an exception of some kind
    186            return $validatedFile;
    187        }
    188
    189        $purposes = config('constants.purposes');
    190
    191        // Cars data which contain 30k++ of arrays
    192        $car = Cache::get('car')->pluck('slug');
    193
    194        $rules = [
    195            '*.0' => ['required', Rule::in($purposes)],
    196            '*.1' => ['required_if:*.0,PRODUCTION-PROJECT'],
    197            '*.2' => ['required'],
    198            '*.3' => ['required'],
    199            '*.4' => ['required'],
    200            '*.5' => ['required'],
    201            '*.6' => ['required'],
    202            '*.7' => ['required', Rule::in($car)],
    203            '*.8' => ['required', 'numeric', 'min:0'],
    204            '*.9' => ['required', 'integer', 'min:1'],
    205        ];
    206
    207        $messages = [
    208            'required' => 'This field is required, please input.',
    209            'numeric' => 'Please input number value only.',
    210            'integer' => 'Please input integer value only.',
    211            'min' => 'Minimal input value is :min.',
    212            'required_if' => 'This field is required, please input.',
    213        ];
    214
    215        // Start Data Validation
    216        $validatedData = Validator::make($validatedFile, $rules, $messages));
    217    }
    218}
    219$car = Cache::get('car')->pluck('id', 'slug');
    220

    Then your validation rule becomes a super quick closure that only has to check for the existence of the key:

    1class ImportBudget extends Controller
    2{
    3    use SpreadsheetTrait;
    4
    5    public function import(Request $request) 
    6    {
    7        // File format validation
    8        $validatedFile = SpreadsheetTrait::fileHandler($request);
    9        
    10        if (!is_array($validatedFile)) return $validatedFile;
    11
    12        $messages = [
    13            'required' => 'This field is required, please input.',
    14            'numeric' => 'Please input number value only.',
    15            'integer' => 'Please input integer value only.',
    16            'min' => 'Minimal input value is :min.',
    17            'required_if' => 'This field is required, please input.',
    18        ];
    19        
    20        // Cars data which contain 30k++ of arrays
    21        $car = Cache::get('car')->pluck('slug')->toArray();
    22
    23        // Start Data Validation
    24        $validatedData = LazyCollection::make(function () use($validatedFile) {
    25            $data = collect($validatedFile);
    26            yield $data;
    27        })->chunk(1000)->each(function ($rows) use ($car, $messages) {
    28            return Validator::make($rows->toArray(), [
    29                '*.0' => ['required', function ($attribute, $value, $fail) {
    30                    if (!in_array($value , config('constants.purposes'))) {
    31                        $fail('The purpose field is invalid.');
    32                    }
    33                }],
    34                '*.1' => 'required_if:*.0,PRODUCTION-PROJECT',
    35                '*.2' => 'required',
    36                '*.3' => 'required',
    37                '*.4' => 'required',
    38                '*.5' => 'required',
    39                '*.6' => 'required',
    40                '*.7' => ['required', function ($attribute, $value, $fail) use($car) {
    41                    if (!in_array($value, $curr)) {
    42                        $fail('The car is invalid.');
    43                    }
    44                }],
    45                '*.8' => 'required|numeric|min:0',
    46                '*.9' => 'required|integer|min:1',
    47            ], $messages);
    48        });
    49    }
    50}
    51{
    52    "message": "Maximum execution time of 60 seconds exceeded",
    53    "exception": "Symfony\\Component\\ErrorHandler\\Error\\FatalError",
    54    "file": "C:\\laragon\\www\\bulus-jai\\vendor\\laravel\\framework\\src\\Illuminate\\Collections\\Arr.php",
    55    "line": 115,
    56    "trace": []
    57}
    58
    59class BatchValidationServices {
    60
    61    public static function budgetValidation($validatedFile)
    62    {
    63        $requiredFields = [
    64            0 => true,
    65            1 => false,
    66            2 => true,
    67            3 => true,
    68            4 => true,
    69            5 => true,
    70            6 => true,
    71            7 => true,
    72            8 => true,
    73            9 => true,
    74            10 => false
    75        ];
    76
    77        $curr = collect(Cache::get('curr'))
    78            ->where('term.status','BUDGETING')
    79            ->pluck('name')
    80            ->toArray();
    81        $item = Cache::get('item')->pluck('item_code')->toArray();
    82        $car = Cache::get('car')->pluck('slug')->toArray();
    83        $deliveryPlan = Cache::get('delivery');
    84        $orderPlan = Cache::get('order');
    85
    86        $collectedData = LazyCollection::make(function () use($validatedFile) {
    87            $data = collect($validatedFile);
    88            yield $data;
    89        }); 
    90
    91        $errors = [];
    92
    93        $collectedData->chunk(1000)
    94            ->each(function ($collection)  use (
    95                $orderPlan,
    96                $deliveryPlan,
    97                $car,
    98                $curr,
    99                $item,
    100                $requiredFields, &$errors){
    101                foreach ($collection->toArray() as $array) {
    102                    foreach ($array as $key => $row) {
    103    
    104                        // Validate blank rows
    105                        for ($i=0; $i < count($requiredFields); $i++) {
    106                            if ($row[$i] === null &&
    107                            $requiredFields[$i] === true) {
    108                                array_push($errors, [$key.'.'.$i => 'This field is required.']);
    109                            }
    110                        }
    111    
    112                        // Validate purpose validity
    113                        if (!in_array($row[0], config('constants.purposes'))) array_push($errors, [$key.'.0' => 'Purpose is invalid.']);
    114    
    115                        // Validate required preparation item
    116                        $preparationItems = array_column(config('constants.preparations'), 'item');
    117    
    118                        if ($row[0] === 'PRODUCTION-PROJECT' && $row[1] === null) {
    119                            array_push($errors, [$key.'.1' => 'This field is required if the purpose is PRODUCTION-PROJECT.']);  
    120                        } elseif ($row[0] === 'PRODUCTION-PROJECT' && $row[1] !== null) {
    121                            if (!in_array($row[1], $preparationItems)) array_push($errors, [$key.'.1' => 'Production preparation item is invalid.']);
    122                        }
    123    
    124                        // Validate order plan & delivery plan 
    125                        if (!in_array($row[2], $orderPlan)) array_push($errors, [$key.'.2' => 'Order plan is invalid.']);
    126                        
    127                        if (!in_array($row[3], $deliveryPlan)) {
    128                            array_push($errors, [$key.'.3' => 'Delivery plan is invalid.']);
    129                        } else {
    130                            if ($row[3] < $row[2]) array_push($errors, [$key.'.3' => 'Delivery plan should be after or at least in the same period as order plan.']);
    131                        }
    132                        
    133                        // Validate destination-carline
    134                        if (!in_array($row[4], $car)) array_push($errors, [$key.'.4' => 'Destination-carline is invalid.']);
    135
    136                        // Validate Origin
    137                        if (!in_array($row[5], ['DOMESTIC', 'IMPORT'])) array_push($errors, [$key.'.5' => 'Origin supplier is invalid, please choose between DOMESTIC or IMPORT only.']);
    138
    139                        // Validate Item
    140                        if(!in_array($row[6], $item)) array_push($errors, [$key.'.6' => 'Item code is invalid.']);
    141
    142                        // Validate Currency
    143                        if (!in_array($row[7], $curr)) {
    144                            array_push($errors, [$key.'.7' => 'Currency is invalid.']);
    145                        } else {
    146                            if ($row[5] === 'IMPORT' && $row[7] === 'IDR') array_push($errors, [$key.'.7' => 'IDR currency shouldn\'t be used for IMPORT.']);
    147                        }
    148
    149                        // Validate Price
    150                        if (!is_numeric($row[8])) {
    151                            array_push($errors, [$key.'.8' => 'Please only input numerical value.']);
    152                        } else {
    153                            if ($row[8] <= 0) array_push($errors, [$key.'.8' => 'Value must be greater than 0.']);
    154                        }
    155
    156                        // Validate Qty
    157                        if (!is_integer($row[9])) {
    158                            array_push($errors, [$key.'.9' => 'Please only input numerical value.']);
    159                        } else {
    160                            if ($row[9] <= 0) array_push($errors, [$key.'.9' => 'Value must be greater than 0.']);
    161                        }
    162                    }
    163                }
    164
    165                return $errors;
    166            });
    167
    168        if (count($errors) > 0) {
    169            return $errors;
    170        } else {
    171            return true;
    172        }
    173    }
    174}
    175class ImportBudget extends Controller
    176{
    177    use SpreadsheetTrait;
    178
    179    public function import(Request $request) 
    180    {
    181        // File format validation
    182        $validatedFile = SpreadsheetTrait::fileHandler($request);
    183        
    184        if (!is_array($validatedFile)) {
    185            // this should be throwing an exception of some kind
    186            return $validatedFile;
    187        }
    188
    189        $purposes = config('constants.purposes');
    190
    191        // Cars data which contain 30k++ of arrays
    192        $car = Cache::get('car')->pluck('slug');
    193
    194        $rules = [
    195            '*.0' => ['required', Rule::in($purposes)],
    196            '*.1' => ['required_if:*.0,PRODUCTION-PROJECT'],
    197            '*.2' => ['required'],
    198            '*.3' => ['required'],
    199            '*.4' => ['required'],
    200            '*.5' => ['required'],
    201            '*.6' => ['required'],
    202            '*.7' => ['required', Rule::in($car)],
    203            '*.8' => ['required', 'numeric', 'min:0'],
    204            '*.9' => ['required', 'integer', 'min:1'],
    205        ];
    206
    207        $messages = [
    208            'required' => 'This field is required, please input.',
    209            'numeric' => 'Please input number value only.',
    210            'integer' => 'Please input integer value only.',
    211            'min' => 'Minimal input value is :min.',
    212            'required_if' => 'This field is required, please input.',
    213        ];
    214
    215        // Start Data Validation
    216        $validatedData = Validator::make($validatedFile, $rules, $messages));
    217    }
    218}
    219$car = Cache::get('car')->pluck('id', 'slug');
    220'*.7' => ['required', fn ($k, $v, $f) => $car[$v] ?? $f("The car in $k is invalid")],
    221

    Source https://stackoverflow.com/questions/70810965

    QUESTION

    Wrong PHP Version/Executable in VSCode terminal but works perfectly in Mac terminal

    Asked 2021-Dec-30 at 12:35

    I just updated my Mac M1 to Big Sur 11.5.2 and something in VSCode seems to have broken. I am unable to use the latest home-brew php which is installed.

    In VSCode its pointing to /usr/bin/php which is Macs built in php, that's not the one im using with home-brew. I tried everything and changed the path but still the same thing.

    I checked the one similar question to mine and all it suggests is to use Homebrew which I already am doing so Im not sure what I am doing wrong here.

    I am running PHPUnit tests in the VSCode terminal and I am getting the following error:

    1/Users/themyth/App/Sites/MapFramework/map -> ./vendor/bin/phpunit tests                           
    2/usr/bin/php declares an invalid value for PHP_VERSION.
    3This breaks fundamental functionality such as version_compare().
    4Please use a different PHP interpreter.
    5/Users/themyth/App/Sites/MapFramework/map ->
    6

    However when I run the same thing in the Mac terminal by going to the same folder it works perfectly:

    1/Users/themyth/App/Sites/MapFramework/map -> ./vendor/bin/phpunit tests                           
    2/usr/bin/php declares an invalid value for PHP_VERSION.
    3This breaks fundamental functionality such as version_compare().
    4Please use a different PHP interpreter.
    5/Users/themyth/App/Sites/MapFramework/map ->
    6/Users/themyth/app/Sites/MapFramework/Map -> ./vendor/bin/phpunit tests                                            
    7PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
    8
    9Runtime:       PHP 8.0.9
    10Configuration: /Users/themyth/App/Sites/MapFramework/Map/phpunit.xml
    11
    12...R                                                                4 / 4 (100%)
    13
    14Time: 00:00.004, Memory: 6.00 MB
    15
    16There was 1 risky test:
    17
    181) tests\map\core\exception\MapExceptionTest::testDisplayMethodShowsBasicStaticHtml
    19This test did not perform any assertions
    20
    21/Users/themyth/App/Sites/MapFramework/Map/tests/map/core/exception/MapExceptionTest.php:16
    22
    23OK, but incomplete, skipped, or risky tests!
    24Tests: 4, Assertions: 4, Risky: 1.
    25/Users/themyth/app/Sites/MapFramework/Map -> 
    26

    When I do which php in both terminals I get a different result:

    In Mac terminal:

    1/Users/themyth/App/Sites/MapFramework/map -> ./vendor/bin/phpunit tests                           
    2/usr/bin/php declares an invalid value for PHP_VERSION.
    3This breaks fundamental functionality such as version_compare().
    4Please use a different PHP interpreter.
    5/Users/themyth/App/Sites/MapFramework/map ->
    6/Users/themyth/app/Sites/MapFramework/Map -> ./vendor/bin/phpunit tests                                            
    7PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
    8
    9Runtime:       PHP 8.0.9
    10Configuration: /Users/themyth/App/Sites/MapFramework/Map/phpunit.xml
    11
    12...R                                                                4 / 4 (100%)
    13
    14Time: 00:00.004, Memory: 6.00 MB
    15
    16There was 1 risky test:
    17
    181) tests\map\core\exception\MapExceptionTest::testDisplayMethodShowsBasicStaticHtml
    19This test did not perform any assertions
    20
    21/Users/themyth/App/Sites/MapFramework/Map/tests/map/core/exception/MapExceptionTest.php:16
    22
    23OK, but incomplete, skipped, or risky tests!
    24Tests: 4, Assertions: 4, Risky: 1.
    25/Users/themyth/app/Sites/MapFramework/Map -> 
    26/Users/themyth/app/Sites/MapFramework/Map -> which php
    27/opt/homebrew/bin/php
    28

    In VSCode terminal:

    1/Users/themyth/App/Sites/MapFramework/map -> ./vendor/bin/phpunit tests                           
    2/usr/bin/php declares an invalid value for PHP_VERSION.
    3This breaks fundamental functionality such as version_compare().
    4Please use a different PHP interpreter.
    5/Users/themyth/App/Sites/MapFramework/map ->
    6/Users/themyth/app/Sites/MapFramework/Map -> ./vendor/bin/phpunit tests                                            
    7PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
    8
    9Runtime:       PHP 8.0.9
    10Configuration: /Users/themyth/App/Sites/MapFramework/Map/phpunit.xml
    11
    12...R                                                                4 / 4 (100%)
    13
    14Time: 00:00.004, Memory: 6.00 MB
    15
    16There was 1 risky test:
    17
    181) tests\map\core\exception\MapExceptionTest::testDisplayMethodShowsBasicStaticHtml
    19This test did not perform any assertions
    20
    21/Users/themyth/App/Sites/MapFramework/Map/tests/map/core/exception/MapExceptionTest.php:16
    22
    23OK, but incomplete, skipped, or risky tests!
    24Tests: 4, Assertions: 4, Risky: 1.
    25/Users/themyth/app/Sites/MapFramework/Map -> 
    26/Users/themyth/app/Sites/MapFramework/Map -> which php
    27/opt/homebrew/bin/php
    28/Users/themyth/App/Sites/MapFramework/map -> which php
    29/usr/bin/php
    30/Users/themyth/App/Sites/MapFramework/map -> 
    31

    How can I point VSCode to the right version of PHP? I don't think this happened before doing the Big Sur update and I am not sure what to edit.

    I tried to open settings.json but I can't find any info about this and I am not sure how to edit this.

    Any advice would be appreciated.


    Edit 1:

    I think this issue happened since I installed PHPIntellisense on VSCode but can't be sure, what I do know is that it was working before. I dont know how to configure VSCode to point to the home-brew PHP which is already installed and working perfectly in the regular terminal


    Edit 2

    I tried to edit settings.json and it made no difference:

    1/Users/themyth/App/Sites/MapFramework/map -> ./vendor/bin/phpunit tests                           
    2/usr/bin/php declares an invalid value for PHP_VERSION.
    3This breaks fundamental functionality such as version_compare().
    4Please use a different PHP interpreter.
    5/Users/themyth/App/Sites/MapFramework/map ->
    6/Users/themyth/app/Sites/MapFramework/Map -> ./vendor/bin/phpunit tests                                            
    7PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
    8
    9Runtime:       PHP 8.0.9
    10Configuration: /Users/themyth/App/Sites/MapFramework/Map/phpunit.xml
    11
    12...R                                                                4 / 4 (100%)
    13
    14Time: 00:00.004, Memory: 6.00 MB
    15
    16There was 1 risky test:
    17
    181) tests\map\core\exception\MapExceptionTest::testDisplayMethodShowsBasicStaticHtml
    19This test did not perform any assertions
    20
    21/Users/themyth/App/Sites/MapFramework/Map/tests/map/core/exception/MapExceptionTest.php:16
    22
    23OK, but incomplete, skipped, or risky tests!
    24Tests: 4, Assertions: 4, Risky: 1.
    25/Users/themyth/app/Sites/MapFramework/Map -> 
    26/Users/themyth/app/Sites/MapFramework/Map -> which php
    27/opt/homebrew/bin/php
    28/Users/themyth/App/Sites/MapFramework/map -> which php
    29/usr/bin/php
    30/Users/themyth/App/Sites/MapFramework/map -> 
    31{
    32    "workbench.colorTheme": "Monokai Dimmed",
    33    "security.workspace.trust.untrustedFiles": "open",
    34    "redhat.telemetry.enabled": false,
    35    "php.validate.executablePath": "/opt/homebrew/bin/php",
    36    "php.executablePath": "/opt/homebrew/bin/php"
    37}
    38

    Edit 3

    I have completely uninstalled VSCode and reinstalled everything. To start from fresh and the same problem happens. This is what the current settings.json file looks like:

    1/Users/themyth/App/Sites/MapFramework/map -> ./vendor/bin/phpunit tests                           
    2/usr/bin/php declares an invalid value for PHP_VERSION.
    3This breaks fundamental functionality such as version_compare().
    4Please use a different PHP interpreter.
    5/Users/themyth/App/Sites/MapFramework/map ->
    6/Users/themyth/app/Sites/MapFramework/Map -> ./vendor/bin/phpunit tests                                            
    7PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
    8
    9Runtime:       PHP 8.0.9
    10Configuration: /Users/themyth/App/Sites/MapFramework/Map/phpunit.xml
    11
    12...R                                                                4 / 4 (100%)
    13
    14Time: 00:00.004, Memory: 6.00 MB
    15
    16There was 1 risky test:
    17
    181) tests\map\core\exception\MapExceptionTest::testDisplayMethodShowsBasicStaticHtml
    19This test did not perform any assertions
    20
    21/Users/themyth/App/Sites/MapFramework/Map/tests/map/core/exception/MapExceptionTest.php:16
    22
    23OK, but incomplete, skipped, or risky tests!
    24Tests: 4, Assertions: 4, Risky: 1.
    25/Users/themyth/app/Sites/MapFramework/Map -> 
    26/Users/themyth/app/Sites/MapFramework/Map -> which php
    27/opt/homebrew/bin/php
    28/Users/themyth/App/Sites/MapFramework/map -> which php
    29/usr/bin/php
    30/Users/themyth/App/Sites/MapFramework/map -> 
    31{
    32    "workbench.colorTheme": "Monokai Dimmed",
    33    "security.workspace.trust.untrustedFiles": "open",
    34    "redhat.telemetry.enabled": false,
    35    "php.validate.executablePath": "/opt/homebrew/bin/php",
    36    "php.executablePath": "/opt/homebrew/bin/php"
    37}
    38{
    39    "workbench.colorTheme": "Default Dark+",
    40    "php.validate.executablePath": "/opt/homebrew/bin/php"
    41}
    42

    When I do which php in the terminal in VSCode I always get the same thing /usr/bin/php

    The same problem is continuing, Im not sure if this is because of the OSX update.

    How could I configure the VSCode terminal to be exactly like the Mac terminal?

    I also opened another project where I am using Symfony and I am trying to create a basic controller & that doesn't work too. I have edited the question to be more generic now:

    php bin/console make:controller test I get the following error:

    1/Users/themyth/App/Sites/MapFramework/map -> ./vendor/bin/phpunit tests                           
    2/usr/bin/php declares an invalid value for PHP_VERSION.
    3This breaks fundamental functionality such as version_compare().
    4Please use a different PHP interpreter.
    5/Users/themyth/App/Sites/MapFramework/map ->
    6/Users/themyth/app/Sites/MapFramework/Map -> ./vendor/bin/phpunit tests                                            
    7PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
    8
    9Runtime:       PHP 8.0.9
    10Configuration: /Users/themyth/App/Sites/MapFramework/Map/phpunit.xml
    11
    12...R                                                                4 / 4 (100%)
    13
    14Time: 00:00.004, Memory: 6.00 MB
    15
    16There was 1 risky test:
    17
    181) tests\map\core\exception\MapExceptionTest::testDisplayMethodShowsBasicStaticHtml
    19This test did not perform any assertions
    20
    21/Users/themyth/App/Sites/MapFramework/Map/tests/map/core/exception/MapExceptionTest.php:16
    22
    23OK, but incomplete, skipped, or risky tests!
    24Tests: 4, Assertions: 4, Risky: 1.
    25/Users/themyth/app/Sites/MapFramework/Map -> 
    26/Users/themyth/app/Sites/MapFramework/Map -> which php
    27/opt/homebrew/bin/php
    28/Users/themyth/App/Sites/MapFramework/map -> which php
    29/usr/bin/php
    30/Users/themyth/App/Sites/MapFramework/map -> 
    31{
    32    "workbench.colorTheme": "Monokai Dimmed",
    33    "security.workspace.trust.untrustedFiles": "open",
    34    "redhat.telemetry.enabled": false,
    35    "php.validate.executablePath": "/opt/homebrew/bin/php",
    36    "php.executablePath": "/opt/homebrew/bin/php"
    37}
    38{
    39    "workbench.colorTheme": "Default Dark+",
    40    "php.validate.executablePath": "/opt/homebrew/bin/php"
    41}
    42Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.0.0". You are running 7.3.24-(to be removed in future macOS)
    43

    What is most frustrating is this seems so straight forward I can't understand what I need to do to fix this

    ANSWER

    Answered 2021-Aug-25 at 09:40

    I got the same problem. Open your terminal and write this:

    1/Users/themyth/App/Sites/MapFramework/map -> ./vendor/bin/phpunit tests                           
    2/usr/bin/php declares an invalid value for PHP_VERSION.
    3This breaks fundamental functionality such as version_compare().
    4Please use a different PHP interpreter.
    5/Users/themyth/App/Sites/MapFramework/map ->
    6/Users/themyth/app/Sites/MapFramework/Map -> ./vendor/bin/phpunit tests                                            
    7PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
    8
    9Runtime:       PHP 8.0.9
    10Configuration: /Users/themyth/App/Sites/MapFramework/Map/phpunit.xml
    11
    12...R                                                                4 / 4 (100%)
    13
    14Time: 00:00.004, Memory: 6.00 MB
    15
    16There was 1 risky test:
    17
    181) tests\map\core\exception\MapExceptionTest::testDisplayMethodShowsBasicStaticHtml
    19This test did not perform any assertions
    20
    21/Users/themyth/App/Sites/MapFramework/Map/tests/map/core/exception/MapExceptionTest.php:16
    22
    23OK, but incomplete, skipped, or risky tests!
    24Tests: 4, Assertions: 4, Risky: 1.
    25/Users/themyth/app/Sites/MapFramework/Map -> 
    26/Users/themyth/app/Sites/MapFramework/Map -> which php
    27/opt/homebrew/bin/php
    28/Users/themyth/App/Sites/MapFramework/map -> which php
    29/usr/bin/php
    30/Users/themyth/App/Sites/MapFramework/map -> 
    31{
    32    "workbench.colorTheme": "Monokai Dimmed",
    33    "security.workspace.trust.untrustedFiles": "open",
    34    "redhat.telemetry.enabled": false,
    35    "php.validate.executablePath": "/opt/homebrew/bin/php",
    36    "php.executablePath": "/opt/homebrew/bin/php"
    37}
    38{
    39    "workbench.colorTheme": "Default Dark+",
    40    "php.validate.executablePath": "/opt/homebrew/bin/php"
    41}
    42Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.0.0". You are running 7.3.24-(to be removed in future macOS)
    43nano ~/.zshrc
    44

    At the top of the file you have this:

    1/Users/themyth/App/Sites/MapFramework/map -> ./vendor/bin/phpunit tests                           
    2/usr/bin/php declares an invalid value for PHP_VERSION.
    3This breaks fundamental functionality such as version_compare().
    4Please use a different PHP interpreter.
    5/Users/themyth/App/Sites/MapFramework/map ->
    6/Users/themyth/app/Sites/MapFramework/Map -> ./vendor/bin/phpunit tests                                            
    7PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
    8
    9Runtime:       PHP 8.0.9
    10Configuration: /Users/themyth/App/Sites/MapFramework/Map/phpunit.xml
    11
    12...R                                                                4 / 4 (100%)
    13
    14Time: 00:00.004, Memory: 6.00 MB
    15
    16There was 1 risky test:
    17
    181) tests\map\core\exception\MapExceptionTest::testDisplayMethodShowsBasicStaticHtml
    19This test did not perform any assertions
    20
    21/Users/themyth/App/Sites/MapFramework/Map/tests/map/core/exception/MapExceptionTest.php:16
    22
    23OK, but incomplete, skipped, or risky tests!
    24Tests: 4, Assertions: 4, Risky: 1.
    25/Users/themyth/app/Sites/MapFramework/Map -> 
    26/Users/themyth/app/Sites/MapFramework/Map -> which php
    27/opt/homebrew/bin/php
    28/Users/themyth/App/Sites/MapFramework/map -> which php
    29/usr/bin/php
    30/Users/themyth/App/Sites/MapFramework/map -> 
    31{
    32    "workbench.colorTheme": "Monokai Dimmed",
    33    "security.workspace.trust.untrustedFiles": "open",
    34    "redhat.telemetry.enabled": false,
    35    "php.validate.executablePath": "/opt/homebrew/bin/php",
    36    "php.executablePath": "/opt/homebrew/bin/php"
    37}
    38{
    39    "workbench.colorTheme": "Default Dark+",
    40    "php.validate.executablePath": "/opt/homebrew/bin/php"
    41}
    42Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.0.0". You are running 7.3.24-(to be removed in future macOS)
    43nano ~/.zshrc
    44# If you come from bash you might have to change your $PATH.
    45# export PATH=$HOME/bin:/usr/local/bin:$PATH
    46

    Put this line just under:

    1/Users/themyth/App/Sites/MapFramework/map -> ./vendor/bin/phpunit tests                           
    2/usr/bin/php declares an invalid value for PHP_VERSION.
    3This breaks fundamental functionality such as version_compare().
    4Please use a different PHP interpreter.
    5/Users/themyth/App/Sites/MapFramework/map ->
    6/Users/themyth/app/Sites/MapFramework/Map -> ./vendor/bin/phpunit tests                                            
    7PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
    8
    9Runtime:       PHP 8.0.9
    10Configuration: /Users/themyth/App/Sites/MapFramework/Map/phpunit.xml
    11
    12...R                                                                4 / 4 (100%)
    13
    14Time: 00:00.004, Memory: 6.00 MB
    15
    16There was 1 risky test:
    17
    181) tests\map\core\exception\MapExceptionTest::testDisplayMethodShowsBasicStaticHtml
    19This test did not perform any assertions
    20
    21/Users/themyth/App/Sites/MapFramework/Map/tests/map/core/exception/MapExceptionTest.php:16
    22
    23OK, but incomplete, skipped, or risky tests!
    24Tests: 4, Assertions: 4, Risky: 1.
    25/Users/themyth/app/Sites/MapFramework/Map -> 
    26/Users/themyth/app/Sites/MapFramework/Map -> which php
    27/opt/homebrew/bin/php
    28/Users/themyth/App/Sites/MapFramework/map -> which php
    29/usr/bin/php
    30/Users/themyth/App/Sites/MapFramework/map -> 
    31{
    32    "workbench.colorTheme": "Monokai Dimmed",
    33    "security.workspace.trust.untrustedFiles": "open",
    34    "redhat.telemetry.enabled": false,
    35    "php.validate.executablePath": "/opt/homebrew/bin/php",
    36    "php.executablePath": "/opt/homebrew/bin/php"
    37}
    38{
    39    "workbench.colorTheme": "Default Dark+",
    40    "php.validate.executablePath": "/opt/homebrew/bin/php"
    41}
    42Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.0.0". You are running 7.3.24-(to be removed in future macOS)
    43nano ~/.zshrc
    44# If you come from bash you might have to change your $PATH.
    45# export PATH=$HOME/bin:/usr/local/bin:$PATH
    46export PATH=/opt/homebrew/opt/php@8.0/bin:$PATH
    47

    Save and close, restart your terminal and it will normally work.

    NB: I write php@8.0 but you can do this with all versions you install with homebrew

    Source https://stackoverflow.com/questions/68899144

    QUESTION

    Symfony #[CurrentUser] attribute returns null

    Asked 2021-Nov-02 at 17:37
    1<?php
    2
    3declare(strict_types=1);
    4
    5namespace App\Controller\User;
    6
    7use App\Entity\User;
    8use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    9use Symfony\Component\HttpFoundation\Request;
    10use Symfony\Component\HttpFoundation\Response;
    11use Symfony\Component\Routing\Annotation\Route;
    12use Symfony\Component\Security\Http\Attribute\CurrentUser;
    13
    14#[Route('/users', name: 'user.')]
    15class UserController extends AbstractController
    16{
    17    #[Route(name: 'list')]
    18    public function list(#[CurrentUser] ?User $user, Request $request): Response { 
    19        dd($user->getFirstName());
    20    }
    21
    22

    Say's Call to a member function getFirstName() on null

    But I'm authorized. At the Symfony Profiler it shows that I'm logged in.

    Env: PHP 8.0.11 Symfony 5.3.9

    ANSWER

    Answered 2021-Nov-02 at 11:47

    if your controller extends "AbstractController" you can use $this->getUser() to get the current User.

    in your list function you are not giving an user id neither an $user so $user is rationally null

    1<?php
    2
    3declare(strict_types=1);
    4
    5namespace App\Controller\User;
    6
    7use App\Entity\User;
    8use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    9use Symfony\Component\HttpFoundation\Request;
    10use Symfony\Component\HttpFoundation\Response;
    11use Symfony\Component\Routing\Annotation\Route;
    12use Symfony\Component\Security\Http\Attribute\CurrentUser;
    13
    14#[Route('/users', name: 'user.')]
    15class UserController extends AbstractController
    16{
    17    #[Route(name: 'list')]
    18    public function list(#[CurrentUser] ?User $user, Request $request): Response { 
    19        dd($user->getFirstName());
    20    }
    21
    22#[Route('/users', name: 'user.')]
    23class UserController extends AbstractController
    24 {
    25#[Route(name: 'list')]
    26public function list( Request 
    27$request): Response { 
    28    dd($this->getUser()->getFirstName());
    29}
    30

    Source https://stackoverflow.com/questions/69809320

    QUESTION

    Symfony 5.3 empty collection with a OneToMany relation

    Asked 2021-Oct-26 at 09:17

    I have on my Symfony 5 project, 2 entities : Client and Template. Each Client has one or more templates (OneToMany), each templates relates to only one Client (ManyToOne). I have a getTemplates() function in Client.php which returns a Collection of templates.

    The problem I am getting is that when I call the getTemplates() function I run it from :

    1$client = $entityManager->getRepository(Client::class)->find($id);
    2$templates = $client->getTemplates();
    3

    I am getting an initialized = false Collection.

    From what I understand, to avoid unnecessary requests, Symfony creates a Template proxy object which is null. To make this work, I can add fetch="EAGER"

    1$client = $entityManager->getRepository(Client::class)->find($id);
    2$templates = $client->getTemplates();
    3@ORM\OneToMany(targetEntity=Template::class, mappedBy="Client", orphanRemoval=true, fetch="EAGER")
    4

    Adding this basically makes request the "real" Template object (more information here).

    What I would like to do is make my getTemplates work without having to request all the templates when I retrieve all my clients like here (sometimes I only need to display all the clients, and request the templates from a certain client afterwards):

    1$client = $entityManager->getRepository(Client::class)->find($id);
    2$templates = $client->getTemplates();
    3@ORM\OneToMany(targetEntity=Template::class, mappedBy="Client", orphanRemoval=true, fetch="EAGER")
    4$templateRepository->findAll()
    5

    I know how to solve my problem, I just would like to have the best way to do it while having the smallest amount of requests to my database (basically only calling it when I need it).

    To sum up, I would like to :

    • findAll() of my clients without retrieving the templates associated to the clients
    • findAll() of my templates and get the relating client - this currently works when I add a fetch="EAGER" since I get an "owner" which corresponds to the correct client

    ANSWER

    Answered 2021-Oct-26 at 09:17

    As Yassinefikri explained, the default Symfony behavior is not to request the linked Entities to avoid bad performance.

    To solve the problem, you need a proper function in the repository where you will fetch the Clients and join them with their Templates.

    This allows to fetch all the Clients without their Template but also be able to fetch all the Clients with their Templates, regarding of if you need it or not.

    Changing the default behavior of Symfony by adding a fetch="EAGER" is not good practice, you should always create a function for a desired result instead of changing default behavior (which would decrease performance, specially if you are dealing with a big DB).

    - EDIT, Better (and more optimized) way of solving the problem

    As Will B said, the behavior comes from Doctrine ORM and not not Symfony (Symfony frequently is used with Doctrine ORM but this applies to ORM in general).

    Another (and better) way of achieving the desired result is to initilialize the object (which will fetch linked entities without actually making JOIN requests to the DB - initializeObject()).

    TO SUM UP

    NEVER use fetch="EAGER" if you can since this is really the work way of dealing with linked entities, it is ay better to use Will B's or Yassinefikri's solution to the problem.

    Source https://stackoverflow.com/questions/69705859

    Community Discussions contain sources that include Stack Exchange Network

    Tutorials and Learning Resources in Symfony

    Tutorials and Learning Resources are not available at this moment for Symfony

    Share this Page

    share link

    Get latest updates on Symfony