<?php declare(strict_types=1);
namespace Shopware\B2B\StoreFrontAuthentication\Framework;
use RuntimeException;
use Shopware\B2B\Common\IdValue;
class AuthenticationService
{
/**
* @var AuthStorageAdapterInterface
*/
private $authStorageAdapter;
/**
* @var StoreFrontAuthenticationRepository
*/
private $authenticationRepository;
/**
* @var IdentityChainIdentityLoader
*/
private $identityChainRepository;
/**
* @var LoginContextService
*/
private $loginContextService;
public function __construct(
AuthStorageAdapterInterface $authStorageAdapter,
StoreFrontAuthenticationRepository $authenticationRepository,
IdentityChainIdentityLoader $identityChainRepository,
LoginContextService $loginContextService
) {
$this->authStorageAdapter = $authStorageAdapter;
$this->authenticationRepository = $authenticationRepository;
$this->identityChainRepository = $identityChainRepository;
$this->loginContextService = $loginContextService;
}
public function getIdentity(): Identity
{
if (!$this->isAuthenticated()) {
throw new NotAuthenticatedException('Not authenticated, can not provide a valid identity.');
}
return $this->authStorageAdapter->getIdentity();
}
public function isAuthenticated(): bool
{
return $this->authStorageAdapter->isAuthenticated();
}
public function isB2b(): bool
{
try {
$this->getIdentity();
} catch (NotAuthenticatedException | NoIdentitySetException | RuntimeException $e) {
return false;
}
return true;
}
public function is($className): bool
{
if (!$this->isB2b()) {
return false;
}
return $this->getIdentity() instanceof $className;
}
public function getIdentityByAuthId(IdValue $authId): Identity
{
$auth = $this->authenticationRepository
->fetchAuthenticationById($authId);
return $this->identityChainRepository
->fetchIdentityByAuthentication($auth, $this->loginContextService);
}
}