src/Twig/UserExtension.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\Twig;
  3. use App\Entity\Account\Advertiser;
  4. use App\Entity\Account\Avatar;
  5. use App\Entity\Account\Customer;
  6. use App\Entity\Profile\Profile;
  7. use App\Entity\User;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. use Twig\Extension\AbstractExtension;
  10. use Twig\TwigFunction;
  11. class UserExtension extends AbstractExtension
  12. {
  13.     public function __construct(
  14.         private TokenStorageInterface $tokenStorage
  15.     ) {}
  16.     public function getFunctions()
  17.     {
  18.         return [
  19.             new TwigFunction('user_avatar', [$this'getUserAvatar']),
  20.             new TwigFunction('is_profile_in_favourites', [$this'isProfileInFavourites']),
  21.             new TwigFunction('is_user_advertiser', [$this'isUserAdvertiser']),
  22.             new TwigFunction('is_user_customer', [$this'isUserCustomer']),
  23.         ];
  24.     }
  25.     public function getUserAvatar(): ?Avatar
  26.     {
  27.         /** @var User $user */
  28.         $user $this->tokenStorage->getToken()->getUser();
  29.         if(!($user instanceof User)) {
  30.             return null;
  31.         }
  32.         return $user->getAvatar() ? $user->getAvatar() : null;
  33.     }
  34.     public function isProfileInFavourites(Profile $profile): bool
  35.     {
  36.         /** @var User $user */
  37.         $user $this->tokenStorage->getToken()->getUser();
  38.         if(!($user instanceof Customer)) {
  39.             return false;
  40.         }
  41.         return $user->findProfileInFavourites($profile) != null;
  42.     }
  43.     public function isUserAdvertiser($user): ?string
  44.     {
  45.         return $user instanceof Advertiser;
  46.     }
  47.     public function isUserCustomer($user): ?string
  48.     {
  49.         return $user instanceof Customer;
  50.     }
  51. }