public function testUsernameIsUniqueSpecification() { $user = $this->prepareUser(); $this->specify("Set username for new user with existing username", function () use($user) { $userRepository = Stub::makeEmpty('Inoplate\\Account\\Domain\\Repositories\\User', ['findByUsername' => Stub::atLeastOnce(function () use($user) { return $user; })], $this); $specification = new AccountDomainSpecifications\UsernameIsUnique($userRepository); expect("Specification is not satisfied", $specification->isSatisfiedBy($user->username()))->false(); }); $this->specify("Set username for existing user with another existing user's username", function () use($user) { $userRepository = Stub::makeEmpty('Inoplate\\Account\\Domain\\Repositories\\User', ['findByUsername' => Stub::atLeastOnce(function () use($user) { return $user; })], $this); $specification = new AccountDomainSpecifications\UsernameIsUnique($userRepository, new AccountDomainModels\UserId('56678')); expect("Specification is not satisfied", $specification->isSatisfiedBy($user->username()))->false(); }); $this->specify("Set username for existing user with same username", function () use($user) { $userRepository = Stub::makeEmpty('Inoplate\\Account\\Domain\\Repositories\\User', ['findByUsername' => Stub::atLeastOnce(function () use($user) { return $user; })], $this); $specification = new AccountDomainSpecifications\UsernameIsUnique($userRepository, new AccountDomainModels\UserId('123456')); expect("Specification is satisfied", $specification->isSatisfiedBy($user->username()))->true(); }); $this->specify("Set username for new user with new username", function () use($user) { $userRepository = Stub::makeEmpty('Inoplate\\Account\\Domain\\Repositories\\User', ['findByUsername' => Stub::atLeastOnce(function () use($user) { return null; })], $this); $specification = new AccountDomainSpecifications\UsernameIsUnique($userRepository); expect("Specification is satisfied", $specification->isSatisfiedBy($user->username()))->true(); }); }
/** * Ensure username is unique * * @param AccountDomainModels\Username $username * @return void */ protected function ensureUsernameIsUnique(AccountDomainModels\Username $username) { $specification = new AccountDomainSpecifications\UsernameIsUnique($this->userRepository); if (!$specification->isSatisfiedBy($username)) { throw new ValueIsNotUniqueException("Username [{$username->value}()] was already taken"); } }