src/util/DataStoreServiceTrait.php
<?php
declare(strict_types=1);
namespace knotlib\datastoreservices\util;
use Psr\Container\ContainerInterface as PsrContainerInterface;
use knotlib\datastoreservices\DI;
use knotlib\services\exception\ServiceNotFoundException;
use knotlib\services\exception\ServiceNotImplementedException;
use knotlib\datastoreservices\RepositoryService;
use knotlib\datastoreservices\TransactionService;
use knotlib\datastoreservices\ConnectionService;
trait DataStoreServiceTrait
{
/**
* Get repository service defined in DI container
*
* @param PsrContainerInterface $container
*
* @return RepositoryService
*
* @throws ServiceNotFoundException
* @throws ServiceNotImplementedException
*/
public function getRepositoryService(PsrContainerInterface $container) : RepositoryService
{
$uri = DI::URI_SERVICE_REPOSITORY;
$service = $container->get($uri);
if (!$service){
throw new ServiceNotFoundException($uri);
}
if (!($service instanceof RepositoryService)){
throw new ServiceNotImplementedException($uri, RepositoryService::class);
}
return $service;
}
/**
* Get transaction service defined in DI container
*
* @param PsrContainerInterface $container
* @param string $connection_name
*
* @return TransactionService
*
* @throws ServiceNotFoundException
* @throws ServiceNotImplementedException
*/
public function getTransactionService(PsrContainerInterface $container, string $connection_name = 'default') : TransactionService
{
$uri = sprintf(DI::URI_SERVICE_TRANSACTION, $connection_name);
$service = $container->get($uri);
if (!$service){
throw new ServiceNotFoundException($uri);
}
if (!($service instanceof TransactionService)){
throw new ServiceNotImplementedException($uri, TransactionService::class);
}
return $service;
}
/**
* Get connection service defined in DI container
*
* @param PsrContainerInterface $container
* @param string $connection_name
*
* @return ConnectionService
*
* @throws ServiceNotFoundException
* @throws ServiceNotImplementedException
*/
public function getConnectionService(PsrContainerInterface $container, string $connection_name = 'default') : ConnectionService
{
$uri = sprintf(DI::URI_SERVICE_CONNECTION, $connection_name);
$service = $container->get($uri);
if (!$service){
throw new ServiceNotFoundException($uri);
}
if (!($service instanceof ConnectionService)){
throw new ServiceNotImplementedException($uri, ConnectionService::class);
}
return $service;
}
}