src/util/DataStoreComponentTrait.php
<?php
declare(strict_types=1);
namespace knotlib\datastoreservices\util;
use Psr\Container\ContainerInterface as PsrContainerInterface;
use knotlib\datastoreservices\DI;
use knotlib\services\exception\ComponentNotFoundException;
use knotlib\services\exception\ComponentNotImplementedException;
use knotlib\datastore\storage\database\Database;
use knotlib\datastore\storage\database\DatabaseConnection;
use knotlib\datastore\storage\database\DatabaseStorage;
trait DataStoreComponentTrait
{
/**
* Get database component defined in DI container
*
* @param PsrContainerInterface $container
*
* @return Database
*
* @throws ComponentNotFoundException
* @throws ComponentNotImplementedException
*/
public function getDatabase(PsrContainerInterface $container) : Database
{
$uri = DI::URI_COMPONENT_DATABASE;
$component = $container->get($uri);
if (!$component){
throw new ComponentNotFoundException('DI component not found: ' . $uri);
}
if (!($component instanceof Database)){
throw new ComponentNotImplementedException($uri, Database::class);
}
return $component;
}
/**
* Get storage component defined in DI container
*
* @param PsrContainerInterface $container
* @param string $connection_name
*
* @return DatabaseStorage
*
* @throws ComponentNotFoundException
* @throws ComponentNotImplementedException
*/
public function getStorage(PsrContainerInterface $container, string $connection_name = 'default') : DatabaseStorage
{
$uri = sprintf(DI::URI_COMPONENT_STORAGE, $connection_name);
$component = $container->get($uri);
if (!$component){
throw new ComponentNotFoundException('DI component not found: ' . $uri);
}
if (!($component instanceof DatabaseStorage)){
throw new ComponentNotImplementedException($uri, Database::class);
}
return $component;
}
/**
* Get connection component defined in DI container
*
* @param PsrContainerInterface $container
* @param string $connection_name
*
* @return DatabaseConnection
*
* @throws ComponentNotFoundException
* @throws ComponentNotImplementedException
*/
public function getConnection(PsrContainerInterface $container, string $connection_name = 'default') : DatabaseConnection
{
$uri = sprintf(DI::URI_COMPONENT_CONNECTION, $connection_name);
$component = $container->get($uri);
if (!$component){
throw new ComponentNotFoundException('DI component not found: ' . $uri);
}
if (!($component instanceof DatabaseConnection)){
throw new ComponentNotImplementedException($uri, DatabaseConnection::class);
}
return $component;
}
}