Container refactoring

This commit is contained in:
Sergio Brighenti 2019-11-19 12:32:58 +01:00
parent 399901c7a8
commit cb86a32d80
8 changed files with 133 additions and 170 deletions

View file

@ -61,8 +61,7 @@ class ViewFactory
$twig->addGlobal('config', $config);
$twig->addGlobal('request', $request);
$twig->addGlobal('alerts', $container->get('session')->getAlert());
$twig->addGlobal('session', $container->get('session')->all());
$twig->addGlobal('session', $container->get('session'));
$twig->addGlobal('PLATFORM_VERSION', PLATFORM_VERSION);
return new View($twig);

View file

@ -24,8 +24,7 @@ if ($config['db']['connection'] === 'sqlite' && !file_exists(__DIR__.'/../'.$con
$firstMigrate = true;
}
$dsn = $config['db']['connection'] === 'sqlite' ? __DIR__.'/../'.$config['db']['dsn'] : $config['db']['dsn'];
$db = new DB($config['db']['connection'].':'.$dsn, $config['db']['username'], $config['db']['password']);
$db = new DB(dsnFromConfig($config), $config['db']['username'], $config['db']['password']);
$migrator = new Migrator($db, 'resources/schemas', $firstMigrate);
$migrator->migrate();

View file

@ -1,31 +1,18 @@
<?php
use App\Database\DB;
use App\Exception\Handlers\AppErrorHandler;
use App\Exception\Handlers\Renderers\HtmlErrorRenderer;
use App\Factories\ViewFactory;
use App\Middleware\InjectMiddleware;
use App\Middleware\RememberMiddleware;
use App\Web\Lang;
use App\Web\Session;
use Aws\S3\S3Client;
use App\Web\View;
use DI\Bridge\Slim\Bridge;
use DI\ContainerBuilder;
use Google\Cloud\Storage\StorageClient;
use League\Flysystem\Adapter\Ftp as FtpAdapter;
use League\Flysystem\Adapter\Local;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Filesystem;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Psr\Container\ContainerInterface as Container;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Spatie\Dropbox\Client as DropboxClient;
use Spatie\FlysystemDropbox\DropboxAdapter;
use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter;
use function DI\factory;
use function DI\get;
use function DI\value;
if (!file_exists('config.php') && is_dir('install/')) {
@ -61,89 +48,19 @@ if (!$config['debug']) {
$builder->enableCompilation(BASE_DIR.'/resources/cache/di/');
$builder->writeProxiesToFile(true, BASE_DIR.'/resources/cache/proxies');
}
$builder->addDefinitions([
'config' => value($config),
'logger' => factory(function () {
$logger = new Logger('app');
$streamHandler = new RotatingFileHandler(BASE_DIR.'logs/log.txt', 10, Logger::DEBUG);
$lineFormatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", "Y-m-d H:i:s");
$lineFormatter->includeStacktraces(true);
$streamHandler->setFormatter($lineFormatter);
$logger->pushHandler($streamHandler);
return $logger;
}),
'session' => factory(function () {
return new Session('xbackbone_session', BASE_DIR.'resources/sessions');
}),
'database' => factory(function (Container $container) {
$config = $container->get('config');
return new DB(dsnFromConfig($config), $config['db']['username'], $config['db']['password']);
}),
'storage' => factory(function (Container $container) {
$config = $container->get('config');
switch ($config['storage']['driver']) {
case 'local':
return new Filesystem(new Local($config['storage']['path']));
case 's3':
$client = new S3Client([
'credentials' => [
'key' => $config['storage']['key'],
'secret' => $config['storage']['secret'],
],
'region' => $config['storage']['region'],
'version' => 'latest',
]);
return new Filesystem(new AwsS3Adapter($client, $config['storage']['bucket'], $config['storage']['path']));
case 'dropbox':
$client = new DropboxClient($config['storage']['token']);
return new Filesystem(new DropboxAdapter($client), ['case_sensitive' => false]);
case 'ftp':
return new Filesystem(new FtpAdapter([
'host' => $config['storage']['host'],
'username' => $config['storage']['username'],
'password' => $config['storage']['password'],
'port' => $config['storage']['port'],
'root' => $config['storage']['path'],
'passive' => $config['storage']['passive'],
'ssl' => $config['storage']['ssl'],
'timeout' => 30,
]));
case 'google-cloud':
$client = new StorageClient([
'projectId' => $config['storage']['project_id'],
'keyFilePath' => $config['storage']['key_path'],
]);
return new Filesystem(new GoogleStorageAdapter($client, $client->bucket($config['storage']['bucket'])));
default:
throw new InvalidArgumentException('The driver specified is not supported.');
}
}),
'lang' => factory(function (Container $container) {
$config = $container->get('config');
if (isset($config['lang'])) {
return Lang::build($config['lang'], BASE_DIR.'resources/lang/');
}
return Lang::build(Lang::recognize(), BASE_DIR.'resources/lang/');
}),
'view' => factory(function (Container $container) {
View::class => factory(function (Container $container) {
return ViewFactory::createAppInstance($container);
}),
'view' => get(View::class),
]);
$builder->addDefinitions(__DIR__.'/container.php');
$app = Bridge::create($builder->build());
$app->setBasePath(parse_url($config['base_url'], PHP_URL_PATH));
$app->setBasePath(parse_url($config['base_url'], PHP_URL_PATH) ?: '');
if (!$config['debug']) {
$app->getRouteCollector()->setCacheFile(BASE_DIR.'resources/cache/routes.cache.php');

102
bootstrap/container.php Normal file
View file

@ -0,0 +1,102 @@
<?php
use App\Database\DB;
use App\Factories\ViewFactory;
use App\Web\Lang;
use App\Web\Session;
use App\Web\View;
use Aws\S3\S3Client;
use Google\Cloud\Storage\StorageClient;
use League\Flysystem\Adapter\Ftp as FtpAdapter;
use League\Flysystem\Adapter\Local;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Filesystem;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Psr\Container\ContainerInterface as Container;
use Spatie\Dropbox\Client as DropboxClient;
use Spatie\FlysystemDropbox\DropboxAdapter;
use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter;
use function DI\factory;
use function DI\get;
return [
Logger::class => factory(function () {
$logger = new Logger('app');
$streamHandler = new RotatingFileHandler(BASE_DIR.'logs/log.txt', 10, Logger::DEBUG);
$lineFormatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", "Y-m-d H:i:s");
$lineFormatter->includeStacktraces(true);
$streamHandler->setFormatter($lineFormatter);
$logger->pushHandler($streamHandler);
return $logger;
}),
'logger' => get(Logger::class),
Session::class => factory(function () {
return new Session('xbackbone_session', BASE_DIR.'resources/sessions');
}),
'session' => get(Session::class),
DB::class => factory(function (Container $container) {
$config = $container->get('config');
return new DB(dsnFromConfig($config), $config['db']['username'], $config['db']['password']);
}),
'database' => get(DB::class),
Filesystem::class => factory(function (Container $container) {
$config = $container->get('config');
switch ($config['storage']['driver']) {
case 'local':
return new Filesystem(new Local($config['storage']['path']));
case 's3':
$client = new S3Client([
'credentials' => [
'key' => $config['storage']['key'],
'secret' => $config['storage']['secret'],
],
'region' => $config['storage']['region'],
'version' => 'latest',
]);
return new Filesystem(new AwsS3Adapter($client, $config['storage']['bucket'], $config['storage']['path']));
case 'dropbox':
$client = new DropboxClient($config['storage']['token']);
return new Filesystem(new DropboxAdapter($client), ['case_sensitive' => false]);
case 'ftp':
return new Filesystem(new FtpAdapter([
'host' => $config['storage']['host'],
'username' => $config['storage']['username'],
'password' => $config['storage']['password'],
'port' => $config['storage']['port'],
'root' => $config['storage']['path'],
'passive' => $config['storage']['passive'],
'ssl' => $config['storage']['ssl'],
'timeout' => 30,
]));
case 'google-cloud':
$client = new StorageClient([
'projectId' => $config['storage']['project_id'],
'keyFilePath' => $config['storage']['key_path'],
]);
return new Filesystem(new GoogleStorageAdapter($client, $client->bucket($config['storage']['bucket'])));
default:
throw new InvalidArgumentException('The driver specified is not supported.');
}
}),
'storage' => get(Filesystem::class),
Lang::class => factory(function (Container $container) {
$config = $container->get('config');
if (isset($config['lang'])) {
return Lang::build($config['lang'], BASE_DIR.'resources/lang/');
}
return Lang::build(Lang::recognize(), BASE_DIR.'resources/lang/');
}),
'lang' => get(Lang::class),
];

View file

@ -1,6 +1,6 @@
{
"name": "sergix44/xbackbone",
"version": "3.0",
"version": "3.0.RC3",
"description": "A lightweight ShareX PHP backend",
"type": "project",
"require": {

31
composer.lock generated
View file

@ -1862,15 +1862,15 @@
"authors": [
{
"name": "Freek Van der Herten",
"role": "Developer",
"email": "freek@spatie.be",
"homepage": "https://spatie.be"
"homepage": "https://spatie.be",
"role": "Developer"
},
{
"name": "Alex Vanderbist",
"role": "Developer",
"email": "alex.vanderbist@gmail.com",
"homepage": "https://spatie.be"
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "A minimal implementation of Dropbox API v2",
@ -2901,35 +2901,34 @@
},
{
"name": "ocramius/package-versions",
"version": "1.5.1",
"version": "1.4.2",
"source": {
"type": "git",
"url": "https://github.com/Ocramius/PackageVersions.git",
"reference": "1d32342b8c1eb27353c8887c366147b4c2da673c"
"reference": "44af6f3a2e2e04f2af46bcb302ad9600cba41c7d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Ocramius/PackageVersions/zipball/1d32342b8c1eb27353c8887c366147b4c2da673c",
"reference": "1d32342b8c1eb27353c8887c366147b4c2da673c",
"url": "https://api.github.com/repos/Ocramius/PackageVersions/zipball/44af6f3a2e2e04f2af46bcb302ad9600cba41c7d",
"reference": "44af6f3a2e2e04f2af46bcb302ad9600cba41c7d",
"shasum": ""
},
"require": {
"composer-plugin-api": "^1.0.0",
"php": "^7.3.0"
"php": "^7.1.0"
},
"require-dev": {
"composer/composer": "^1.8.6",
"doctrine/coding-standard": "^6.0.0",
"composer/composer": "^1.6.3",
"doctrine/coding-standard": "^5.0.1",
"ext-zip": "*",
"infection/infection": "^0.13.4",
"phpunit/phpunit": "^8.2.5",
"vimeo/psalm": "^3.4.9"
"infection/infection": "^0.7.1",
"phpunit/phpunit": "^7.5.17"
},
"type": "composer-plugin",
"extra": {
"class": "PackageVersions\\Installer",
"branch-alias": {
"dev-master": "1.6.x-dev"
"dev-master": "2.0.x-dev"
}
},
"autoload": {
@ -2948,7 +2947,7 @@
}
],
"description": "Composer plugin that provides efficient querying for installed package versions (no runtime IO)",
"time": "2019-07-17T15:49:50+00:00"
"time": "2019-11-15T16:17:10+00:00"
},
{
"name": "phpstan/phpdoc-parser",

View file

@ -7,21 +7,13 @@ use App\Database\Migrator;
use App\Factories\ViewFactory;
use App\Web\Session;
use App\Web\View;
use Aws\S3\S3Client;
use DI\Bridge\Slim\Bridge;
use DI\ContainerBuilder;
use Google\Cloud\Storage\StorageClient;
use League\Flysystem\Adapter\Ftp as FtpAdapter;
use League\Flysystem\Adapter\Local;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\FileExistsException;
use League\Flysystem\Filesystem;
use Psr\Container\ContainerInterface as Container;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Spatie\Dropbox\Client as DropboxClient;
use Spatie\FlysystemDropbox\DropboxAdapter;
use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter;
use function DI\factory;
use function DI\get;
use function DI\value;
@ -53,57 +45,12 @@ $builder = new ContainerBuilder();
$builder->addDefinitions([
'config' => value($config),
Session::class => factory(function () {
return new Session('xbackbone_session');
}),
'session' => get(Session::class),
Filesystem::class => factory(function (Container $container) {
$config = $container->get('config');
switch ($config['storage']['driver']) {
case 'local':
return new Filesystem(new Local($config['storage']['path']));
case 's3':
$client = new S3Client([
'credentials' => [
'key' => $config['storage']['key'],
'secret' => $config['storage']['secret'],
],
'region' => $config['storage']['region'],
'version' => 'latest',
]);
return new Filesystem(new AwsS3Adapter($client, $config['storage']['bucket'], $config['storage']['path']));
case 'dropbox':
$client = new DropboxClient($config['storage']['token']);
return new Filesystem(new DropboxAdapter($client), ['case_sensitive' => false]);
case 'ftp':
return new Filesystem(new FtpAdapter([
'host' => $config['storage']['host'],
'username' => $config['storage']['username'],
'password' => $config['storage']['password'],
'port' => $config['storage']['port'],
'root' => $config['storage']['path'],
'passive' => $config['storage']['passive'],
'ssl' => $config['storage']['ssl'],
'timeout' => 30,
]));
case 'google-cloud':
$client = new StorageClient([
'projectId' => $config['storage']['project_id'],
'keyFilePath' => $config['storage']['key_path'],
]);
return new Filesystem(new GoogleStorageAdapter($client, $client->bucket($config['storage']['bucket'])));
default:
throw new InvalidArgumentException('The driver specified is not supported.');
}
}),
View::class => factory(function ($container) {
View::class => factory(function (Container $container) {
return ViewFactory::createInstallerInstance($container);
}),
'view' => get(View::class),
]);
$builder->addDefinitions(__DIR__.'/../bootstrap/container.php');
$app = Bridge::create($builder->build());
$app->setBasePath(parse_url($config['base_url'].'/install', PHP_URL_PATH));
@ -142,7 +89,7 @@ $app->get('/', function (Response $response, View $view, Session $session) use (
$installed = file_exists(__DIR__.'/../config.php');
return $view->render($response, 'install.twig', [
'installed' => $installed
'installed' => $installed,
]);
})->setName('install');

View file

@ -14,7 +14,7 @@
<script src="../static/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="installer.js"></script>
</head>
<body>
<body class="bg-light">
<div class="container">
<div class="mt-4">
{% include 'comp/alert.twig' %}