|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Silverback API Components Bundle Project |
| 5 | + * |
| 6 | + * (c) Daniel West <daniel@silverback.is> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Silverback\ApiComponentsBundle\Tests\Repository\User; |
| 13 | + |
| 14 | +use Doctrine\ORM\NonUniqueResultException; |
| 15 | +use PHPUnit\Framework\Attributes\DataProvider; |
| 16 | +use PHPUnit\Framework\TestCase; |
| 17 | +use Silverback\ApiComponentsBundle\Entity\User\AbstractUser; |
| 18 | +use Silverback\ApiComponentsBundle\Repository\User\FindUserByUsernameTrait; |
| 19 | +use Silverback\ApiComponentsBundle\Repository\User\UserRepositoryInterface; |
| 20 | +use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\User; |
| 21 | + |
| 22 | +final class FindUserByUsernameTraitTest extends TestCase |
| 23 | +{ |
| 24 | + /** |
| 25 | + * @return iterable<string, array{string, string, bool}> |
| 26 | + */ |
| 27 | + public static function usernames(): iterable |
| 28 | + { |
| 29 | + yield 'the username' => ['my_username', 'my_username', true]; |
| 30 | + yield 'the username in capitals with surrounding space' => ['my_username', ' MY_USERNAME ', true]; |
| 31 | + yield 'a username stored in capitals' => ['My_Username', 'my_username', true]; |
| 32 | + yield 'the email address the identifier also matches' => ['my_username', 'user@example.com', false]; |
| 33 | + } |
| 34 | + |
| 35 | + #[DataProvider('usernames')] |
| 36 | + public function test_only_the_users_own_username_finds_them(string $storedUsername, string $username, bool $found): void |
| 37 | + { |
| 38 | + $user = new User($storedUsername, 'user@example.com'); |
| 39 | + $repository = $this->createStub(UserRepositoryInterface::class); |
| 40 | + $repository->method('loadUserByIdentifier')->willReturn($user); |
| 41 | + |
| 42 | + self::assertSame($found ? $user : null, $this->finder()->find($repository, $username)); |
| 43 | + } |
| 44 | + |
| 45 | + public function test_a_username_matching_several_users_finds_none(): void |
| 46 | + { |
| 47 | + $repository = $this->createStub(UserRepositoryInterface::class); |
| 48 | + $repository->method('loadUserByIdentifier')->willThrowException(new NonUniqueResultException()); |
| 49 | + |
| 50 | + self::assertNull($this->finder()->find($repository, 'my_username')); |
| 51 | + } |
| 52 | + |
| 53 | + private function finder(): object |
| 54 | + { |
| 55 | + return new class { |
| 56 | + use FindUserByUsernameTrait; |
| 57 | + |
| 58 | + public function find(UserRepositoryInterface $repository, string $username): ?AbstractUser |
| 59 | + { |
| 60 | + return $this->findUserByUsernameIn($repository, $username); |
| 61 | + } |
| 62 | + }; |
| 63 | + } |
| 64 | +} |
0 commit comments