0

I'd like to return a variable message based on which one of the if statements fails, but I don't know how to do so within one validator. I'm not quite sure what the best practice is in this case. Both of the if statements require the $entity, and splitting this up into separate validators would mean I'd have to query it multiple times just for the validation.

        'validators' => [
            [
                'name'    => ValidatorCallback::class,
                'options' => [
                    'callback' => function ($value) {
                        $entity= $this->getObjectManager()
                                             ->getRepository(SalesChannel::class)
                                             ->find($value);

                        if (is_null($entity)) {
                            //No entity found with the given id.
                            return false;
                        }

                        if ($value !== $entity->getParent()->getId()) {
                            //Wrong parent
                                return false;
                            }
                        },
                        'messages' => [
                            'callbackValue' => _(
                                'Error, ...... is wrong'
                            ),
                        ],
                    ],
                ],
            ],
lucid
  • 422
  • 3
  • 15

1 Answers1

1

As i see, as an ORM you are using Doctrine 2 ? Inside documentation, you can find part about Identity Map pattern Entities and the Identity Map.

The most important informations are:

... no matter how often do you retrieve it from the EntityManager and even no matter what kind of Query method you are using (find, Repository Finder or DQL). This is called Identity Map pattern, which means Doctrine keeps a map of each entity and ids that have been retrieved per PHP request and keeps returning you the same instances.

As you can see, you can split it into separate validators, without affecting performance.

VirCom
  • 3,414
  • 1
  • 10
  • 10