In my user entity I declared 2 PATCH routes. Both of these require token authentication to access. I wanted to provide user data from the token instead of the uri variable. After creating custom data provider, my routes however broke completely. Using the route with custom state processor I was able to diagnose that data provider always returns almost fully null object. I had no problems with data providers before but I didn't use them for PATCH. Am i missing some annotation? Api platform documentation is really lacking and examples are hard to find. I'm theorizing that it still tries to access users from original url that is users/{id}
user entity:
#[ApiResource(
operations: [
new Get(
normalizationContext: ['groups'=> ['user:read']],
),
new Patch(//for password and email
name: 'credentials',
uriTemplate: '/users/credentials',
processor: UserCredentialsPersistStateProcessor::class,
validationContext: ['groups' => ['user:write_credentials']],
denormalizationContext: ['groups' => ['user:write_credentials']],
security: "is_granted('ROLE_REDDIT_ADMIN') or is_granted('ROLE_USER')",
securityMessage: "Only user himself can modify his settings.",
provider: UserFromTokenProvider::class,
// input: User::class,
),
new Patch(// for all other settings
uriTemplate: '/users',
denormalizationContext: ['groups'=> ['user:write']],
security: "is_granted('ROLE_REDDIT_ADMIN') or is_granted('ROLE_USER')",
securityMessage: "Only user himself can modify his settings.",
provider: UserFromTokenProvider::class,
),
//rest of routes
],
)]
class UserFromTokenProvider implements ProviderInterface
{
public function __construct(
private UserRepository $repository,
private Security $security
) {
}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): User|null
{
$currentUser = $this->security->getUser();
if ($currentUser !== null) {
$user = $this->repository->findOneBy(['login' => $currentUser->getUserIdentifier()]);
return $user;
} else {
throw new ItemNotFoundException('Token is not assosiated with user.', 404);
}
}
}
result from var dump:
object(App\Entity\User)#6754 (17) {
["id":"App\Entity\User":private]=>
NULL
["login":"App\Entity\User":private]=>
NULL
["nickname":"App\Entity\User":private]=>
NULL
["email":"App\Entity\User":private]=>
NULL
["newEmail":"App\Entity\User":private]=>
string(16) "[email protected]"
["description":"App\Entity\User":private]=>
NULL
["password":"App\Entity\User":private]=>
NULL
["plainOldPassword":"App\Entity\User":private]=>
string(6) "string"
["plainPassword":"App\Entity\User":private]=>
string(6) "string"
["isNSFW":"App\Entity\User":private]=>
bool(false)
["roles":"App\Entity\User":private]=>
array(1) {
[0]=>
string(9) "ROLE_USER"
}
I tried to modify the provider, returning null, full object with id of 1, trowing exceptions with always the same result.