Skip to content

Commit

Permalink
Merge pull request #81 from bearsunday/release
Browse files Browse the repository at this point in the history
Refactor (psalm: level3)
  • Loading branch information
koriym committed Jan 17, 2021
2 parents 7ee14a2 + c12c660 commit 9a27b9c
Show file tree
Hide file tree
Showing 49 changed files with 449 additions and 381 deletions.
45 changes: 26 additions & 19 deletions composer.json
Expand Up @@ -10,23 +10,20 @@
],
"require": {
"php": "^7.2 || ^8.0",
"bear/resource": "^1.x-dev",
"bear/sunday": "1.x-dev",
"bear/resource": "^1.15",
"bear/sunday": "^1.5",
"doctrine/annotations": "^1.8",
"doctrine/cache": "^1.10",
"mobiledetect/mobiledetectlib": "^2.8",
"ray/aop": "2.x-dev",
"ray/di": "2.x-dev"
},
"config": {
"sort-packages": true
"ray/aop": "^2.10",
"ray/di": "2.11"
},
"require-dev": {
"ext-redis": "*",
"bamarni/composer-bin-plugin": "^1.4",
"koriym/attributes": "^0.2",
"phpunit/phpunit": "^9.5",
"symfony/process": "^4.3"
"symfony/process": "^4.3",
"koriym/attributes": "^1.0",
"bamarni/composer-bin-plugin": "^1.4"
},
"autoload": {
"psr-4": {
Expand All @@ -45,19 +42,29 @@
"tests/Fake/fake-app/src"
]
},
"files": ["tests/Fake/Memcached.php", "tests/Fake/Redis.php", "tests/syslog.php"]
"files": [
"tests/Fake/Memcached.php",
"tests/Fake/Redis.php",
"tests/Fake/RedisException.php",
"tests/syslog.php"
]
},
"config": {
"sort-packages": true
},
"scripts" :{
"post-install-cmd": ["@composer bin all install --ansi"],
"post-update-cmd": ["@composer bin all update --ansi"],
"test": ["phpunit"],
"test": ["./vendor/bin/phpunit"],
"tests": ["@cs", "@sa", "@test"],
"sa": ["./vendor/bin/phpstan analyse -l max src tests -c phpstan.neon --no-progress", "psalm --show-info=false"],
"coverage": ["php -dzend_extension=xdebug.so ./vendor/bin/phpunit --coverage-text --coverage-html=build/coverage"],
"cs": ["./vendor/bin/phpcs --standard=./phpcs.xml src"],
"cs-fix": ["./vendor/bin/phpcbf src"],
"metrics": ["./vendor/bin/phpmetrics --report-html=build/metrics --exclude=Exception --log-junit=build/junit.xml --junit=build/junit.xml src"],
"build": ["@cs", "@sa", "@coverage", "@metrics"],
"baseline": ["phpstan analyse --configuration phpstan.neon src/ tests/ --generate-baseline", "vendor/bin/psalm --set-baseline=psalm.baseline.xml"]
"coverage": ["php -dzend_extension=xdebug.so -dxdebug.mode=coverage ./vendor/bin/phpunit --coverage-text --coverage-html=build/coverage"],
"pcov": ["php -dextension=pcov.so -d pcov.enabled=1 ./vendor/bin/phpunit --coverage-text --coverage-html=build/coverage --coverage-clover=coverage.xml"],
"cs": ["./vendor/bin/phpcs"],
"cs-fix": ["./vendor/bin/phpcbf src tests"],
"clean": ["./vendor/bin/phpstan clear-result-cache", "./vendor/bin/psalm --clear-cache", "rm -rf tests/tmp/*.php"],
"sa": ["./vendor/bin/phpstan analyse -c phpstan.neon", "psalm --show-info=true"],
"metrics": ["./vendor/bin/phpmetrics --report-html=build/metrics --exclude=Exception --junit=build/junit.xml src"],
"phpmd": ["./vendor/bin/phpmd --exclude src/Annotation src text ./phpmd.xml"],
"build": ["@cs", "@sa", "@pcov", "@metrics"]
}
}
89 changes: 73 additions & 16 deletions phpcs.xml
@@ -1,19 +1,76 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="PHP_CodeSniffer" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/squizlabs/PHP_CodeSniffer/master/phpcs.xsd">
<rule ref="Generic.NamingConventions.UpperCaseConstantName"/>
<rule ref="Generic.CodeAnalysis.UnusedFunctionParameter"/>
<rule ref="Generic.Strings.UnnecessaryStringConcat"/>
<rule ref="PSR2">
<exclude name="Generic.Files.LineLength"/>
<?xml version="1.0"?>
<ruleset
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="bearcs"
xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/squizlabs/PHP_CodeSniffer/master/phpcs.xsd">

<arg name="basepath" value="."/>
<arg name="extensions" value="php"/>
<arg name="parallel" value="80"/>
<arg name="cache" value=".phpcs-cache"/>

<!-- Compatibility with PHP 7.3.0 -->
<config name="php_version" value="70300"/>

<!-- Ignore warnings, show progress of the run and show sniff names -->
<arg value="nps"/>

<!-- Directories to be checked -->
<file>src</file>
<file>tests</file>
<exclude-pattern>*/tests/tmp/*</exclude-pattern>

<!-- PSR12 Coding Standard -->
<rule ref="PSR12"/>

<!-- Doctrine Coding Standard -->
<rule ref="Doctrine">
<!-- Inapplicable for this project -->
<!-- Base -->
<exclude name="Generic.Formatting.MultipleStatementAlignment.NotSame"/>
<exclude name="Squiz.Strings.DoubleQuoteUsage.ContainsVar"/>
<exclude name="SlevomatCodingStandard.Classes.SuperfluousAbstractClassNaming.SuperfluousPrefix"/>
<exclude name="SlevomatCodingStandard.Classes.SuperfluousExceptionNaming.SuperfluousSuffix"/>
<exclude name="SlevomatCodingStandard.Classes.SuperfluousInterfaceNaming.SuperfluousSuffix"/>
<exclude name="SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.MissingVariable"/>
<exclude name="SlevomatCodingStandard.Commenting.UselessInheritDocComment.UselessInheritDocComment"/>
<exclude name="SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint"/>
<exclude name="SlevomatCodingStandard.TypeHints.PropertyTypeHint.MissingNativeTypeHint"/>
<exclude name="SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingNativeTypeHint"/>
<!-- /Base -->
<!-- Option -->
<exclude name="SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed"/>
<!-- attribute -->
<exclude name="Squiz.WhiteSpace.FunctionSpacing.Before"/>
<!-- /Option -->
<!-- Exclude Fake files form Doctrine CS -->
<exclude-pattern>*/tests/Fake/*</exclude-pattern>
</rule>
<rule ref="PEAR.Commenting.FunctionComment">
<exclude name="PEAR.Commenting.FunctionComment.MissingReturn"/>
<exclude name="PEAR.Commenting.FunctionComment.MissingParamComment"/>
<exclude name="PEAR.Commenting.FunctionComment.SpacingBeforeTags"/>
<exclude name="PEAR.Commenting.FunctionComment.MissingParamTag"/>
<exclude name="PEAR.Commenting.FunctionComment.Missing"/>
<exclude name="PEAR.Commenting.FunctionComment.ParameterCommentsNotAligned"/>
<exclude name="PEAR.Commenting.FunctionComment.ParamNameNoMatch"/>

<!-- Additional Rules -->
<rule ref="SlevomatCodingStandard.Commenting.DocCommentSpacing">
<properties>
<property name="annotationsGroups" type="array">
<element value="@param, @psalm-param, @phpstan-param"/>
<element value="@return, @psalm-return, @phpstan-return"/>
<element value="@throws"/>
</property>
</properties>
</rule>
<rule ref="SlevomatCodingStandard.TypeHints.PropertyTypeHint.MissingNativeTypeHint">
<include-pattern>tests/*</include-pattern>
</rule>
<rule ref="SlevomatCodingStandard.Classes.PropertySpacing">
<properties>
<property name="minLinesCountBeforeWithComment" value="1"/>
<property name="maxLinesCountBeforeWithComment" value="1"/>
<property name="maxLinesCountBeforeWithoutComment" value="0"/>
</properties>
</rule>
<rule ref="SlevomatCodingStandard.Namespaces.UnusedUses">
<properties>
<property name="searchAnnotations" value="true"/>
</properties>
</rule>
<exclude-pattern>*/Fake/*</exclude-pattern>
<exclude-pattern>*/tmp/*</exclude-pattern>
</ruleset>
2 changes: 0 additions & 2 deletions phpstan.neon
@@ -1,5 +1,3 @@
includes:
- phpstan-baseline.neon
parameters:
level: max
paths:
Expand Down
2 changes: 1 addition & 1 deletion psalm.xml
@@ -1,6 +1,6 @@
<?xml version="1.0"?>
<psalm
errorLevel="1"
errorLevel="3"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
Expand Down
35 changes: 22 additions & 13 deletions src/CacheInterceptor.php
Expand Up @@ -5,16 +5,21 @@
namespace BEAR\QueryRepository;

use BEAR\QueryRepository\Exception\LogicException;
use BEAR\QueryRepository\Exception\RuntimeException;
use BEAR\Resource\ResourceObject;
use Ray\Aop\MethodInterceptor;
use Ray\Aop\MethodInvocation;
use Throwable;

use function assert;
use function get_class;
use function sprintf;
use function trigger_error;

use const E_USER_WARNING;

class CacheInterceptor implements MethodInterceptor
{
/**
* @var QueryRepositoryInterface
*/
/** @var QueryRepositoryInterface */
private $repository;

public function __construct(
Expand All @@ -28,40 +33,44 @@ public function __construct(
*/
public function invoke(MethodInvocation $invocation)
{
/** @var ResourceObject $ro */
$ro = $invocation->getThis();
assert($ro instanceof ResourceObject);
try {
$stored = $this->repository->get($ro->uri);
} catch (LogicException | RuntimeException $e) {
} catch (LogicException $e) {
throw $e;
} catch (\Exception $e) {
$this->triggerError($e);
} catch (Throwable $e) {
$this->triggerWarning($e);

return $invocation->proceed();
}

if ($stored) {
[$ro->uri, $ro->code, $ro->headers, $ro->body, $ro->view] = $stored;

return $ro;
}

/** @psalm-suppress MixedAssignment */
$ro = $invocation->proceed();
assert($ro instanceof ResourceObject);
try {
$ro->code === 200 ? $this->repository->put($ro) : $this->repository->purge($ro->uri);
} catch (LogicException | RuntimeException $e) {
} catch (LogicException $e) {
throw $e;
} catch (\Exception $e) {
$this->triggerError($e);
} catch (Throwable $e) {
$this->triggerWarning($e);
}

return $ro;
}

/**
* Trigger error when cache server is down instead of throwing the exception
* Trigger warning
*
* When the cache server is down, it will issue a warning rather than an exception to continue service.
*/
private function triggerError(\Exception $e) : void
private function triggerWarning(Throwable $e): void
{
$message = sprintf('%s: %s in %s:%s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine());
trigger_error($message, E_USER_WARNING);
Expand Down
6 changes: 2 additions & 4 deletions src/CacheVersionModule.php
Expand Up @@ -9,12 +9,10 @@

class CacheVersionModule extends AbstractModule
{
/**
* @var string
*/
/** @var string */
private $version;

public function __construct(string $cacheVersion, AbstractModule $module = null)
public function __construct(string $cacheVersion, ?AbstractModule $module = null)
{
$this->version = $cacheVersion;
parent::__construct($module);
Expand Down
35 changes: 22 additions & 13 deletions src/CliHttpCache.php
Expand Up @@ -4,15 +4,19 @@

namespace BEAR\QueryRepository;

use function assert;
use BEAR\Sunday\Extension\Transfer\HttpCacheInterface;

use function is_string;
use function parse_str;
use function sprintf;
use function str_replace;
use function strtoupper;

use const PHP_EOL;

final class CliHttpCache implements HttpCacheInterface
{
/**
* @var ResourceStorageInterface
*/
/** @var ResourceStorageInterface */
private $storage;

public function __construct(ResourceStorageInterface $storage)
Expand All @@ -23,11 +27,12 @@ public function __construct(ResourceStorageInterface $storage)
/**
* {@inheritdoc}
*/
public function isNotModified(array $server) : bool
public function isNotModified(array $server): bool
{
if (isset($server['argc']) && $server['argc'] === 4) {
assert(isset($server['argv'][3]) && is_string($server['argv'][3]));
$server = $this->setRequestHeaders($server, $server['argv'][3]);
/** @var array{HTTP_IF_NONE_MATCH: string}|array{argc: int, argv: array} $server */
$hasRequestHeaderInCli = isset($server['argc']) && $server['argc'] === 4 && isset($server['argv']);
if ($hasRequestHeaderInCli) {
$server = $this->setRequestHeaders($server, $server['argv'][3]); // @phpstan-ignore-line
}

return isset($server['HTTP_IF_NONE_MATCH']) && is_string($server['HTTP_IF_NONE_MATCH']) && $this->storage->hasEtag($server['HTTP_IF_NONE_MATCH']);
Expand All @@ -43,19 +48,23 @@ public function transfer()
echo '304 Not Modified' . PHP_EOL . PHP_EOL;
}

private function setRequestHeaders(array $server, string $query) : array
/**
* @param array<string, mixed> $server
*
* @return array<string, string>
*/
private function setRequestHeaders(array $server, string $query): array
{
\parse_str($query, $headers);
/** @var array<string, string> $headers */
parse_str($query, $headers);
foreach ($headers as $key => $header) {
$server[$this->getServerKey($key)] = (string) $header;
}

return $server;
}

private function getServerKey(string $key) : string
private function getServerKey(string $key): string
{
return sprintf('HTTP_%s', strtoupper(\str_replace('-', '_', $key)));
return sprintf('HTTP_%s', strtoupper(str_replace('-', '_', $key)));
}
}
8 changes: 4 additions & 4 deletions src/CommandInterceptor.php
Expand Up @@ -11,11 +11,11 @@
use Ray\Aop\MethodInterceptor;
use Ray\Aop\MethodInvocation;

use function get_class;

class CommandInterceptor implements MethodInterceptor
{
/**
* @var CommandInterface[]
*/
/** @var CommandInterface[] */
private $commands = [];

/**
Expand All @@ -38,7 +38,7 @@ public function invoke(MethodInvocation $invocation)
/** @psalm-suppress MixedAssignment */
$ro = $invocation->proceed();
if (! $ro instanceof ResourceObject) {
throw new ReturnValueIsNotResourceObjectException(\get_class($invocation->getThis()));
throw new ReturnValueIsNotResourceObjectException(get_class($invocation->getThis()));
}

if ($ro->code >= Code::BAD_REQUEST) {
Expand Down
10 changes: 3 additions & 7 deletions src/CommandsProvider.php
Expand Up @@ -9,14 +9,10 @@

class CommandsProvider implements ProviderInterface
{
/**
* @var QueryRepositoryInterface
*/
/** @var QueryRepositoryInterface */
private $repository;

/**
* @var ResourceInterface
*/
/** @var ResourceInterface */
private $resource;

public function __construct(
Expand All @@ -34,7 +30,7 @@ public function get()
{
return [
new RefreshSameCommand($this->repository),
new RefreshAnnotatedCommand($this->repository, $this->resource)
new RefreshAnnotatedCommand($this->repository, $this->resource),
];
}
}

0 comments on commit 9a27b9c

Please sign in to comment.