|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Sherlockode\SyliusAdvancedContentPlugin\User; |
| 4 | + |
| 5 | +use Sherlockode\AdvancedContentBundle\User\AnonymousUserProvider; |
| 6 | +use Sylius\Component\Core\Model\AdminUserInterface; |
| 7 | +use Sylius\Component\User\Repository\UserRepositoryInterface; |
| 8 | +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; |
| 9 | +use Symfony\Contracts\Translation\TranslatorInterface; |
| 10 | + |
| 11 | +class AdminUserProvider extends AnonymousUserProvider |
| 12 | +{ |
| 13 | + /** |
| 14 | + * @var TokenStorageInterface |
| 15 | + */ |
| 16 | + private $tokenStorage; |
| 17 | + |
| 18 | + /** |
| 19 | + * @var UserRepositoryInterface |
| 20 | + */ |
| 21 | + private $userRepository; |
| 22 | + |
| 23 | + /** |
| 24 | + * @param TranslatorInterface $translator |
| 25 | + * @param TokenStorageInterface $tokenStorage |
| 26 | + * @param UserRepositoryInterface $userRepository |
| 27 | + */ |
| 28 | + public function __construct( |
| 29 | + TranslatorInterface $translator, |
| 30 | + TokenStorageInterface $tokenStorage, |
| 31 | + UserRepositoryInterface $userRepository |
| 32 | + ) { |
| 33 | + parent::__construct($translator); |
| 34 | + |
| 35 | + $this->tokenStorage = $tokenStorage; |
| 36 | + $this->userRepository = $userRepository; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * @return int|null |
| 41 | + */ |
| 42 | + public function getUserId(): ?int |
| 43 | + { |
| 44 | + $token = $this->tokenStorage->getToken(); |
| 45 | + if ($token === null) { |
| 46 | + return null; |
| 47 | + } |
| 48 | + |
| 49 | + $user = $token->getUser(); |
| 50 | + if ($user === null) { |
| 51 | + return null; |
| 52 | + } |
| 53 | + |
| 54 | + return $user->getId(); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * @param int|null $userId |
| 59 | + * |
| 60 | + * @return string |
| 61 | + */ |
| 62 | + public function getUserName(?int $userId): string |
| 63 | + { |
| 64 | + if ($userId === null) { |
| 65 | + return parent::getUserName($userId); |
| 66 | + } |
| 67 | + |
| 68 | + $user = $this->userRepository->find($userId); |
| 69 | + if ($user === null) { |
| 70 | + return parent::getUserName($userId); |
| 71 | + } |
| 72 | + |
| 73 | + if (!$user instanceof AdminUserInterface) { |
| 74 | + return $user->getUsername(); |
| 75 | + } |
| 76 | + |
| 77 | + return $user->getFirstName() . ' ' . $user->getLastName(); |
| 78 | + } |
| 79 | +} |
0 commit comments