57 lines
		
	
	
	
		
			1.5 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			57 lines
		
	
	
	
		
			1.5 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
<?php
 | 
						|
 | 
						|
namespace Nest\Database;
 | 
						|
 | 
						|
use Nest\Application;
 | 
						|
use Nest\Database\Configuration\DatabasesConfiguration;
 | 
						|
use Nest\Database\Exceptions\Configuration\MissingRequiredConfigurationValueException;
 | 
						|
use Nest\Database\Exceptions\UnknownDatabaseException;
 | 
						|
 | 
						|
/**
 | 
						|
 * Databases manager.
 | 
						|
 */
 | 
						|
class Databases
 | 
						|
{
 | 
						|
	/**
 | 
						|
	 * Loaded databases.
 | 
						|
	 * @var array<string, Database>
 | 
						|
	 */
 | 
						|
	private array $databases;
 | 
						|
 | 
						|
	/**
 | 
						|
	 * @param Application $application Application of the databases.
 | 
						|
	 * @param DatabasesConfiguration $configuration Configuration of the databases.
 | 
						|
	 * @throws MissingRequiredConfigurationValueException
 | 
						|
	 */
 | 
						|
	public function __construct(protected Application $application, protected DatabasesConfiguration $configuration)
 | 
						|
	{
 | 
						|
		$this->load();
 | 
						|
	}
 | 
						|
 | 
						|
	/**
 | 
						|
	 * Load databases from their factories.
 | 
						|
	 * @return void
 | 
						|
	 * @throws MissingRequiredConfigurationValueException
 | 
						|
	 */
 | 
						|
	public function load(): void
 | 
						|
	{
 | 
						|
		foreach ($this->configuration->getFactories() as $identifier => $databaseFactory)
 | 
						|
		{ // Load all databases from their factories.
 | 
						|
			$this->databases[$identifier] = $databaseFactory->make();
 | 
						|
		}
 | 
						|
	}
 | 
						|
 | 
						|
	/**
 | 
						|
	 * @param string $identifier Database identifier.
 | 
						|
	 * @return Database Database corresponding to the given identifier.
 | 
						|
	 * @throws UnknownDatabaseException
 | 
						|
	 */
 | 
						|
	public function db(string $identifier): Database
 | 
						|
	{
 | 
						|
		if (empty($this->databases[$identifier]))
 | 
						|
			// Cannot find a database with this identifier, throwing an exception.
 | 
						|
			throw new UnknownDatabaseException($identifier);
 | 
						|
 | 
						|
		return $this->databases[$identifier]; // Return loaded database.
 | 
						|
	}
 | 
						|
}
 |