Configuración automática del "propietario
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
With a Subscription, click any sentence in the script to jump to that part of the video!
Login SubscribeCada DragonTreasure debe tener un owner... y para establecerlo, cuando POSTpara crear un tesoro, requerimos ese campo. Creo que deberíamos hacerlo opcional. Así que, en la prueba, deja de enviar el campo owner:
| // ... lines 1 - 12 | |
| class DragonTreasureResourceTest extends ApiTestCase | |
| { | |
| // ... lines 15 - 41 | |
| public function testPostToCreateTreasure(): void | |
| { | |
| // ... lines 44 - 45 | |
| $this->browser() | |
| // ... lines 47 - 51 | |
| ->post('/api/treasures', HttpOptions::json([ | |
| // ... lines 53 - 56 | |
| 'owner' => '/api/users/'.$user->getId(), | |
| ])) | |
| // ... lines 59 - 60 | |
| ; | |
| } | |
| // ... lines 63 - 179 | |
| } |
Cuando esto ocurra, configurémoslo automáticamente para el usuario autenticado actualmente.
Asegúrate de que la prueba falla. Copia el nombre del método... y ejecútalo:
symfony php bin/phpunit --filter=testPostToCreateTreasure
Falló. Obtuve un 422, 201 esperado. Ese 422 es un error de validación de la propiedad owner: este valor no debe ser nulo.
Eliminar la validación del propietario
Si vamos a hacerlo opcional, tenemos que eliminar ese Assert\NotNull:
| // ... lines 1 - 88 | |
| class DragonTreasure | |
| { | |
| // ... lines 91 - 136 | |
| // ... line 138 | |
| private ?User $owner = null; | |
| // ... lines 140 - 251 | |
| } |
Y ahora cuando intentemos la prueba
symfony php bin/phpunit --filter=testPostToCreateTreasure
¡Hola magnífico error 500! Probablemente se deba a que el nulo owner_id hace kaboom cuando llega a la base de datos. ¡Yup!
Utilizar los procesadores de estado
Entonces: ¿cómo podemos establecer automáticamente este campo cuando no se envía? En el tutorial anterior de la API Platform 2, lo hice con un oyente de entidad, que es una buena solución. Pero en la API Platform 3, al igual que cuando hicimos hash de la contraseña de usuario, ahora hay un sistema muy bueno para esto: el sistema de procesadores de estado.
Como recordatorio, nuestras rutas POST y PATCH para DragonTreasure ya tienen un procesador de estado que proviene de Doctrine: es el responsable de guardar el objeto en la base de datos. Llegados a este punto, nuestro objetivo te resultará familiar: decorar ese proceso de estado para que podamos ejecutar código adicional antes de guardar.
Como antes, empieza ejecutando:
php bin/console make:state-processor
Llámalo DragonTreasureSetOwnerProcessor:
| // ... lines 1 - 2 | |
| namespace App\State; | |
| use ApiPlatform\Metadata\Operation; | |
| use ApiPlatform\State\ProcessorInterface; | |
| class DragonTreasureSetOwnerProcessor implements ProcessorInterface | |
| { | |
| public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void | |
| { | |
| // Handle the state | |
| } | |
| } |
En src/State/, ábrelo. Vale, ¡a decorar! Añade el método construct con private ProcessorInterface $innerProcessor:
| // ... lines 1 - 5 | |
| use ApiPlatform\State\ProcessorInterface; | |
| // ... lines 7 - 9 | |
| class DragonTreasureSetOwnerProcessor implements ProcessorInterface | |
| { | |
| public function __construct(private ProcessorInterface $innerProcessor) | |
| { | |
| } | |
| // ... lines 15 - 19 | |
| } |
Luego abajo en process(), ¡llama a eso! Este método no devuelve nada - tiene un retorno void - así que sólo necesitamos $this->innerProcessor - no olvides esa parte como estoy haciendo yo - ->process() pasando $data, $operation, $uriVariables y$context:
| // ... lines 1 - 9 | |
| class DragonTreasureSetOwnerProcessor implements ProcessorInterface | |
| { | |
| // ... lines 12 - 15 | |
| public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void | |
| { | |
| $this->innerProcessor->process($data, $operation, $uriVariables, $context); | |
| } | |
| } |
Ahora, para hacer que Symfony utilice nuestro procesador de estado en lugar del normal de Doctrine, añade #[AsDecorator]... y el id del servicio esapi_platform.doctrine.orm.state.persist_processor:
| // ... lines 1 - 6 | |
| use Symfony\Component\DependencyInjection\Attribute\AsDecorator; | |
| ('api_platform.doctrine.orm.state.persist_processor') | |
| class DragonTreasureSetOwnerProcessor implements ProcessorInterface | |
| { | |
| // ... lines 12 - 19 | |
| } |
¡Genial! Ahora, a todo lo que utilice ese servicio en el sistema se le pasará nuestro servicio en su lugar... y luego se nos pasará el original.
¡Decorar varias veces está bien!
Ah, y está pasando algo guay. Mira UserHashPasswordStateProcessor. ¡Estamos decorando lo mismo ahí! Sí, estamos decorando ese servicio dos veces, ¡lo que está totalmente permitido! Internamente, esto creará una especie de cadena de servicios decorados.
Bien, pongámonos a trabajar en la configuración del propietario. Conecta automáticamente nuestro servicio favorito Security para que podamos averiguar quién ha iniciado sesión:
| // ... lines 1 - 7 | |
| use Symfony\Bundle\SecurityBundle\Security; | |
| // ... lines 9 - 11 | |
| class DragonTreasureSetOwnerProcessor implements ProcessorInterface | |
| { | |
| public function __construct(private ProcessorInterface $innerProcessor, private Security $security) | |
| { | |
| } | |
| // ... lines 17 - 25 | |
| } |
Entonces, antes de que hagamos el guardado, si $data es un instanceof DragonTreasurey $data->getOwner() es nulo y $this->security->getUser() -asegurándonos de que el usuario está conectado- entonces $data->setOwner($this->security->getUser()):
| // ... lines 1 - 11 | |
| class DragonTreasureSetOwnerProcessor implements ProcessorInterface | |
| { | |
| // ... lines 14 - 17 | |
| public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void | |
| { | |
| if ($data instanceof DragonTreasure && $data->getOwner() === null && $this->security->getUser()) { | |
| $data->setOwner($this->security->getUser()); | |
| } | |
| $this->innerProcessor->process($data, $operation, $uriVariables, $context); | |
| } | |
| } |
¡Eso debería bastar! Ejecuta esa prueba:
symfony php bin/phpunit --filter=testPostToCreateTreasure
¡Caramba! Tamaño de memoria permitido agotado. ¡Me huele a recursión! Porque... Me estoy llamando aprocess(): Necesito $this->innerProcessor->process():
| // ... lines 1 - 11 | |
| class DragonTreasureSetOwnerProcessor implements ProcessorInterface | |
| { | |
| // ... lines 14 - 17 | |
| public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void | |
| { | |
| // ... lines 20 - 23 | |
| $this->innerProcessor->process($data, $operation, $uriVariables, $context); | |
| } | |
| } |
Ahora:
symfony php bin/phpunit --filter=testPostToCreateTreasure
Una prueba superada mola mucho más que la recursividad. ¡Y el campo propietario ahora es opcional!
Siguiente: actualmente devolvemos todos los tesoros de nuestro punto final de colección GET, incluidos los tesoros no publicados. Arreglémoslo modificando la consulta detrás de ese punto final para ocultarlos.
15 Comments
process method should return the result, otherwise you get NULL response in the response body
Hey @Nuri!
I think you're right - it was a (I believe) non-intentional change in API Platform 3.2. I've just added a note for this (I had a note in an earlier chapter already). And you weren't the only one tripping over this :) - https://github.com/SymfonyCasts/api-platform3/issues/43 - I appreciate the reports.
Cheers!
hi i'm stuck here
i'm using api 3.3.1 and symfony 7.1
my test:
the owner part on my Park entity:
i'm getting an error i can't understand:
i finally manage to make it works. To make it i had to add an Authorization Header (i'm using JWT). But in the tutorial i don't how the user is authenticated in the test:
you have :
`public function testPostToCreateTreasure(): void
So where is the authentication happening ? how could the test pass if you don't authenticate ? i am missing something ?
Thanks and great tut by the way.
Ok i think i found the "problem".
It is because i am using JWT for the connexion and actingAs apparently is using the PHP sessions as far as i understand.
I tried without actingAS and put only the authorisation header with my token and the test pass.
thanks
Hey @Zaz
Thank you for sharing your solution. As far as I know, the
actingAs()method is a quick way to log in as any user in your tests, but it does not goes through the login process, it's more like a hackCheers!
It appears that the custom processor runs after the security annotations. So when this is set: object.getOwnerUser() on an entity's security annotation - the test just fails :-(
I could put security logic into the processor, but it feels like it belongs in the security annotations as: 'object.getOwnerUser() == user'.
ideally the processor would set ownerUser to: the currently logged in user (when it's not set explicitly via the post) and throw a 403 when the owner is set incorrectly. Or is this not the right approach? I'm just a little confused about how these two concepts work together in a real app.
Hey @Cameron
Sorry for the late reply. Yea, sometimes the execution order can cause you trouble. Have you tried moving your security logic into a voter? Or, in this case, it may make sense to use a constraint validation on the
ownerproperty.Cheers!
I was able to get it it work by gwtting the voter to only act if there was an error, then it passes through to the processor. But it wasnt clear how to design api logic for both of these elements as theres some interplay / considerations
Yea, it seems to me this is a flaw on ApiPlatform, and this is not the only case. In this video Ryan talks about another runtime condition that may cause you trouble. I think your approach is correct unless we're missing something. Have you tried asking in the ApiPlatform slack channel? They may know more about how to handle this edge-case
When will this finally be ready?
Hey @Rsteuber!
I JUST recorded the audio today - it'll probably be a week or two before the video is out, but you refresh, you'll see the final "script" for this chapter (though, code blocks will come later). Also, if you download the code, what we do in this chapter is already in there. I hope that helps!
Cheers!
Hmm, it seems I can't download the source code yet. Guess i have to wait when it is released.
Cheers :)
Hey @Rsteuber
Yea, the download button it's disabled for non-published chapters, but if you only want to download the course code, you can go to any other chapter and download it there
Cheers!
Hey Ryan, Yes thank you so very much! It really helps :)
"Houston: no signs of life"
Start the conversation!