Skip to content

Commit

Permalink
psalm optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
ProklUng committed Jan 13, 2022
1 parent 58d3ca2 commit 2e34c73
Show file tree
Hide file tree
Showing 11 changed files with 45 additions and 19 deletions.
8 changes: 4 additions & 4 deletions functions/container.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
*
* @param string|object $classContainer Класс контейнера.
*
* @return Container
* @return ContainerInterface
*
* @since 21.03.2021 Класс (или объект) контейнера как параметр.
*/
Expand All @@ -30,13 +30,13 @@ function container($classContainer = ServiceProvider::class)
/**
* Экземпляр манипулятора с делегированными контейнерами.
*
* @return ContainerInterface|null
* @return null|object
*
* @throws Exception
* @throws Exception Ошибки инициализации контейнера.
*
* @since 30.07.2021
*/
function delegatedContainer() : ?ContainerInterface
function delegatedContainer() : ?object
{
return container()->get('delegated_container_manipulator');
}
Expand Down
1 change: 0 additions & 1 deletion psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
allowStringToStandInForClass="true"
allowCoercionFromStringToClassConst="true"
findUnusedPsalmSuppress="true"
skipChecksOnUnresolvableIncludes="true"
>
Expand Down
9 changes: 7 additions & 2 deletions src/Micro/AbstractStandaloneServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Exception;
use Prokl\ServiceProvider\Framework\SymfonyCompilerPassBagLight;
use Prokl\ServiceProvider\ServiceProvider;
use Psr\Container\ContainerInterface;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;

Expand All @@ -18,7 +19,7 @@
class AbstractStandaloneServiceProvider extends ServiceProvider
{
/**
* @var ContainerBuilder $containerBuilder Контейнер.
* @var ContainerBuilder|ContainerInterface $containerBuilder Контейнер.
*/
protected static $containerBuilder;

Expand All @@ -28,7 +29,11 @@ class AbstractStandaloneServiceProvider extends ServiceProvider
protected $standartCompilerPasses;

/**
* @inheritDoc
* @param string $filename Имя файла.
* @param string|null $pathBundlesConfig Путь к файлу с конфигурацией бандлов.
*
* @throws Exception
* @psalm-suppress ConstructorSignatureMismatch
*/
public function __construct(
string $filename,
Expand Down
3 changes: 2 additions & 1 deletion src/Micro/ExampleMicroServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Prokl\ServiceProvider\Micro;

use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
Expand All @@ -15,7 +16,7 @@
class ExampleMicroServiceProvider extends AbstractStandaloneServiceProvider
{
/**
* @var ContainerBuilder $containerBuilder Контейнер.
* @var ContainerBuilder|ContainerInterface $containerBuilder Контейнер.
*/
protected static $containerBuilder;

Expand Down
23 changes: 17 additions & 6 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
use Prokl\ServiceProvider\Services\AppKernel;
use Prokl\ServiceProvider\Utils\ErrorScreen;
use Prokl\ServiceProvider\Utils\Loaders\PhpLoaderSettingsBitrix;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\ContainerInterface as PsrContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use RuntimeException;
use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper;
use Symfony\Component\Config\ConfigCache;
Expand Down Expand Up @@ -85,7 +87,7 @@ class ServiceProvider
private const CONFIG_EXTS = '.{php,xml,yaml,yml}';

/**
* @var ContainerBuilder $containerBuilder Контейнер.
* @var ContainerBuilder|ContainerInterface $containerBuilder Контейнер.
*/
protected static $containerBuilder;

Expand Down Expand Up @@ -197,6 +199,7 @@ public function __construct(

$this->filename = $filename;

/** @psalm-suppress RedundantConditionGivenDocblockType */
if (static::$containerBuilder !== null) {
return;
}
Expand Down Expand Up @@ -231,10 +234,12 @@ public function get(string $id)
/**
* Контейнер.
*
* @return ContainerInterface
* @return ContainerInterface|null
* @throws Exception Ошибки инициализации контейнера.
*/
public function container() : ContainerInterface
public function container() : ?ContainerInterface
{
/** @psalm-suppress RedundantConditionGivenDocblockType */
return static::$containerBuilder ?: $this->initContainer($this->filename);
}

Expand Down Expand Up @@ -270,6 +275,7 @@ public function reboot() : void
*/
public function shutdown() : void
{
/** @psalm-suppress DocblockTypeContradiction */
if (static::$containerBuilder === null) {
return;
}
Expand Down Expand Up @@ -340,15 +346,17 @@ private function boot() : void
*
* @param string $fileName Конфиг.
*
* @return ContainerBuilder|Container
* @return ContainerBuilder|Container|ContainerInterface
* @throws Exception Ошибки контейнера.
* @throws ContainerExceptionInterface | NotFoundExceptionInterface Ошибки контейнера.
*
* @since 28.09.2020 Доработка.
*/
private function initContainer(string $fileName)
{
// Если в dev режиме, то не компилировать контейнер.
if ((bool)$_ENV['DEBUG'] === true) {
/** @psalm-suppress RedundantConditionGivenDocblockType */
if (static::$containerBuilder !== null) {
return static::$containerBuilder;
}
Expand Down Expand Up @@ -465,6 +473,7 @@ private function dumpContainer(ConfigCache $cache, ContainerBuilder $container,
$asFiles = $container->getParameter('container.dumper.inline_factories');
}

/** @psalm-suppress ArgumentTypeCoercion */
$dumper = new PhpDumper(static::$containerBuilder);
if (class_exists(\ProxyManager\Configuration::class) && class_exists(ProxyDumper::class)) {
$dumper->setProxyDumper(new ProxyDumper());
Expand All @@ -476,6 +485,7 @@ private function dumpContainer(ConfigCache $cache, ContainerBuilder $container,
'file' => $cache->getPath(),
'as_files' => $asFiles,
'debug' => $this->debug,
/** @psalm-suppress PossiblyUndefinedMethod */
'build_time' => static::$containerBuilder->hasParameter('kernel.container_build_time')
? static::$containerBuilder->getParameter('kernel.container_build_time') : time(),
'preload_classes' => array_map('get_class', $this->bundles),
Expand Down Expand Up @@ -552,6 +562,7 @@ private function loadContainer(string $fileName)
$this->setDefaultParamsContainer();

// Дополнить переменные приложения сведениями о зарегистрированных бандлах.
/** @psalm-suppress PossiblyNullReference */
static::$containerBuilder->get('kernel')->registerStandaloneBundles();

// Инициализация автономных бандлов.
Expand Down Expand Up @@ -644,7 +655,7 @@ private function initialize(string $fileName): ?ContainerBuilder
$this->loadContainer($fileName);

$this->bundlesLoader->registerExtensions(static::$containerBuilder);

/** @psalm-suppress PossiblyUndefinedMethod */
static::$containerBuilder->compile(true);

// Boot bundles.
Expand All @@ -671,6 +682,7 @@ private function initialize(string $fileName): ?ContainerBuilder
*/
private function setDefaultParamsContainer() : void
{
/** @psalm-suppress PossiblyUndefinedMethod */
if (!static::$containerBuilder->hasDefinition('kernel')) {
$this->registerKernel($this->kernelServiceClass);
}
Expand Down Expand Up @@ -813,7 +825,6 @@ private function runPostLoadingPasses(): void
/**
* Отсортировать по приоритету.
*
* @psalm-suppress MissingClosureParamType
* @psalm-suppress InvalidScalarArgument
*/
usort($this->postLoadingPassesBag, static function ($a, $b) : bool {
Expand Down
3 changes: 3 additions & 0 deletions src/Services/AppKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ public function getLogDir()
*/
public function getProjectDir(): string
{
/** @psalm-suppress RedundantConditionGivenDocblockType */
/** @psalm-suppress DocblockTypeContradiction */
if ($this->projectDir === null) {
$this->projectDir = Application::getDocumentRoot();
}
Expand Down Expand Up @@ -201,6 +203,7 @@ public function setContainer(?ContainerInterface $container = null) : void
*/
public function getContainer()
{
/** @psalm-suppress DocblockTypeContradiction */
if (static::$kernelContainer === null) {
throw new LogicException('Cannot retrieve the container from a non-booted kernel.');
}
Expand Down
1 change: 1 addition & 0 deletions src/Services/PSR/PSR7/PsrResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ public function withBody(StreamInterface $body)
$newResponse = clone $this->response;
$newResponse->setContent($body);

/** @psalm-suppress ImplicitToStringCast */
return new static($newResponse, $this->httpVersion, $body);
}

Expand Down
1 change: 1 addition & 0 deletions src/Utils/DelegatedContainer/Manipulator.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public function get($id, int $invalidBehavior = self::EXCEPTION_ON_INVALID_REFER

/**
* @inheritdoc
* @psalm-suppress MissingParamType
*/
public function has($id)
{
Expand Down
8 changes: 4 additions & 4 deletions src/Utils/ErrorScreen.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,19 @@ public function __construct(
/**
* Показать экран смерти.
*
* @param string $message Сообщение об ошибке.
* @param string $errorMessage Сообщение об ошибке.
*
* @return boolean
*/
public function die(string $message = '') : ?bool
public function die(string $errorMessage = '') : ?bool
{
if (defined('PHPUNIT_COMPOSER_INSTALL') || defined('__PHPUNIT_PHAR__')) {
throw new RuntimeException(
$message
$errorMessage
);
}

$content = $this->prepareErrorScreen($message);
$content = $this->prepareErrorScreen($errorMessage);

$this->application->RestartBuffer();
echo $content;
Expand Down
4 changes: 4 additions & 0 deletions src/Utils/Loaders/PhpLoaderSettingsBitrix.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ public function load($resource, string $type = null)
return $this->loadBitrixConfig('services', true);
}, $this, ProtectedPhpFileLoader::class);

if (!$load) {
return;
}

try {
$settings = $load($path, $this->env);
if (is_array($settings)) {
Expand Down
3 changes: 2 additions & 1 deletion tests/Cases/fixtures/MicroServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Prokl\ServiceProvider\Micro\AbstractStandaloneServiceProvider;
use Prokl\ServiceProvider\Micro\ExampleAppKernel;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
Expand All @@ -17,7 +18,7 @@
class MicroServiceProvider extends AbstractStandaloneServiceProvider
{
/**
* @var ContainerBuilder $containerBuilder Контейнер.
* @var ContainerBuilder|ContainerInterface $containerBuilder Контейнер.
*/
protected static $containerBuilder;

Expand Down

0 comments on commit 2e34c73

Please sign in to comment.