From d35de4661b55f6e3d55a9937febd926795c4b81a Mon Sep 17 00:00:00 2001 From: Young-jin Yun Date: Fri, 6 Jan 2023 01:41:19 +0900 Subject: [PATCH 01/11] upgrading test --- composer.json | 14 +- library/Odesk/Phystrix/AbstractCommand.php | 170 +++++++----------- library/Odesk/Phystrix/ApcuStateStorage.php | 44 ++--- library/Odesk/Phystrix/ArrayStateStorage.php | 64 ++----- library/Odesk/Phystrix/CircuitBreaker.php | 55 +++--- .../Odesk/Phystrix/CircuitBreakerFactory.php | 12 +- .../Phystrix/CircuitBreakerInterface.php | 26 +-- library/Odesk/Phystrix/CommandFactory.php | 42 ++--- library/Odesk/Phystrix/CommandMetrics.php | 48 +++-- .../Odesk/Phystrix/CommandMetricsFactory.php | 28 ++- .../Phystrix/Exception/RuntimeException.php | 26 +-- .../Odesk/Phystrix/HealthCountsSnapshot.php | 46 ++--- library/Odesk/Phystrix/MetricsCounter.php | 78 ++++---- .../MetricsEventStream/ApcMetricsPoller.php | 54 +++--- .../MetricsEventStream/ApcuMetricsPoller.php | 55 +++--- .../MetricsPollerInterface.php | 4 +- .../MetricsEventStream/MetricsServer.php | 19 +- library/Odesk/Phystrix/NoOpCircuitBreaker.php | 36 ++-- .../Odesk/Phystrix/StateStorageInterface.php | 40 +---- phpunit.xml.dist | 47 +++-- .../Odesk/Phystrix/ArrayStateStorageTest.php | 23 ++- .../Phystrix/CircuitBreakerFactoryTest.php | 53 +++--- .../Odesk/Phystrix/CircuitBreakerTest.php | 51 +++--- .../Odesk/Phystrix/CommandFactoryTest.php | 78 ++++---- .../Phystrix/CommandMetricsFactoryTest.php | 23 ++- .../Odesk/Phystrix/CommandMetricsTest.php | 63 +++---- tests/Tests/Odesk/Phystrix/CommandMock.php | 25 +-- tests/Tests/Odesk/Phystrix/CommandTest.php | 85 ++++----- .../Exception/RuntimeExceptionTest.php | 8 +- .../Odesk/Phystrix/FactoryCommandMock.php | 6 +- .../Phystrix/HealthCountsSnapshotTest.php | 17 +- .../Odesk/Phystrix/MetricsCounterTest.php | 26 ++- .../Odesk/Phystrix/NoOpCircuitBreakerTest.php | 17 +- .../Tests/Odesk/Phystrix/RequestCacheTest.php | 25 ++- tests/Tests/Odesk/Phystrix/RequestLogTest.php | 33 ++-- 35 files changed, 602 insertions(+), 839 deletions(-) diff --git a/composer.json b/composer.json index 5cdc508..447b2a4 100644 --- a/composer.json +++ b/composer.json @@ -12,16 +12,16 @@ } }, "require": { - "php": ">=7.1", + "php": ">=7.4", "ext-json": "*", - "psr/container": "^1.0", - "psr/simple-cache": "^1.0", - "laminas/laminas-config": "^3.3" + "psr/container": "^1.0|^2.0", + "psr/simple-cache": "^1.0|^2.0|^3.0", + "laminas/laminas-config": "^3.5" }, "require-dev": { - "phpunit/phpunit": "~5.7", - "squizlabs/php_codesniffer": "^3.4", - "php-di/php-di": "^6.0" + "phpunit/phpunit": "^9.5", + "squizlabs/php_codesniffer": "^3.7", + "php-di/php-di": "^6.4" }, "extra": { "branch-alias": { diff --git a/library/Odesk/Phystrix/AbstractCommand.php b/library/Odesk/Phystrix/AbstractCommand.php index c764d4e..d803a9f 100644 --- a/library/Odesk/Phystrix/AbstractCommand.php +++ b/library/Odesk/Phystrix/AbstractCommand.php @@ -44,134 +44,120 @@ abstract class AbstractCommand /** * Command Key, used for grouping Circuit Breakers - * - * @var string */ - protected $commandKey; + protected ?string $commandKey = null; /** * Command configuration - * - * @var Config */ - protected $config; + protected ?Config $config = null; - /** - * @var CircuitBreakerFactory - */ - private $circuitBreakerFactory; + private CircuitBreakerFactory $circuitBreakerFactory; - /** - * @var CommandMetricsFactory - */ - private $commandMetricsFactory; + private CommandMetricsFactory $commandMetricsFactory; - /** - * @var ContainerInterface|null - */ - protected $container; + protected ?ContainerInterface $container; - /** - * @var CacheInterface - */ - private $requestCache; + private ?CacheInterface $requestCache; - /** - * @var RequestLog - */ - private $requestLog; + private ?RequestLog $requestLog; /** * Events logged during execution - * - * @var array */ - private $executionEvents = array(); + private array $executionEvents = []; /** * Execution time in milliseconds - * - * @var integer */ - private $executionTime; + private ?int $executionTime = null; /** * Exception thrown if there was one - * - * @var Exception */ - private $executionException; + private ?Exception $executionException; /** * Timestamp in milliseconds - * - * @var integer */ - private $invocationStartTime; + private int $invocationStartTime; + + public function getConfig(): ?Config + { + return $this->config; + } + + public function getCircuitBreakerFactory(): CircuitBreakerFactory + { + return $this->circuitBreakerFactory; + } + + public function getContainer(): ?ContainerInterface + { + return $this->container; + } + + public function getRequestCache(): ?CacheInterface + { + return $this->requestCache; + } + + public function getRequestLog(): ?RequestLog + { + return $this->requestLog; + } /** * Determines and returns command key, used for circuit breaker grouping and metrics tracking - * - * @return string */ - public function getCommandKey() + public function getCommandKey(): ?string { if ($this->commandKey) { return $this->commandKey; - } else { - // If the command key hasn't been defined in the class we use the current class name - // but hystrix dashboard not work, because fixed below. - // refs : https://github.com/persevereVon/preq-laravel/blob/master/src/AbstractCommand.php#L100 - return str_replace('\\', '.', get_class($this)); } + + // If the command key hasn't been defined in the class we use the current class name + // but hystrix dashboard not work, because fixed below. + // refs : https://github.com/persevereVon/preq-laravel/blob/master/src/AbstractCommand.php#L100 + return str_replace('\\', '.', get_class($this)); } /** * Sets instance of circuit breaker factory - * - * @param CircuitBreakerFactory $circuitBreakerFactory */ - public function setCircuitBreakerFactory(CircuitBreakerFactory $circuitBreakerFactory) + public function setCircuitBreakerFactory(CircuitBreakerFactory $circuitBreakerFactory): void { $this->circuitBreakerFactory = $circuitBreakerFactory; } /** * Sets instance of command metrics factory - * - * @param CommandMetricsFactory $commandMetricsFactory */ - public function setCommandMetricsFactory(CommandMetricsFactory $commandMetricsFactory) + public function setCommandMetricsFactory(CommandMetricsFactory $commandMetricsFactory): void { $this->commandMetricsFactory = $commandMetricsFactory; } /** * Sets shared object for request caching - * - * @param CacheInterface $requestCache */ - public function setRequestCache(CacheInterface $requestCache) + public function setRequestCache(CacheInterface $requestCache): void { $this->requestCache = $requestCache; } /** * Sets shared object for request logging - * - * @param RequestLog $requestLog */ - public function setRequestLog(RequestLog $requestLog) + public function setRequestLog(RequestLog $requestLog): void { $this->requestLog = $requestLog; } /** * Sets base command configuration from the global phystrix configuration - * - * @param Config $phystrixConfig */ - public function initializeConfig(Config $phystrixConfig) + public function initializeConfig(Config $phystrixConfig): void { $commandKey = $this->getCommandKey(); $config = new Config($phystrixConfig->get('default')->toArray(), true); @@ -184,13 +170,10 @@ public function initializeConfig(Config $phystrixConfig) /** * Sets configuration for the command, allows to override config in runtime - * - * @param Config $config - * @param bool $merge */ - public function setConfig(Config $config, $merge = true) + public function setConfig(Config $config, bool $merge = true): void { - if ($this->config && $merge) { + if ($this->config instanceof Config && $merge) { $this->config->merge($config); } else { $this->config = $config; @@ -199,10 +182,8 @@ public function setConfig(Config $config, $merge = true) /** * Determines whether request caching is enabled for this command - * - * @return bool */ - private function isRequestCacheEnabled() + private function isRequestCacheEnabled(): bool { if (!$this->requestCache instanceof CacheInterface) { return false; @@ -281,26 +262,22 @@ abstract protected function run(); /** * Custom preparation logic, preceding command execution */ - protected function prepare() + protected function prepare(): void { } /** * Custom logic proceeding event generation - * - * @param string $eventName */ - protected function processExecutionEvent($eventName) + protected function processExecutionEvent(string $eventName): void { // } /** * Sets service container instance, for injecting custom dependencies into the command - * - * @param ContainerInterface|null $container */ - public function setContainer(ContainerInterface $container = null) + public function setContainer(?ContainerInterface $container = null) { $this->container = $container; } @@ -310,7 +287,7 @@ public function setContainer(ContainerInterface $container = null) * * @param string $eventName type from class constants EVENT_* */ - private function recordExecutionEvent($eventName) + private function recordExecutionEvent(string $eventName): void { $this->executionEvents[] = $eventName; @@ -319,20 +296,16 @@ private function recordExecutionEvent($eventName) /** * Command Metrics for this command key - * - * @return CommandMetrics */ - private function getMetrics() + private function getMetrics(): CommandMetrics { return $this->commandMetricsFactory->get($this->getCommandKey(), $this->config); } /** * Circuit breaker for this command key - * - * @return CircuitBreakerInterface */ - private function getCircuitBreaker() + private function getCircuitBreaker(): CircuitBreakerInterface { return $this->circuitBreakerFactory->get($this->getCommandKey(), $this->config, $this->getMetrics()); } @@ -340,12 +313,11 @@ private function getCircuitBreaker() /** * Attempts to retrieve fallback by calling getFallback * - * @param Exception $originalException (Optional) If null, the request was short-circuited + * @param Exception|null $originalException (Optional) If null, the request was short-circuited * @return mixed - * @throws RuntimeException When fallback is disabled, not available for the command, or failed retrieving * @throws Exception */ - private function getFallbackOrThrowException(Exception $originalException = null) + private function getFallbackOrThrowException(?Exception $originalException = null) { $metrics = $this->getMetrics(); $message = $originalException === null ? 'Short-circuited' : $originalException->getMessage(); @@ -394,7 +366,7 @@ private function getFallbackOrThrowException(Exception $originalException = null * @return mixed * @throws FallbackNotAvailableException When no custom fallback provided */ - protected function getFallback(Exception $exception = null) + protected function getFallback(?Exception $exception = null) { throw new FallbackNotAvailableException('No fallback available'); } @@ -407,20 +379,16 @@ protected function getFallback(Exception $exception = null) * * If multiple command instances are executed within current HTTP request, only the first one will be * executed and all others returned from cache. - * - * @return string|null */ - protected function getCacheKey() + protected function getCacheKey(): ?string { return null; } /** * Returns events collected - * - * @return array */ - public function getExecutionEvents() + public function getExecutionEvents(): array { return $this->executionEvents; } @@ -428,37 +396,31 @@ public function getExecutionEvents() /** * Records command execution time if the command was executed, not short-circuited and not returned from cache */ - private function recordExecutionTime() + private function recordExecutionTime(): void { $this->executionTime = $this->getTimeInMilliseconds() - $this->invocationStartTime; } /** * Returns execution time in milliseconds, null if not executed - * - * @return null|integer */ - public function getExecutionTimeInMilliseconds() + public function getExecutionTimeInMilliseconds(): ?int { return $this->executionTime; } /** * Returns exception thrown while executing the command, if there was any - * - * @return Exception|null */ - public function getExecutionException() + public function getExecutionException(): ?Exception { return $this->executionException; } /** * Returns current time on the server in milliseconds - * - * @return float */ - private function getTimeInMilliseconds() + private function getTimeInMilliseconds(): float { return floor(microtime(true) * 1000); } @@ -466,7 +428,7 @@ private function getTimeInMilliseconds() /** * Adds reference to the command to the current request log */ - private function recordExecutedCommand() + private function recordExecutedCommand(): void { if ($this->requestLog && $this->config->get('requestLog')->get('enabled')) { $this->requestLog->addExecutedCommand($this); diff --git a/library/Odesk/Phystrix/ApcuStateStorage.php b/library/Odesk/Phystrix/ApcuStateStorage.php index fb3af37..2fa390b 100644 --- a/library/Odesk/Phystrix/ApcuStateStorage.php +++ b/library/Odesk/Phystrix/ApcuStateStorage.php @@ -46,37 +46,26 @@ public function __construct() /** * Prepends cache prefix and filters out invalid characters - * - * @param string $name - * @return string */ - protected function prefix($name) + protected function prefix(string $name): string { return self::CACHE_PREFIX . $name; } /** * Returns counter value for the given bucket - * - * @param string $commandKey - * @param string $type - * @param integer $index - * @return integer */ - public function getBucket($commandKey, $type, $index) + public function getBucket(string $commandKey, string $type, int $index): ?int { $bucketName = $this->prefix($commandKey . '_' . $type . '_' . $index); + return apcu_fetch($bucketName); } /** * Increments counter value for the given bucket - * - * @param string $commandKey - * @param string $type - * @param integer $index */ - public function incrementBucket($commandKey, $type, $index) + public function incrementBucket(string $commandKey, string $type, int $index): void { $bucketName = $this->prefix($commandKey . '_' . $type . '_' . $index); if (!apcu_add($bucketName, 1, self::BUCKET_EXPIRE_SECONDS)) { @@ -86,12 +75,8 @@ public function incrementBucket($commandKey, $type, $index) /** * If the given bucket is found, sets counter value to 0. - * - * @param string $commandKey Circuit breaker key - * @param string $type - * @param integer $index */ - public function resetBucket($commandKey, $type, $index) + public function resetBucket(string $commandKey, string $type, int $index): void { $bucketName = $this->prefix($commandKey . '_' . $type . '_' . $index); if (apcu_exists($bucketName)) { @@ -103,9 +88,9 @@ public function resetBucket($commandKey, $type, $index) * Marks the given circuit as open * * @param string $commandKey Circuit key - * @param integer $sleepingWindowInMilliseconds In how much time we should allow a single test + * @param int $sleepingWindowInMilliseconds In how much time we should allow a single test */ - public function openCircuit($commandKey, $sleepingWindowInMilliseconds) + public function openCircuit(string $commandKey, int $sleepingWindowInMilliseconds): void { $openedKey = $this->prefix($commandKey . self::OPENED_NAME); $singleTestFlagKey = $this->prefix($commandKey . self::SINGLE_TEST_BLOCKED); @@ -120,12 +105,8 @@ public function openCircuit($commandKey, $sleepingWindowInMilliseconds) /** * Whether a single test is allowed - * - * @param string $commandKey Circuit breaker key - * @param integer $sleepingWindowInMilliseconds In how much time we should allow the next single test - * @return boolean */ - public function allowSingleTest($commandKey, $sleepingWindowInMilliseconds) + public function allowSingleTest(string $commandKey, int $sleepingWindowInMilliseconds): bool { $singleTestFlagKey = $this->prefix($commandKey . self::SINGLE_TEST_BLOCKED); // using 'add' enforces thread safety. @@ -136,11 +117,8 @@ public function allowSingleTest($commandKey, $sleepingWindowInMilliseconds) /** * Whether a circuit is open - * - * @param string $commandKey Circuit breaker key - * @return boolean */ - public function isCircuitOpen($commandKey) + public function isCircuitOpen(string $commandKey): bool { $openedKey = $this->prefix($commandKey . self::OPENED_NAME); return (bool) apcu_fetch($openedKey); @@ -148,10 +126,8 @@ public function isCircuitOpen($commandKey) /** * Marks the given circuit as closed - * - * @param string $commandKey Circuit key */ - public function closeCircuit($commandKey) + public function closeCircuit(string $commandKey): void { $openedKey = $this->prefix($commandKey . self::OPENED_NAME); apcu_store($openedKey, false); diff --git a/library/Odesk/Phystrix/ArrayStateStorage.php b/library/Odesk/Phystrix/ArrayStateStorage.php index c7ca73d..5a667c5 100644 --- a/library/Odesk/Phystrix/ArrayStateStorage.php +++ b/library/Odesk/Phystrix/ArrayStateStorage.php @@ -30,41 +30,26 @@ class ArrayStateStorage implements StateStorageInterface { /** * E.g. array('CommandKey' => array('success' => array(2 => 123))); where 2 is index and 123 is the metric value - * - * @var array */ - protected $buckets = array(); + protected array $buckets = []; /** * E.g. array('CommandKey' => 1234567) where 123456789 is the time in milliseconds when a single test is allowed - * - * @var array */ - protected $openCircuits = array(); + protected array $openCircuits = []; /** * Returns counter value for the given bucket - * - * @param string $commandKey - * @param string $type - * @param integer $index - * @return integer */ - public function getBucket($commandKey, $type, $index) + public function getBucket(string $commandKey, string $type, int $index): ?int { - return isset($this->buckets[$commandKey][$type][$index]) - ? $this->buckets[$commandKey][$type][$index] - : null; + return $this->buckets[$commandKey][$type][$index] ?? null; } /** * Increments counter value for the given bucket - * - * @param string $commandKey - * @param string $type - * @param integer $index */ - public function incrementBucket($commandKey, $type, $index) + public function incrementBucket(string $commandKey, string $type, int $index): void { if (!isset($this->buckets[$commandKey][$type][$index])) { $this->buckets[$commandKey][$type][$index] = 1; @@ -75,12 +60,8 @@ public function incrementBucket($commandKey, $type, $index) /** * If the given bucket is found, sets counter value to 0. - * - * @param string $commandKey Circuit breaker key - * @param string $type - * @param integer $index */ - public function resetBucket($commandKey, $type, $index) + public function resetBucket(string $commandKey, string $type, int $index): void { if (isset($this->buckets[$commandKey][$type][$index])) { $this->buckets[$commandKey][$type][$index] = 0; @@ -89,50 +70,39 @@ public function resetBucket($commandKey, $type, $index) /** * Marks the given circuit as open - * - * @param string $commandKey Circuit key - * @param integer $sleepingWindowInMilliseconds In how much time we should allow a single test */ - public function openCircuit($commandKey, $sleepingWindowInMilliseconds) + public function openCircuit(string $commandKey, int $sleepingWindowInMilliseconds): void { $this->openCircuits[$commandKey] = $this->getTimeInMilliseconds() + $sleepingWindowInMilliseconds; } /** * Whether a single test is allowed - * - * @param string $commandKey Circuit breaker key - * @param integer $sleepingWindowInMilliseconds In how much time we should allow the next single test - * @return boolean */ - public function allowSingleTest($commandKey, $sleepingWindowInMilliseconds) + public function allowSingleTest(string $commandKey, int $sleepingWindowInMilliseconds): bool { if (!isset($this->openCircuits[$commandKey])) { return true; - } else { - $allow = $this->openCircuits[$commandKey] < $this->getTimeInMilliseconds(); - $this->openCircuits[$commandKey] = $this->getTimeInMilliseconds() + $sleepingWindowInMilliseconds; - return $allow; } + + $allow = $this->openCircuits[$commandKey] < $this->getTimeInMilliseconds(); + $this->openCircuits[$commandKey] = $this->getTimeInMilliseconds() + $sleepingWindowInMilliseconds; + + return $allow; } /** * Whether a circuit is open - * - * @param string $commandKey Circuit breaker key - * @return boolean */ - public function isCircuitOpen($commandKey) + public function isCircuitOpen(string $commandKey): bool { return isset($this->openCircuits[$commandKey]); } /** * Marks the given circuit as closed - * - * @param string $commandKey Circuit key */ - public function closeCircuit($commandKey) + public function closeCircuit(string $commandKey): void { if (isset($this->openCircuits[$commandKey])) { unset($this->openCircuits[$commandKey]); @@ -141,10 +111,8 @@ public function closeCircuit($commandKey) /** * Returns current time on the server in milliseconds - * - * @return float */ - private function getTimeInMilliseconds() + private function getTimeInMilliseconds(): float { return floor(microtime(true) * 1000); } diff --git a/library/Odesk/Phystrix/CircuitBreaker.php b/library/Odesk/Phystrix/CircuitBreaker.php index 3e13c04..9522726 100644 --- a/library/Odesk/Phystrix/CircuitBreaker.php +++ b/library/Odesk/Phystrix/CircuitBreaker.php @@ -31,29 +31,19 @@ */ class CircuitBreaker implements CircuitBreakerInterface { - /** - * @var CommandMetrics - */ - private $metrics; + private CommandMetrics $metrics; /** * Phystrix config - * - * @var Config */ - private $config; + private Config $config; - /** - * @var StateStorageInterface - */ - private $stateStorage; + private StateStorageInterface $stateStorage; /** * String identifier of the group of commands this circuit breaker is responsible for - * - * @var string */ - private $commandKey; + private string $commandKey; /** * Constructor @@ -64,7 +54,7 @@ class CircuitBreaker implements CircuitBreakerInterface * @param StateStorageInterface $stateStorage */ public function __construct( - $commandKey, + string $commandKey, CommandMetrics $metrics, Config $commandConfig, StateStorageInterface $stateStorage @@ -75,12 +65,30 @@ public function __construct( $this->stateStorage = $stateStorage; } + public function getMetrics(): CommandMetrics + { + return $this->metrics; + } + + public function getConfig(): Config + { + return $this->config; + } + + public function getStateStorage(): StateStorageInterface + { + return $this->stateStorage; + } + + public function getCommandKey(): string + { + return $this->commandKey; + } + /** * Whether the circuit is open - * - * @return boolean */ - public function isOpen() + public function isOpen(): bool { if ($this->stateStorage->isCircuitOpen($this->commandKey)) { // if we're open we immediately return true and don't bother attempting to 'close' ourself @@ -109,10 +117,8 @@ public function isOpen() /** * Whether a single test is allowed now - * - * @return boolean */ - public function allowSingleTest() + public function allowSingleTest(): bool { return $this->stateStorage->allowSingleTest( $this->commandKey, @@ -122,10 +128,8 @@ public function allowSingleTest() /** * Whether the request is allowed - * - * @return boolean */ - public function allowRequest() + public function allowRequest(): bool { if ($this->config->get('circuitBreaker')->get('forceOpen')) { return false; @@ -141,9 +145,8 @@ public function allowRequest() * Marks a successful request * * @link http://goo.gl/dtHN34 - * @return void */ - public function markSuccess() + public function markSuccess(): void { if ($this->stateStorage->isCircuitOpen($this->commandKey)) { $this->stateStorage->closeCircuit($this->commandKey); diff --git a/library/Odesk/Phystrix/CircuitBreakerFactory.php b/library/Odesk/Phystrix/CircuitBreakerFactory.php index 5a4996a..f4a2915 100644 --- a/library/Odesk/Phystrix/CircuitBreakerFactory.php +++ b/library/Odesk/Phystrix/CircuitBreakerFactory.php @@ -27,15 +27,9 @@ */ class CircuitBreakerFactory { - /** - * @var array - */ - protected $circuitBreakersByCommand = array(); + protected array $circuitBreakersByCommand = []; - /** - * @var StateStorageInterface - */ - protected $stateStorage; + protected StateStorageInterface $stateStorage; /** * Constructor @@ -55,7 +49,7 @@ public function __construct(StateStorageInterface $stateStorage) * @param CommandMetrics $metrics * @return CircuitBreakerInterface */ - public function get($commandKey, Config $commandConfig, CommandMetrics $metrics) + public function get(string $commandKey, Config $commandConfig, CommandMetrics $metrics): CircuitBreakerInterface { if (!isset($this->circuitBreakersByCommand[$commandKey])) { $circuitBreakerConfig = $commandConfig->get('circuitBreaker'); diff --git a/library/Odesk/Phystrix/CircuitBreakerInterface.php b/library/Odesk/Phystrix/CircuitBreakerInterface.php index a5219e0..cfb2428 100644 --- a/library/Odesk/Phystrix/CircuitBreakerInterface.php +++ b/library/Odesk/Phystrix/CircuitBreakerInterface.php @@ -20,36 +20,38 @@ namespace Odesk\Phystrix; +use Laminas\Config\Config; + /** * Circuit breaker interface */ interface CircuitBreakerInterface { + public function getMetrics(): CommandMetrics; + + public function getConfig(): Config; + + public function getStateStorage(): StateStorageInterface; + + public function getCommandKey(): string; + /** * Whether the circuit is open - * - * @return boolean */ - public function isOpen(); + public function isOpen(): bool; /** * Whether the request is allowed - * - * @return boolean */ - public function allowRequest(); + public function allowRequest(): bool; /** * Whether a single test is allowed now - * - * @return boolean */ - public function allowSingleTest(); + public function allowSingleTest(): bool; /** * Marks a successful request - * - * @return void */ - public function markSuccess(); + public function markSuccess(): void; } diff --git a/library/Odesk/Phystrix/CommandFactory.php b/library/Odesk/Phystrix/CommandFactory.php index 94e56f9..5e22c9e 100644 --- a/library/Odesk/Phystrix/CommandFactory.php +++ b/library/Odesk/Phystrix/CommandFactory.php @@ -32,35 +32,17 @@ */ class CommandFactory { - /** - * @var Config - */ - protected $config; + protected Config $config; - /** - * @var ContainerInterface - */ - protected $container; + protected ?ContainerInterface $container; - /** - * @var CircuitBreakerFactory - */ - protected $circuitBreakerFactory; + protected CircuitBreakerFactory $circuitBreakerFactory; - /** - * @var CommandMetricsFactory - */ - protected $commandMetricsFactory; + protected CommandMetricsFactory $commandMetricsFactory; - /** - * @var CacheInterface - */ - protected $requestCache; + protected ?CacheInterface $requestCache; - /** - * @var RequestLog - */ - protected $requestLog; + protected ?RequestLog $requestLog; /** * Constructor @@ -76,9 +58,9 @@ public function __construct( Config $config, CircuitBreakerFactory $circuitBreakerFactory, CommandMetricsFactory $commandMetricsFactory, - CacheInterface $requestCache = null, - RequestLog $requestLog = null, - ContainerInterface $container = null + ?CacheInterface $requestCache = null, + ?RequestLog $requestLog = null, + ?ContainerInterface $container = null ) { $this->config = $config; $this->circuitBreakerFactory = $circuitBreakerFactory; @@ -95,7 +77,7 @@ public function __construct( * @return AbstractCommand * @throws ReflectionException */ - public function getCommand($class) + public function getCommand(string $class): AbstractCommand { $parameters = func_get_args(); array_shift($parameters); @@ -111,11 +93,11 @@ public function getCommand($class) $command->setContainer($this->container); $command->initializeConfig($this->config); - if ($this->requestCache) { + if ($this->requestCache instanceof RequestCache) { $command->setRequestCache($this->requestCache); } - if ($this->requestLog) { + if ($this->requestLog instanceof RequestLog) { $command->setRequestLog($this->requestLog); } diff --git a/library/Odesk/Phystrix/CommandMetrics.php b/library/Odesk/Phystrix/CommandMetrics.php index 139a624..dbc956d 100644 --- a/library/Odesk/Phystrix/CommandMetrics.php +++ b/library/Odesk/Phystrix/CommandMetrics.php @@ -29,37 +29,32 @@ */ class CommandMetrics { - /** - * @var MetricsCounter - */ - private $counter; + private MetricsCounter $counter; - /** - * @var integer - */ - private $healthSnapshotIntervalInMilliseconds = 1000; + private int $healthSnapshotIntervalInMilliseconds; - /** - * @var HealthCountsSnapshot - */ - private $lastSnapshot; + private ?HealthCountsSnapshot $lastSnapshot = null; /** * Constructor * - * @param MetricsCounter $counter * @param integer $snapshotInterval Snapshot interval time in milliseconds */ - public function __construct(MetricsCounter $counter, $snapshotInterval) + public function __construct(MetricsCounter $counter, int $snapshotInterval) { $this->counter = $counter; $this->healthSnapshotIntervalInMilliseconds = $snapshotInterval; } + public function getHealthSnapshotIntervalInMilliseconds(): int + { + return $this->healthSnapshotIntervalInMilliseconds; + } + /** * Increments success counter */ - public function markSuccess() + public function markSuccess(): void { $this->counter->add(MetricsCounter::SUCCESS); } @@ -67,7 +62,7 @@ public function markSuccess() /** * Increments from cache counter */ - public function markResponseFromCache() + public function markResponseFromCache(): void { $this->counter->add(MetricsCounter::RESPONSE_FROM_CACHE); } @@ -75,7 +70,7 @@ public function markResponseFromCache() /** * Increments failure counter */ - public function markFailure() + public function markFailure(): void { $this->counter->add(MetricsCounter::FAILURE); } @@ -83,7 +78,7 @@ public function markFailure() /** * Increments fallback success counter */ - public function markFallbackSuccess() + public function markFallbackSuccess(): void { $this->counter->add(MetricsCounter::FALLBACK_SUCCESS); } @@ -91,7 +86,7 @@ public function markFallbackSuccess() /** * Increments fallback failure counter */ - public function markFallbackFailure() + public function markFallbackFailure(): void { $this->counter->add(MetricsCounter::FALLBACK_FAILURE); } @@ -99,7 +94,7 @@ public function markFallbackFailure() /** * Increments exception thrown counter */ - public function markExceptionThrown() + public function markExceptionThrown(): void { $this->counter->add(MetricsCounter::EXCEPTION_THROWN); } @@ -107,7 +102,7 @@ public function markExceptionThrown() /** * Increments short circuited counter */ - public function markShortCircuited() + public function markShortCircuited(): void { $this->counter->add(MetricsCounter::SHORT_CIRCUITED); } @@ -116,7 +111,7 @@ public function markShortCircuited() * Resets counters for all metrics * may cause some stats to be removed from reporting, see http://goo.gl/dtHN34 */ - public function resetCounter() + public function resetCounter(): void { $this->counter->reset(); } @@ -124,20 +119,17 @@ public function resetCounter() /** * Returns rolling count for a given metrics type * - * @param integer $type E.g. MetricsCounter::SUCCESS - * @return integer + * @param int $type E.g. MetricsCounter::SUCCESS */ - public function getRollingCount($type) + public function getRollingCount(int $type): int { return $this->counter->get($type); } /** * Returns (and creates when needed) the current health metrics snapshot - * - * @return HealthCountsSnapshot */ - public function getHealthCounts() + public function getHealthCounts(): HealthCountsSnapshot { // current time in milliseconds $now = microtime(true) * 1000; diff --git a/library/Odesk/Phystrix/CommandMetricsFactory.php b/library/Odesk/Phystrix/CommandMetricsFactory.php index d70c60c..40d68c2 100644 --- a/library/Odesk/Phystrix/CommandMetricsFactory.php +++ b/library/Odesk/Phystrix/CommandMetricsFactory.php @@ -27,34 +27,32 @@ */ class CommandMetricsFactory { - /** - * @var array - */ - protected $commandMetricsByCommand = array(); + protected array $commandMetricsByCommand = []; - /** - * @var StateStorageInterface - */ - protected $stateStorage; + protected StateStorageInterface $stateStorage; /** * Constructor - * - * @param StateStorageInterface $stateStorage */ public function __construct(StateStorageInterface $stateStorage) { $this->stateStorage = $stateStorage; } + public function getCommandMetricsByCommand(): array + { + return $this->commandMetricsByCommand; + } + + public function getStateStorage(): StateStorageInterface + { + return $this->stateStorage; + } + /** * Get command metrics instance by command key for given command config - * - * @param string $commandKey - * @param Config $commandConfig - * @return CommandMetrics */ - public function get($commandKey, Config $commandConfig) + public function get(string $commandKey, Config $commandConfig): CommandMetrics { if (!isset($this->commandMetricsByCommand[$commandKey])) { $metricsConfig = $commandConfig->get('metrics'); diff --git a/library/Odesk/Phystrix/Exception/RuntimeException.php b/library/Odesk/Phystrix/Exception/RuntimeException.php index 1179f75..06fdf9b 100644 --- a/library/Odesk/Phystrix/Exception/RuntimeException.php +++ b/library/Odesk/Phystrix/Exception/RuntimeException.php @@ -29,31 +29,25 @@ class RuntimeException extends \RuntimeException { /** * Exception while retrieving the fallback, if enabled - * - * @var Exception */ - private $fallbackException; + private ?Exception $fallbackException; /** * Class name of the command - * - * @var string */ - private $commandClass; + private string $commandClass; /** * Constructor * - * @param string $message - * @param int $commandClass * @param Exception $originalException (Optional) Original exception. May be null if short-circuited * @param Exception $fallbackException (Optional) Exception thrown while retrieving fallback */ public function __construct( - $message, - $commandClass, - Exception $originalException = null, - Exception $fallbackException = null + string $message, + string $commandClass, + ?Exception $originalException = null, + ?Exception $fallbackException = null ) { parent::__construct($message, 0, $originalException); $this->fallbackException = $fallbackException; @@ -62,20 +56,16 @@ public function __construct( /** * Returns class name of the command the exception was thrown from - * - * @return string */ - public function getCommandClass() + public function getCommandClass(): string { return $this->commandClass; } /** * Returns fallback exception if available - * - * @return Exception */ - public function getFallbackException() + public function getFallbackException(): ?Exception { return $this->fallbackException; } diff --git a/library/Odesk/Phystrix/HealthCountsSnapshot.php b/library/Odesk/Phystrix/HealthCountsSnapshot.php index ced3857..f42cf3b 100644 --- a/library/Odesk/Phystrix/HealthCountsSnapshot.php +++ b/library/Odesk/Phystrix/HealthCountsSnapshot.php @@ -25,31 +25,19 @@ */ class HealthCountsSnapshot { - /** - * @var integer - */ - private $successful; + private int $successful; - /** - * @var integer - */ - private $failure; + private int $failure; /** * Time the snapshot was made, in milliseconds - * - * @var integer */ - private $time; + private int $time; /** * Constructor - * - * @param integer $time - * @param integer $successful - * @param integer $failure */ - public function __construct($time, $successful, $failure) + public function __construct(int $time, int $successful, int $failure) { $this->time = $time; $this->failure = $failure; @@ -58,56 +46,46 @@ public function __construct($time, $successful, $failure) /** * Returns the time the snapshot was taken - * - * @return integer */ - public function getTime() + public function getTime(): int { return $this->time; } /** * Returns the number of failures - * - * @return integer */ - public function getFailure() + public function getFailure(): int { return $this->failure; } /** * Returns the number of failures - * - * @return integer */ - public function getSuccessful() + public function getSuccessful(): int { return $this->successful; } /** * Returns the total sum of requests made - * - * @return integer */ - public function getTotal() + public function getTotal(): int { return $this->successful + $this->failure; } /** * Returns error percentage - * - * @return float */ - public function getErrorPercentage() + public function getErrorPercentage(): float { $total = $this->getTotal(); - if (!$total) { + if ($total === 0) { return 0; - } else { - return $this->getFailure() / $total * 100; } + + return $this->getFailure() / $total * 100; } } diff --git a/library/Odesk/Phystrix/MetricsCounter.php b/library/Odesk/Phystrix/MetricsCounter.php index 68b3600..ca46605 100644 --- a/library/Odesk/Phystrix/MetricsCounter.php +++ b/library/Odesk/Phystrix/MetricsCounter.php @@ -38,50 +38,38 @@ class MetricsCounter EXCEPTION_THROWN = 8, RESPONSE_FROM_CACHE = 9; - /** - * @var string - */ - private $commandKey; + private string $commandKey; - /** - * @var StateStorageInterface - */ - private $stateStorage; + private StateStorageInterface $stateStorage; /** * Time span to track counters, in milliseconds - * - * @var integer */ - private $rollingStatisticalWindowInMilliseconds; + private int $rollingStatisticalWindowInMilliseconds; /** * Number of buckets within the statistical window - * - * @var integer */ - private $rollingStatisticalWindowBuckets; + private int $rollingStatisticalWindowBuckets; /** * Size of a bucket in milliseconds - * - * @var float */ - private $bucketInMilliseconds; + private float $bucketInMilliseconds; /** * Constructor * * @param string $commandKey * @param StateStorageInterface $stateStorage - * @param integer $rollingStatisticalWindowInMilliseconds Time span in milliseconds - * @param integer $rollingStatisticalWindowBuckets The number of buckets in the statistical window + * @param int $rollingStatisticalWindowInMilliseconds Time span in milliseconds + * @param int $rollingStatisticalWindowBuckets The number of buckets in the statistical window */ public function __construct( - $commandKey, + string $commandKey, StateStorageInterface $stateStorage, - $rollingStatisticalWindowInMilliseconds, - $rollingStatisticalWindowBuckets + int $rollingStatisticalWindowInMilliseconds, + int $rollingStatisticalWindowBuckets ) { $this->commandKey = $commandKey; $this->stateStorage = $stateStorage; @@ -91,23 +79,38 @@ public function __construct( $this->rollingStatisticalWindowInMilliseconds / $this->rollingStatisticalWindowBuckets; } + public function getCommandKey(): string + { + return $this->commandKey; + } + + public function getRollingStatisticalWindowInMilliseconds(): int + { + return $this->rollingStatisticalWindowInMilliseconds; + } + + public function getRollingStatisticalWindowBuckets(): int + { + return $this->rollingStatisticalWindowBuckets; + } + + public function getBucketInMilliseconds(): float + { + return $this->bucketInMilliseconds; + } + /** * Increase counter for given metric type - * - * @param integer $type */ - public function add($type) + public function add(int $type): void { $this->stateStorage->incrementBucket($this->commandKey, $type, $this->getCurrentBucketIndex()); } /** * Calculates sum for given metric type within the statistical window - * - * @param integer $type - * @return integer */ - public function get($type) + public function get(int $type): int { $sum = 0; $now = $this->getTimeInMilliseconds(); @@ -122,20 +125,16 @@ public function get($type) /** * Returns current time on the server in milliseconds - * - * @return float */ - private function getTimeInMilliseconds() + private function getTimeInMilliseconds(): float { return floor(microtime(true) * 1000); } /** * Returns unique index for the current bucket - * - * @return integer */ - private function getCurrentBucketIndex() + private function getCurrentBucketIndex(): int { return $this->getBucketIndex(0, $this->getTimeInMilliseconds()); } @@ -143,11 +142,10 @@ private function getCurrentBucketIndex() /** * Gets unique bucket index by current time and bucket sequential number in the statistical window * - * @param integer $bucketNumber - * @param integer $time Current time in milliseconds - * @return float + * @param int $bucketNumber + * @param int $time Current time in milliseconds */ - private function getBucketIndex($bucketNumber, $time) + private function getBucketIndex(int $bucketNumber, int $time): float { // Getting unique bucket index return floor(($time - $bucketNumber * $this->bucketInMilliseconds) / $this->bucketInMilliseconds); @@ -162,7 +160,7 @@ private function getBucketIndex($bucketNumber, $time) * * May cause short-circuited stats to be removed from reporting, see http://goo.gl/dtHN34 */ - public function reset() + public function reset(): void { // For each type of metric, we attempt to set the counter to 0 foreach ( diff --git a/library/Odesk/Phystrix/MetricsEventStream/ApcMetricsPoller.php b/library/Odesk/Phystrix/MetricsEventStream/ApcMetricsPoller.php index 5b8ed8f..19e9401 100644 --- a/library/Odesk/Phystrix/MetricsEventStream/ApcMetricsPoller.php +++ b/library/Odesk/Phystrix/MetricsEventStream/ApcMetricsPoller.php @@ -22,9 +22,11 @@ use APCIterator; use Odesk\Phystrix\ApcStateStorage; +use Odesk\Phystrix\CircuitBreakerFactory; +use Odesk\Phystrix\CommandMetricsFactory; use Odesk\Phystrix\MetricsCounter; use RuntimeException; -use Zend\Config\Config; +use Laminas\Config\Config; /** * The class attempts to find counters for all commands currently running @@ -32,25 +34,13 @@ */ class ApcMetricsPoller implements MetricsPollerInterface { - /** - * @var Config - */ - protected $config; + protected Config $config; - /** - * @var array - */ - protected $configsPerCommandKey = array(); + protected array $configsPerCommandKey = []; - /** - * @var \Odesk\Phystrix\CommandMetricsFactory - */ - protected $commandMetricsFactory; + protected CommandMetricsFactory $commandMetricsFactory; - /** - * @var \Odesk\Phystrix\CircuitBreakerFactory - */ - protected $circuitBreakerFactory; + protected CircuitBreakerFactory $circuitBreakerFactory; /** * Constructor @@ -62,9 +52,9 @@ public function __construct(Config $config) { $this->config = $config; - $stateStorage = new \Odesk\Phystrix\ApcStateStorage(); - $this->commandMetricsFactory = new \Odesk\Phystrix\CommandMetricsFactory($stateStorage); - $this->circuitBreakerFactory = new \Odesk\Phystrix\CircuitBreakerFactory($stateStorage); + $stateStorage = new ApcStateStorage(); + $this->commandMetricsFactory = new CommandMetricsFactory($stateStorage); + $this->circuitBreakerFactory = new CircuitBreakerFactory($stateStorage); } /** @@ -73,7 +63,7 @@ public function __construct(Config $config) * @param string $commandKey * @return Config */ - protected function getCommandConfig($commandKey) + protected function getCommandConfig(string $commandKey): Config { if (isset($this->configsPerCommandKey[$commandKey])) { return $this->configsPerCommandKey[$commandKey]; @@ -84,18 +74,18 @@ protected function getCommandConfig($commandKey) $config->merge($commandConfig); } $this->configsPerCommandKey[$commandKey] = $config; + return $config; } /** * Finds all commands currently running (having any metrics recorded within the statistical rolling window). * - * @return array * @throws RuntimeException When entry with invalid name found in cache */ - protected function getCommandsRunning() + protected function getCommandsRunning(): array { - $commandKeys = array(); + $commandKeys = []; foreach (new APCIterator('user', '/^' . ApcStateStorage::CACHE_PREFIX . '/') as $counter) { // APC entries do not expire within one request context so we have to check manually: if ($counter['creation_time'] + $counter['ttl'] < time()) { @@ -117,15 +107,14 @@ protected function getCommandsRunning() } } } + return $commandKeys; } /** * Returns current time on the server in milliseconds - * - * @return float */ - private function getTimeInMilliseconds() + private function getTimeInMilliseconds(): float { return floor(microtime(true) * 1000); } @@ -133,19 +122,17 @@ private function getTimeInMilliseconds() /** * Finds all commands currently running (having any metrics recorded within the statistical rolling window). * For each command key prepares a set of statistic. Returns all sets. - * - * @return array */ - public function getStatsForCommandsRunning() + public function getStatsForCommandsRunning(): array { - $stats = array(); + $stats = []; $commandKeys = $this->getCommandsRunning(); foreach ($commandKeys as $commandKey) { $commandConfig = $this->getCommandConfig($commandKey); $commandMetrics = $this->commandMetricsFactory->get($commandKey, $commandConfig); $circuitBreaker = $this->circuitBreakerFactory->get($commandKey, $commandConfig, $commandMetrics); $healtCounts = $commandMetrics->getHealthCounts(); - $commandStats = array( + $commandStats = [ // We have to use "HystrixCommand" exactly, otherwise it won't work 'type' => 'HystrixCommand', 'name' => $commandKey, @@ -206,10 +193,11 @@ public function getStatsForCommandsRunning() 'propertyValue_requestLogEnabled' => $commandConfig->get('requestLog')->get('enabled'), 'reportingHosts' => 1, - ); + ]; $stats[] = $commandStats; } + return $stats; } } diff --git a/library/Odesk/Phystrix/MetricsEventStream/ApcuMetricsPoller.php b/library/Odesk/Phystrix/MetricsEventStream/ApcuMetricsPoller.php index 90325f2..7fb2281 100644 --- a/library/Odesk/Phystrix/MetricsEventStream/ApcuMetricsPoller.php +++ b/library/Odesk/Phystrix/MetricsEventStream/ApcuMetricsPoller.php @@ -22,9 +22,12 @@ use APCUIterator; use Odesk\Phystrix\ApcStateStorage; +use Odesk\Phystrix\ApcuStateStorage; +use Odesk\Phystrix\CircuitBreakerFactory; +use Odesk\Phystrix\CommandMetricsFactory; use Odesk\Phystrix\MetricsCounter; use RuntimeException; -use Zend\Config\Config; +use Laminas\Config\Config; /** * The class attempts to find counters for all commands currently running @@ -32,25 +35,13 @@ */ class ApcuMetricsPoller implements MetricsPollerInterface { - /** - * @var Config - */ - protected $config; + protected Config $config; - /** - * @var array - */ - protected $configsPerCommandKey = array(); + protected array $configsPerCommandKey = []; - /** - * @var \Odesk\Phystrix\CommandMetricsFactory - */ - protected $commandMetricsFactory; + protected CommandMetricsFactory $commandMetricsFactory; - /** - * @var \Odesk\Phystrix\CircuitBreakerFactory - */ - protected $circuitBreakerFactory; + protected CircuitBreakerFactory $circuitBreakerFactory; /** * Constructor @@ -62,9 +53,9 @@ public function __construct(Config $config) { $this->config = $config; - $stateStorage = new \Odesk\Phystrix\ApcuStateStorage(); - $this->commandMetricsFactory = new \Odesk\Phystrix\CommandMetricsFactory($stateStorage); - $this->circuitBreakerFactory = new \Odesk\Phystrix\CircuitBreakerFactory($stateStorage); + $stateStorage = new ApcuStateStorage(); + $this->commandMetricsFactory = new CommandMetricsFactory($stateStorage); + $this->circuitBreakerFactory = new CircuitBreakerFactory($stateStorage); } /** @@ -73,7 +64,7 @@ public function __construct(Config $config) * @param string $commandKey * @return Config */ - protected function getCommandConfig($commandKey) + protected function getCommandConfig(string $commandKey): Config { if (isset($this->configsPerCommandKey[$commandKey])) { return $this->configsPerCommandKey[$commandKey]; @@ -84,18 +75,18 @@ protected function getCommandConfig($commandKey) $config->merge($commandConfig); } $this->configsPerCommandKey[$commandKey] = $config; + return $config; } /** * Finds all commands currently running (having any metrics recorded within the statistical rolling window). * - * @return array * @throws RuntimeException When entry with invalid name found in cache */ - protected function getCommandsRunning() + protected function getCommandsRunning(): array { - $commandKeys = array(); + $commandKeys = []; foreach (new APCUIterator('/^' . ApcStateStorage::CACHE_PREFIX . '/') as $counter) { // APC entries do not expire within one request context so we have to check manually: if ($counter['creation_time'] + $counter['ttl'] < time()) { @@ -117,15 +108,14 @@ protected function getCommandsRunning() } } } + return $commandKeys; } /** * Returns current time on the server in milliseconds - * - * @return float */ - private function getTimeInMilliseconds() + private function getTimeInMilliseconds(): float { return floor(microtime(true) * 1000); } @@ -133,19 +123,17 @@ private function getTimeInMilliseconds() /** * Finds all commands currently running (having any metrics recorded within the statistical rolling window). * For each command key prepares a set of statistic. Returns all sets. - * - * @return array */ - public function getStatsForCommandsRunning() + public function getStatsForCommandsRunning(): array { - $stats = array(); + $stats = []; $commandKeys = $this->getCommandsRunning(); foreach ($commandKeys as $commandKey) { $commandConfig = $this->getCommandConfig($commandKey); $commandMetrics = $this->commandMetricsFactory->get($commandKey, $commandConfig); $circuitBreaker = $this->circuitBreakerFactory->get($commandKey, $commandConfig, $commandMetrics); $healtCounts = $commandMetrics->getHealthCounts(); - $commandStats = array( + $commandStats = [ // We have to use "HystrixCommand" exactly, otherwise it won't work 'type' => 'HystrixCommand', 'name' => $commandKey, @@ -206,10 +194,11 @@ public function getStatsForCommandsRunning() 'propertyValue_requestLogEnabled' => $commandConfig->get('requestLog')->get('enabled'), 'reportingHosts' => 1, - ); + ]; $stats[] = $commandStats; } + return $stats; } } diff --git a/library/Odesk/Phystrix/MetricsEventStream/MetricsPollerInterface.php b/library/Odesk/Phystrix/MetricsEventStream/MetricsPollerInterface.php index c25f0fd..eee1558 100644 --- a/library/Odesk/Phystrix/MetricsEventStream/MetricsPollerInterface.php +++ b/library/Odesk/Phystrix/MetricsEventStream/MetricsPollerInterface.php @@ -28,8 +28,6 @@ interface MetricsPollerInterface /** * Finds all commands currently running (having any metrics recorded within the statistical rolling window). * For each command key prepares a set of statistic. Returns all sets. - * - * @return array */ - public function getStatsForCommandsRunning(); + public function getStatsForCommandsRunning(): array; } diff --git a/library/Odesk/Phystrix/MetricsEventStream/MetricsServer.php b/library/Odesk/Phystrix/MetricsEventStream/MetricsServer.php index aad00c4..ed0d955 100644 --- a/library/Odesk/Phystrix/MetricsEventStream/MetricsServer.php +++ b/library/Odesk/Phystrix/MetricsEventStream/MetricsServer.php @@ -27,23 +27,14 @@ class MetricsServer { public const DEFAULT_DELAY = 500; // in milliseconds - /** - * @var integer - */ - protected $delay; + protected int $delay; - /** - * @var MetricsPollerInterface - */ - protected $metricsPoller; + protected MetricsPollerInterface $metricsPoller; /** * Constructor - * - * @param MetricsPollerInterface $metricsPoller - * @param int $delay */ - public function __construct(MetricsPollerInterface $metricsPoller, $delay = self::DEFAULT_DELAY) + public function __construct(MetricsPollerInterface $metricsPoller, int $delay = self::DEFAULT_DELAY) { $this->metricsPoller = $metricsPoller; $this->delay = $delay; @@ -52,7 +43,7 @@ public function __construct(MetricsPollerInterface $metricsPoller, $delay = self /** * Serves text/event-stream format */ - public function run() + public function run(): void { header('HTTP/1.1 200 OK'); header('Content-Type: text/event-stream;charset=UTF-8'); @@ -64,7 +55,7 @@ public function run() } } - protected function runStream() + protected function runStream(): void { $stats = $this->metricsPoller->getStatsForCommandsRunning(); diff --git a/library/Odesk/Phystrix/NoOpCircuitBreaker.php b/library/Odesk/Phystrix/NoOpCircuitBreaker.php index ad1aec8..10ba8c4 100644 --- a/library/Odesk/Phystrix/NoOpCircuitBreaker.php +++ b/library/Odesk/Phystrix/NoOpCircuitBreaker.php @@ -20,37 +20,53 @@ namespace Odesk\Phystrix; +use Laminas\Config\Config; + /** * A not operational circuit breaker, will always like as a closed circuit */ class NoOpCircuitBreaker implements CircuitBreakerInterface { + public function getMetrics(): CommandMetrics + { + // TODO: Implement getMetrics() method. + } + + public function getConfig(): Config + { + // TODO: Implement getConfig() method. + } + + public function getStateStorage(): StateStorageInterface + { + // TODO: Implement getStateStorage() method. + } + + public function getCommandKey(): string + { + // TODO: Implement getCommandKey() method. + } + /** * Single test will always be allowed - * - * @return boolean */ - public function allowSingleTest() + public function allowSingleTest(): bool { return true; } /** * Request will always be allowed - * - * @return boolean */ - public function allowRequest() + public function allowRequest(): bool { return true; } /** * Circuit is never closed - * - * @return boolean */ - public function isOpen() + public function isOpen(): bool { return false; } @@ -58,7 +74,7 @@ public function isOpen() /** * Does nothing (enforced by Circuit Breaker interface) */ - public function markSuccess() + public function markSuccess(): void { } } diff --git a/library/Odesk/Phystrix/StateStorageInterface.php b/library/Odesk/Phystrix/StateStorageInterface.php index b61c1fc..93c7af2 100644 --- a/library/Odesk/Phystrix/StateStorageInterface.php +++ b/library/Odesk/Phystrix/StateStorageInterface.php @@ -27,61 +27,39 @@ interface StateStorageInterface { /** * Increments counter value for the given bucket - * - * @param string $commandKey - * @param string $type - * @param integer $index */ - public function incrementBucket($commandKey, $type, $index); + public function incrementBucket(string $commandKey, string $type, int $index): void; /** * Returns counter value for the given bucket - * - * @param string $commandKey - * @param string $type - * @param integer $index - * @return integer */ - public function getBucket($commandKey, $type, $index); + public function getBucket(string $commandKey, string $type, int $index): ?int; /** * Marks the given circuit as open * - * @param string $commandKey Circuit key - * @param integer $sleepingWindowInMilliseconds In how much time we should allow a single test + * @param int $sleepingWindowInMilliseconds In how much time we should allow a single test */ - public function openCircuit($commandKey, $sleepingWindowInMilliseconds); + public function openCircuit(string $commandKey, int $sleepingWindowInMilliseconds): void; /** * Marks the given circuit as closed - * - * @param string $commandKey Circuit key + */ - public function closeCircuit($commandKey); + public function closeCircuit(string $commandKey): void; /** * Whether a single test is allowed - * - * @param string $commandKey Circuit breaker key - * @param integer $sleepingWindowInMilliseconds In how much time we should allow the next single test - * @return boolean */ - public function allowSingleTest($commandKey, $sleepingWindowInMilliseconds); + public function allowSingleTest(string $commandKey, int $sleepingWindowInMilliseconds): bool; /** * Whether a circuit is open - * - * @param string $commandKey Circuit breaker key - * @return boolean */ - public function isCircuitOpen($commandKey); + public function isCircuitOpen(string $commandKey): bool; /** * If the given bucket is found, sets counter value to 0. - * - * @param string $commandKey Circuit breaker key - * @param string $type - * @param integer $index */ - public function resetBucket($commandKey, $type, $index); + public function resetBucket(string $commandKey, string $type, int $index): void; } diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 4f4d326..da720e0 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,36 +1,31 @@ - + ./tests/Tests - + + + library/ + + - - - - ./vendor - ./tests/ - - - ./library - - - diff --git a/tests/Tests/Odesk/Phystrix/ArrayStateStorageTest.php b/tests/Tests/Odesk/Phystrix/ArrayStateStorageTest.php index c5e24c2..9be5672 100644 --- a/tests/Tests/Odesk/Phystrix/ArrayStateStorageTest.php +++ b/tests/Tests/Odesk/Phystrix/ArrayStateStorageTest.php @@ -21,21 +21,18 @@ namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\ArrayStateStorage; -use PHPUnit_Framework_TestCase; +use Tests\Odesk\TestCase; -class ArrayStateStorageTest extends PHPUnit_Framework_TestCase +class ArrayStateStorageTest extends TestCase { - /** - * @var ArrayStateStorage - */ - protected $storage; + protected ArrayStateStorage $storage; - protected function setUp() + protected function setUp(): void { $this->storage = new ArrayStateStorage(); } - public function testIncrementAndGetBucket() + public function testIncrementAndGetBucket(): void { $this->assertNull($this->storage->getBucket('TestCommand', 'success', 2)); $this->storage->incrementBucket('TestCommand', 'success', 2); @@ -52,7 +49,7 @@ public function testIncrementAndGetBucket() $this->assertEquals(1, $this->storage->getBucket('OtherTestCommand', 'success', 1)); } - public function testResetBucket() + public function testResetBucket(): void { $this->storage->incrementBucket('TestCommand', 'success', 2); $this->storage->incrementBucket('TestCommand', 'success', 2); @@ -63,14 +60,14 @@ public function testResetBucket() $this->assertEquals(0, $this->storage->getBucket('TestCommand', 'success', 2)); } - public function testOpenCircuit() + public function testOpenCircuit(): void { $this->assertFalse($this->storage->isCircuitOpen('TestCommand')); $this->storage->openCircuit('TestCommand', 1000); $this->assertTrue($this->storage->isCircuitOpen('TestCommand')); } - public function testIsCircuitOpen() + public function testIsCircuitOpen(): void { $this->storage->openCircuit('TestCommand', 1000); $this->assertTrue($this->storage->isCircuitOpen('TestCommand')); @@ -78,7 +75,7 @@ public function testIsCircuitOpen() $this->assertFalse($this->storage->isCircuitOpen('TestCommand')); } - public function testCloseCircuit() + public function testCloseCircuit(): void { $this->storage->openCircuit('TestCommand', 1000); $this->assertTrue($this->storage->isCircuitOpen('TestCommand')); @@ -86,7 +83,7 @@ public function testCloseCircuit() $this->assertFalse($this->storage->isCircuitOpen('TestCommand')); } - public function testAllowSingleTest() + public function testAllowSingleTest(): void { // there is no point in checking, but when circuit is closed, the test is allowed also $this->assertTrue($this->storage->allowSingleTest('TestCommand', 900)); diff --git a/tests/Tests/Odesk/Phystrix/CircuitBreakerFactoryTest.php b/tests/Tests/Odesk/Phystrix/CircuitBreakerFactoryTest.php index a1311e5..ad71657 100644 --- a/tests/Tests/Odesk/Phystrix/CircuitBreakerFactoryTest.php +++ b/tests/Tests/Odesk/Phystrix/CircuitBreakerFactoryTest.php @@ -20,62 +20,61 @@ namespace Tests\Odesk\Phystrix; +use Laminas\Config\Config; use Odesk\Phystrix\CircuitBreakerFactory; use Odesk\Phystrix\CommandMetrics; +use Odesk\Phystrix\NoOpCircuitBreaker; +use Odesk\Phystrix\StateStorageInterface; +use Tests\Odesk\TestCase; -class CircuitBreakerFactoryTest extends \PHPUnit_Framework_TestCase +class CircuitBreakerFactoryTest extends TestCase { - /** - * @var CircuitBreakerFactory - */ - protected $factory; + protected CircuitBreakerFactory $factory; - /** - * @var CommandMetrics - */ - protected $metrics; + protected CommandMetrics $metrics; - protected static $baseConfig = array( - 'circuitBreaker' => array( + protected static array $baseConfig = [ + 'circuitBreaker' => [ 'enabled' => true, - ) - ); + ] + ]; - protected function setUp() + protected function setUp(): void { - $this->factory = new CircuitBreakerFactory($this->createMock('Odesk\Phystrix\StateStorageInterface')); - $this->metrics = $this->createMock('Odesk\Phystrix\CommandMetrics', array(), array(), '', false); + $this->factory = new CircuitBreakerFactory($this->createMock(StateStorageInterface::class)); + $this->metrics = $this->createMock(CommandMetrics::class); } - public function testGetNoOpCircuitBreaker() + public function testGetNoOpCircuitBreaker(): void { $config = self::$baseConfig; $config['circuitBreaker']['enabled'] = false; - $config = new \Laminas\Config\Config($config); + $config = new Config($config); $circuitBreaker = $this->factory->get('TestCommand', $config, $this->metrics); - $this->assertInstanceOf('Odesk\Phystrix\NoOpCircuitBreaker', $circuitBreaker); + $this->assertInstanceOf(NoOpCircuitBreaker::class, $circuitBreaker); } public function testGetInstantiatesOnce() { $config = self::$baseConfig; $config['circuitBreaker']['enabled'] = false; - $config = new \Laminas\Config\Config($config); + $config = new Config($config); // this will be a NoOpCircuitBreaker $circuitBreaker = $this->factory->get('TestCommand', $config, $this->metrics); // now trying to get the same circuit breaker with a different config $circuitBreakerB - = $this->factory->get('TestCommand', new \Laminas\Config\Config(self::$baseConfig), $this->metrics); + = $this->factory->get('TestCommand', new Config(self::$baseConfig), $this->metrics); $this->assertEquals($circuitBreaker, $circuitBreakerB); } - public function testGetInjectsParameters() + public function testGetInjectsParameters(): void { - $config = new \Laminas\Config\Config(self::$baseConfig); + $config = new Config(self::$baseConfig); $circuitBreaker = $this->factory->get('TestCommand', $config, $this->metrics); - $this->assertAttributeEquals('TestCommand', 'commandKey', $circuitBreaker); - $this->assertAttributeEquals($config, 'config', $circuitBreaker); - $this->assertAttributeInstanceOf('Odesk\Phystrix\CommandMetrics', 'metrics', $circuitBreaker); - $this->assertAttributeInstanceOf('Odesk\Phystrix\StateStorageInterface', 'stateStorage', $circuitBreaker); + + $this->assertEquals('TestCommand', $circuitBreaker->getCommandKey()); + $this->assertEquals($config, $circuitBreaker->getConfig()); + $this->assertInstanceOf(CommandMetrics::class, $circuitBreaker->getMetrics()); + $this->assertInstanceOf(StateStorageInterface::class, $circuitBreaker->getStateStorage()); } } diff --git a/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php b/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php index 0368928..4eec2c5 100644 --- a/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php +++ b/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php @@ -20,29 +20,28 @@ namespace Tests\Odesk\Phystrix; +use Laminas\Config\Config; use Odesk\Phystrix\CircuitBreaker; +use Odesk\Phystrix\CommandMetrics; +use Odesk\Phystrix\HealthCountsSnapshot; +use Odesk\Phystrix\StateStorageInterface; +use Tests\Odesk\TestCase; -class CircuitBreakerTest extends \PHPUnit_Framework_TestCase +class CircuitBreakerTest extends TestCase { - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $metrics; + protected CommandMetrics $metrics; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $stateStorage; + protected StateStorageInterface $stateStorage; - protected function setUp() + protected function setUp(): void { - $this->metrics = $this->createMock('Odesk\Phystrix\CommandMetrics', array(), array(), '', false); - $this->stateStorage = $this->createMock('Odesk\Phystrix\StateStorageInterface'); + $this->metrics = $this->createMock(CommandMetrics::class); + $this->stateStorage = $this->createMock(StateStorageInterface::class); } - protected function getCircuitBreaker($config = array()) + protected function getCircuitBreaker($config = array()): CircuitBreaker { - $commandConfig = new \Laminas\Config\Config(array( + $commandConfig = new Config(array( 'circuitBreaker' => array( 'enabled' => true, 'errorThresholdPercentage' => 50, @@ -57,13 +56,13 @@ protected function getCircuitBreaker($config = array()) ) ), ), true); - $commandConfig->merge(new \Laminas\Config\Config($config, true)); + $commandConfig->merge(new Config($config, true)); return new CircuitBreaker('TestCommand', $this->metrics, $commandConfig, $this->stateStorage); } - public function testIsOpenReturnsTrueImmediately() + public function testIsOpenReturnsTrueImmediately(): void { $this->stateStorage->expects($this->once()) ->method('isCircuitOpen') @@ -76,14 +75,14 @@ public function testIsOpenReturnsTrueImmediately() $this->assertTrue($this->getCircuitBreaker()->isOpen()); } - public function testIsOpenNotPastTheThreshold() + public function testIsOpenNotPastTheThreshold(): void { $this->stateStorage->expects($this->once()) ->method('isCircuitOpen') ->with($this->equalTo('TestCommand')) ->will($this->returnValue(false)); - $healthCounts = $this->createMock('Odesk\Phystrix\HealthCountsSnapshot', array(), array(), '', false); + $healthCounts = $this->createMock(HealthCountsSnapshot::class); $healthCounts->expects($this->once()) ->method('getTotal') ->will($this->returnValue(47)); // total is 47, threshold is set to 50. @@ -97,9 +96,9 @@ public function testIsOpenNotPastTheThreshold() $this->assertFalse($this->getCircuitBreaker()->isOpen()); } - public function testIsOpenErrorPercentageNotBigEnough() + public function testIsOpenErrorPercentageNotBigEnough(): void { - $healthCounts = $this->createMock('Odesk\Phystrix\HealthCountsSnapshot', array(), array(), '', false); + $healthCounts = $this->createMock(HealthCountsSnapshot::class); $healthCounts->expects($this->once()) ->method('getTotal') ->will($this->returnValue(60)); // total is 60, threshold is set to 50. @@ -113,9 +112,9 @@ public function testIsOpenErrorPercentageNotBigEnough() $this->assertFalse($this->getCircuitBreaker()->isOpen()); } - public function testIsOpenOpensCircuit() + public function testIsOpenOpensCircuit(): void { - $healthCounts = $this->createMock('Odesk\Phystrix\HealthCountsSnapshot', array(), array(), '', false); + $healthCounts = $this->createMock(HealthCountsSnapshot::class); $healthCounts->expects($this->once()) ->method('getTotal') ->will($this->returnValue(60)); // total is 60, threshold is set to 50. @@ -133,7 +132,7 @@ public function testIsOpenOpensCircuit() $this->assertTrue($this->getCircuitBreaker()->isOpen()); } - public function testAllowSingleTest() + public function testAllowSingleTest(): void { $this->stateStorage->expects($this->at(0)) ->method('allowSingleTest') @@ -149,7 +148,7 @@ public function testAllowSingleTest() $this->assertTrue($this->getCircuitBreaker()->allowSingleTest()); } - public function testAllowRequestForceOpen() + public function testAllowRequestForceOpen(): void { $this->stateStorage->expects($this->never()) ->method('isCircuitOpen'); // making sure it doesn't get to checking if the circuit is open @@ -157,7 +156,7 @@ public function testAllowRequestForceOpen() $this->assertFalse($circuitBreaker->allowRequest()); } - public function testAllowRequestForceClose() + public function testAllowRequestForceClose(): void { $this->stateStorage->expects($this->never()) ->method('isCircuitOpen'); // making sure it doesn't get to checking if the circuit is open @@ -165,7 +164,7 @@ public function testAllowRequestForceClose() $this->assertTrue($circuitBreaker->allowRequest()); } - public function testMarkSuccessClosesCircuitIfOpenAndResetCounter() + public function testMarkSuccessClosesCircuitIfOpenAndResetCounter(): void { $this->stateStorage->expects($this->once()) ->method('isCircuitOpen') diff --git a/tests/Tests/Odesk/Phystrix/CommandFactoryTest.php b/tests/Tests/Odesk/Phystrix/CommandFactoryTest.php index 3375f96..2cc38c9 100644 --- a/tests/Tests/Odesk/Phystrix/CommandFactoryTest.php +++ b/tests/Tests/Odesk/Phystrix/CommandFactoryTest.php @@ -21,26 +21,28 @@ namespace Tests\Odesk\Phystrix; use DI\ContainerBuilder; +use Laminas\Config\Config; use Odesk\Phystrix\CircuitBreakerFactory; use Odesk\Phystrix\CommandFactory; use Odesk\Phystrix\CommandMetricsFactory; use Odesk\Phystrix\RequestCache; use Odesk\Phystrix\RequestLog; -use PHPUnit_Framework_TestCase; +use Odesk\Phystrix\StateStorageInterface; use ReflectionException; +use Tests\Odesk\TestCase; -class CommandFactoryTest extends PHPUnit_Framework_TestCase +class CommandFactoryTest extends TestCase { - public function testGetCommand() + public function testGetCommand(): void { - $config = new \Laminas\Config\Config(array( - 'default' => array( - 'fallback' => array('enabled' => true) - ) - )); + $config = new Config([ + 'default' => [ + 'fallback' => ['enabled' => true], + ], + ]); $container = ContainerBuilder::buildDevContainer(); - /** @var \Odesk\Phystrix\StateStorageInterface $stateStorage */ - $stateStorage = $this->createMock('Odesk\Phystrix\StateStorageInterface'); + /** @var StateStorageInterface $stateStorage */ + $stateStorage = $this->createMock(StateStorageInterface::class); $circuitBreakerFactory = new CircuitBreakerFactory($stateStorage); $commandMetricsFactory = new CommandMetricsFactory($stateStorage); $requestCache = new RequestCache(); @@ -54,19 +56,19 @@ public function testGetCommand() $container ); /** @var FactoryCommandMock $command */ - $command = $commandFactory->getCommand('Tests\Odesk\Phystrix\FactoryCommandMock', 'test', 'hello'); + $command = $commandFactory->getCommand(FactoryCommandMock::class, 'test', 'hello'); // injects constructor parameters $this->assertEquals('test', $command->a); $this->assertEquals('hello', $command->b); // injects the infrastructure components - $expectedDefaultConfig = new \Laminas\Config\Config(array( - 'fallback' => array('enabled' => true) - ), true); - $this->assertAttributeEquals($expectedDefaultConfig, 'config', $command); - $this->assertAttributeEquals($circuitBreakerFactory, 'circuitBreakerFactory', $command); - $this->assertAttributeEquals($container, 'container', $command); - $this->assertAttributeEquals($requestCache, 'requestCache', $command); - $this->assertAttributeEquals($requestLog, 'requestLog', $command); + $expectedDefaultConfig = new Config([ + 'fallback' => ['enabled' => true], + ], true); + $this->assertEquals($expectedDefaultConfig, $command->getConfig()); + $this->assertEquals($circuitBreakerFactory, $command->getCircuitBreakerFactory()); + $this->assertEquals($container, $command->getContainer()); + $this->assertEquals($requestCache, $command->getRequestCache()); + $this->assertEquals($requestLog, $command->getRequestLog()); } /** @@ -74,19 +76,19 @@ public function testGetCommand() */ public function testGetCommandMergesConfig() { - $config = new \Laminas\Config\Config(array( - 'default' => array( - 'fallback' => array('enabled' => true), - 'customData' => 12345 - ), - 'Tests.Odesk.Phystrix.FactoryCommandMock' => array( - 'fallback' => array('enabled' => false), - 'circuitBreaker' => array('enabled' => false) - ) - )); + $config = new Config([ + 'default' => [ + 'fallback' => ['enabled' => true], + 'customData' => 12345, + ], + 'Tests.Odesk.Phystrix.FactoryCommandMock' => [ + 'fallback' => ['enabled' => false], + 'circuitBreaker' => ['enabled' => false], + ], + ]); $container = ContainerBuilder::buildDevContainer(); - /** @var \Odesk\Phystrix\StateStorageInterface $stateStorage */ - $stateStorage = $this->createMock('Odesk\Phystrix\StateStorageInterface'); + /** @var StateStorageInterface $stateStorage */ + $stateStorage = $this->createMock(StateStorageInterface::class); $circuitBreakerFactory = new CircuitBreakerFactory($stateStorage); $commandMetricsFactory = new CommandMetricsFactory($stateStorage); $commandFactory = new CommandFactory( @@ -98,12 +100,12 @@ public function testGetCommandMergesConfig() $container ); /** @var FactoryCommandMock $command */ - $command = $commandFactory->getCommand('Tests\Odesk\Phystrix\FactoryCommandMock', 'test', 'hello'); - $expectedConfig = new \Laminas\Config\Config(array( - 'fallback' => array('enabled' => false), - 'circuitBreaker' => array('enabled' => false), - 'customData' => 12345 - ), true); - $this->assertAttributeEquals($expectedConfig, 'config', $command); + $command = $commandFactory->getCommand(FactoryCommandMock::class, 'test', 'hello'); + $expectedConfig = new Config([ + 'fallback' => ['enabled' => false], + 'circuitBreaker' => ['enabled' => false], + 'customData' => 12345, + ], true); + $this->assertEquals($expectedConfig, $command->getConfig()); } } diff --git a/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php b/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php index c15ee77..cdbcfab 100644 --- a/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php +++ b/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php @@ -20,15 +20,19 @@ namespace Tests\Odesk\Phystrix; +use Laminas\Config\Config; use Odesk\Phystrix\ArrayStateStorage; +use Odesk\Phystrix\CommandMetrics; use Odesk\Phystrix\CommandMetricsFactory; +use Odesk\Phystrix\MetricsCounter; use ReflectionClass; +use Tests\Odesk\TestCase; -class CommandMetricsFactoryTest extends \PHPUnit_Framework_TestCase +class CommandMetricsFactoryTest extends TestCase { - public function testGet() + public function testGet(): void { - $config = new \Laminas\Config\Config(array( + $config = new Config(array( 'metrics' => array( 'rollingStatisticalWindowInMilliseconds' => 10000, 'rollingStatisticalWindowBuckets' => 10, @@ -37,15 +41,16 @@ public function testGet() )); $factory = new CommandMetricsFactory(new ArrayStateStorage()); $metrics = $factory->get('TestCommand', $config); - $this->assertAttributeEquals(2000, 'healthSnapshotIntervalInMilliseconds', $metrics); + $this->assertEquals(2000, $metrics->getHealthSnapshotIntervalInMilliseconds()); - $reflection = new ReflectionClass('Odesk\Phystrix\CommandMetrics'); + $reflection = new ReflectionClass(CommandMetrics::class); $property = $reflection->getProperty('counter'); $property->setAccessible(true); + /** @var MetricsCounter $counter */ $counter = $property->getValue($metrics); - $this->assertAttributeEquals('TestCommand', 'commandKey', $counter); - $this->assertAttributeEquals(10000, 'rollingStatisticalWindowInMilliseconds', $counter); - $this->assertAttributeEquals(10, 'rollingStatisticalWindowBuckets', $counter); - $this->assertAttributeEquals(1000, 'bucketInMilliseconds', $counter); // 10000 / 10 = 1000 + $this->assertEquals('TestCommand', $counter->getCommandKey()); + $this->assertEquals(10000, $counter->getRollingStatisticalWindowInMilliseconds()); + $this->assertEquals(10, $counter->getRollingStatisticalWindowBuckets()); + $this->assertEquals(1000, $counter->getBucketInMilliseconds()); // 10000 / 10 = 1000 } } diff --git a/tests/Tests/Odesk/Phystrix/CommandMetricsTest.php b/tests/Tests/Odesk/Phystrix/CommandMetricsTest.php index 2e978af..74f3350 100644 --- a/tests/Tests/Odesk/Phystrix/CommandMetricsTest.php +++ b/tests/Tests/Odesk/Phystrix/CommandMetricsTest.php @@ -24,104 +24,99 @@ use Odesk\Phystrix\HealthCountsSnapshot; use Odesk\Phystrix\MetricsCounter; use ReflectionClass; +use Tests\Odesk\TestCase; -class CommandMetricsTest extends \PHPUnit_Framework_TestCase +class CommandMetricsTest extends TestCase { - /** - * @var CommandMetrics - */ - protected $metrics; + protected CommandMetrics $metrics; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $counter; + protected MetricsCounter $counter; - protected function setUp() + protected function setUp(): void { - $this->counter = $this->createMock('Odesk\Phystrix\MetricsCounter', array(), array(), '', false); + $this->counter = $this->createMock(\Odesk\Phystrix\MetricsCounter::class); $this->metrics = new CommandMetrics($this->counter, 1000); // microtime is fixed global $globalUnitTestPhystrixMicroTime; $globalUnitTestPhystrixMicroTime = 1369861562.1266; } - protected function tearDown() + protected function tearDown(): void { // making microtime to fallback to the default behavior global $globalUnitTestPhystrixMicroTime; $globalUnitTestPhystrixMicroTime = null; } - public function testMarkSuccess() + public function testMarkSuccess(): void { $this->counter->expects($this->once())->method('add')->with(MetricsCounter::SUCCESS); $this->metrics->markSuccess(); } - public function testMarkFailure() + public function testMarkFailure(): void { $this->counter->expects($this->once())->method('add')->with(MetricsCounter::FAILURE); $this->metrics->markFailure(); } - public function testMarkShortCircuited() + public function testMarkShortCircuited(): void { $this->counter->expects($this->once())->method('add')->with(MetricsCounter::SHORT_CIRCUITED); $this->metrics->markShortCircuited(); } - public function testMarkExceptionThrown() + public function testMarkExceptionThrown(): void { $this->counter->expects($this->once())->method('add')->with(MetricsCounter::EXCEPTION_THROWN); $this->metrics->markExceptionThrown(); } - public function testMarkFallbackSuccess() + public function testMarkFallbackSuccess(): void { $this->counter->expects($this->once())->method('add')->with(MetricsCounter::FALLBACK_SUCCESS); $this->metrics->markFallbackSuccess(); } - public function testMarkFallbackFailure() + public function testMarkFallbackFailure(): void { $this->counter->expects($this->once())->method('add')->with(MetricsCounter::FALLBACK_FAILURE); $this->metrics->markFallbackFailure(); } - public function testMarkResponseFromCache() + public function testMarkResponseFromCache(): void { $this->counter->expects($this->once())->method('add')->with(MetricsCounter::RESPONSE_FROM_CACHE); $this->metrics->markResponseFromCache(); } - public function testResetCounter() + public function testResetCounter(): void { $this->counter->expects($this->once())->method('reset'); $this->metrics->resetCounter(); } - public function testGetRollingCount() + public function testGetRollingCount(): void { $this->counter->expects($this->once())->method('get')->with(1); $this->metrics->getRollingCount(1); } - public function testGetHealthCountsInitialSnapshot() + public function testGetHealthCountsInitialSnapshot(): void { $this->counter->expects($this->exactly(2)) ->method('get') - ->will($this->returnValueMap(array( - array(MetricsCounter::FAILURE, 22), - array(MetricsCounter::SUCCESS, 33), - ))); + ->will($this->returnValueMap([ + [MetricsCounter::FAILURE, 22], + [MetricsCounter::SUCCESS, 33], + ])); $snapshot = $this->metrics->getHealthCounts(); $this->assertEquals(22, $snapshot->getFailure()); $this->assertEquals(33, $snapshot->getSuccessful()); } - public function testGetHealthCountsReusingSnapshot() + public function testGetHealthCountsReusingSnapshot(): void { $now = \Odesk\Phystrix\microtime() * 1000; // current time in milliseconds @@ -129,7 +124,7 @@ public function testGetHealthCountsReusingSnapshot() $snapshot = new HealthCountsSnapshot($now - 500, 11, 22); // setting it as the last snapshot into metrics - $reflection = new ReflectionClass('Odesk\Phystrix\CommandMetrics'); + $reflection = new ReflectionClass(CommandMetrics::class); $property = $reflection->getProperty('lastSnapshot'); $property->setAccessible(true); $property->setValue($this->metrics, $snapshot); @@ -139,7 +134,7 @@ public function testGetHealthCountsReusingSnapshot() $this->assertEquals($snapshot, $this->metrics->getHealthCounts()); } - public function testGetHealthCountsExpiringSnapshot() + public function testGetHealthCountsExpiringSnapshot(): void { $now = \Odesk\Phystrix\microtime() * 1000; // current time in milliseconds @@ -147,17 +142,17 @@ public function testGetHealthCountsExpiringSnapshot() $snapshot = new HealthCountsSnapshot($now - 2000, 11, 22); // setting it as the last snapshot into metrics - $reflection = new ReflectionClass('Odesk\Phystrix\CommandMetrics'); + $reflection = new ReflectionClass(CommandMetrics::class); $property = $reflection->getProperty('lastSnapshot'); $property->setAccessible(true); $property->setValue($this->metrics, $snapshot); $this->counter->expects($this->exactly(2)) ->method('get') - ->will($this->returnValueMap(array( - array(MetricsCounter::FAILURE, 22), - array(MetricsCounter::SUCCESS, 33), - ))); + ->will($this->returnValueMap([ + [MetricsCounter::FAILURE, 22], + [MetricsCounter::SUCCESS, 33], + ])); $newSnapshot = $this->metrics->getHealthCounts(); $this->assertNotEquals($snapshot, $newSnapshot); diff --git a/tests/Tests/Odesk/Phystrix/CommandMock.php b/tests/Tests/Odesk/Phystrix/CommandMock.php index 2401762..e1238a1 100644 --- a/tests/Tests/Odesk/Phystrix/CommandMock.php +++ b/tests/Tests/Odesk/Phystrix/CommandMock.php @@ -26,42 +26,43 @@ class CommandMock extends AbstractCommand { - public $throwBadRequestException = false; + public bool $throwBadRequestException = false; - public $throwException = false; + public bool $throwException = false; - public $throwExceptionInFallback = false; + public bool $throwExceptionInFallback = false; - public $cacheKey = null; + public ?string $cacheKey = null; - public $simulateDelay = false; + public bool $simulateDelay = false; - protected function run() + protected function run(): string { if ($this->simulateDelay) { // simulates that command execution took 555 milliseconds global $globalUnitTestPhystrixMicroTime; $globalUnitTestPhystrixMicroTime += 0.555; } + if ($this->throwBadRequestException) { throw new BadRequestException('special treatment'); } elseif ($this->throwException) { throw new DomainException('could not run'); - } else { - return 'run result'; } + + return 'run result'; } - protected function getFallback(\Exception $e = null) + protected function getFallback(?\Exception $e = null): string { if ($this->throwExceptionInFallback) { throw new DomainException('error falling back'); - } else { - return 'fallback result'; } + + return 'fallback result'; } - protected function getCacheKey() + protected function getCacheKey(): ?string { return $this->cacheKey; } diff --git a/tests/Tests/Odesk/Phystrix/CommandTest.php b/tests/Tests/Odesk/Phystrix/CommandTest.php index 29a4f52..b225dd9 100644 --- a/tests/Tests/Odesk/Phystrix/CommandTest.php +++ b/tests/Tests/Odesk/Phystrix/CommandTest.php @@ -22,54 +22,39 @@ use DomainException; use Exception; +use Laminas\Config\Config; use Odesk\Phystrix\AbstractCommand; +use Odesk\Phystrix\CircuitBreaker; +use Odesk\Phystrix\CircuitBreakerFactory; +use Odesk\Phystrix\CircuitBreakerInterface; +use Odesk\Phystrix\CommandMetrics; +use Odesk\Phystrix\CommandMetricsFactory; use Odesk\Phystrix\Exception\RuntimeException; use Odesk\Phystrix\RequestCache; use Odesk\Phystrix\RequestLog; use ReflectionClass; -use Laminas\Config\Config; +use Tests\Odesk\TestCase; -class CommandTest extends \PHPUnit_Framework_TestCase +class CommandTest extends TestCase { - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $circuitBreakerFactory; + protected CircuitBreakerFactory $circuitBreakerFactory; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $circuitBreaker; + protected CircuitBreakerInterface $circuitBreaker; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $commandMetricsFactory; + protected CommandMetricsFactory $commandMetricsFactory; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $commandMetrics; + protected CommandMetrics $commandMetrics; - /** - * @var CommandMock - */ - protected $command; + protected CommandMock $command; - /** - * @var RequestLog - */ - protected $requestLog; + protected RequestLog $requestLog; - protected function setUp() + protected function setUp(): void { - $this->circuitBreakerFactory - = $this->createMock('Odesk\Phystrix\CircuitBreakerFactory', array(), array(), '', false); - $this->circuitBreaker - = $this->createMock('Odesk\Phystrix\CircuitBreakerInterface', array(), array(), '', false); - $this->commandMetricsFactory - = $this->createMock('Odesk\Phystrix\CommandMetricsFactory', array(), array(), '', false); - $this->commandMetrics = $this->createMock('Odesk\Phystrix\CommandMetrics', array(), array(), '', false); + $this->circuitBreakerFactory = $this->createMock(CircuitBreakerFactory::class); + $this->circuitBreaker = $this->createMock(CircuitBreakerInterface::class); + $this->commandMetricsFactory = $this->createMock(CommandMetricsFactory::class); + $this->commandMetrics = $this->createMock(CommandMetrics::class); $this->command = new CommandMock(); $this->command->setCommandMetricsFactory($this->commandMetricsFactory); @@ -77,17 +62,17 @@ protected function setUp() $this->requestLog = new RequestLog(); $this->command->setRequestLog($this->requestLog); $this->command->setCircuitBreakerFactory($this->circuitBreakerFactory); - $this->command->setConfig(new Config(array( - 'fallback' => array( + $this->command->setConfig(new Config([ + 'fallback' => [ 'enabled' => true, - ), - 'requestCache' => array( + ], + 'requestCache' => [ 'enabled' => true, - ), - 'requestLog' => array( + ], + 'requestLog' => [ 'enabled' => true, - ), - ), true)); + ], + ], true)); } /** @@ -95,7 +80,7 @@ protected function setUp() * * @param bool $allowRequest (Optional) Whether CB should allow the request */ - protected function setUpCommonExpectations($allowRequest = true) + protected function setUpCommonExpectations(bool $allowRequest = true): void { $this->circuitBreakerFactory->expects($this->once()) ->method('get') @@ -113,7 +98,7 @@ protected function setUpCommonExpectations($allowRequest = true) /** * Makes the command run for 555 milliseconds */ - protected function setUpExecutionDelayExpectations() + protected function setUpExecutionDelayExpectations(): void { // testing execution time was recorded correctly global $globalUnitTestPhystrixMicroTime; @@ -121,14 +106,14 @@ protected function setUpExecutionDelayExpectations() $this->command->simulateDelay = true; } - public function testSetTestMergesConfig() + public function testSetTestMergesConfig(): void { $command = new CommandMock(); - $command->setConfig(new Config(array('a' => 1), true)); - $command->setConfig(new Config(array('b' => 2), true)); - $this->assertAttributeEquals(new Config(array('a' => 1, 'b' => 2), true), 'config', $command); - $command->setConfig(new Config(array('c' => 3), true), false); // false to skip merge - $this->assertAttributeEquals(new Config(array('c' => 3), true), 'config', $command); + $command->setConfig(new Config(['a' => 1], true)); + $command->setConfig(new Config(['b' => 2], true)); + $this->assertEquals(new Config(['a' => 1, 'b' => 2], true), $command->getConfig()); + $command->setConfig(new Config(['c' => 3], true), false); // false to skip merge + $this->assertEquals(new Config(['c' => 3], true), $command->getConfig()); } public function testExecuteDefaultCommandKey() diff --git a/tests/Tests/Odesk/Phystrix/Exception/RuntimeExceptionTest.php b/tests/Tests/Odesk/Phystrix/Exception/RuntimeExceptionTest.php index 67dc9a2..b2cf18a 100644 --- a/tests/Tests/Odesk/Phystrix/Exception/RuntimeExceptionTest.php +++ b/tests/Tests/Odesk/Phystrix/Exception/RuntimeExceptionTest.php @@ -21,17 +21,17 @@ namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\Exception\RuntimeException; -use PHPUnit_Framework_TestCase; +use Tests\Odesk\TestCase; -class RuntimeExceptionTest extends PHPUnit_Framework_TestCase +class RuntimeExceptionTest extends TestCase { - public function testGetCommandClass() + public function testGetCommandClass(): void { $exception = new RuntimeException('test', 'MyCommand'); $this->assertEquals('MyCommand', $exception->getCommandClass()); } - public function testGetFallbackException() + public function testGetFallbackException(): void { $fallbackException = new \Exception('fallback exception'); $exception = new RuntimeException('test', 'MyCommand', null, $fallbackException); diff --git a/tests/Tests/Odesk/Phystrix/FactoryCommandMock.php b/tests/Tests/Odesk/Phystrix/FactoryCommandMock.php index bc56c9d..b642f47 100644 --- a/tests/Tests/Odesk/Phystrix/FactoryCommandMock.php +++ b/tests/Tests/Odesk/Phystrix/FactoryCommandMock.php @@ -24,10 +24,10 @@ class FactoryCommandMock extends AbstractCommand { - public $a; - public $b; + public string $a; + public string $b; - public function __construct($a, $b) + public function __construct(string $a, string $b) { $this->a = $a; $this->b = $b; diff --git a/tests/Tests/Odesk/Phystrix/HealthCountsSnapshotTest.php b/tests/Tests/Odesk/Phystrix/HealthCountsSnapshotTest.php index 11edeba..e890f32 100644 --- a/tests/Tests/Odesk/Phystrix/HealthCountsSnapshotTest.php +++ b/tests/Tests/Odesk/Phystrix/HealthCountsSnapshotTest.php @@ -21,25 +21,22 @@ namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\HealthCountsSnapshot; -use PHPUnit_Framework_TestCase; +use Tests\Odesk\TestCase; -class HealthCountsSnapshotTest extends PHPUnit_Framework_TestCase +class HealthCountsSnapshotTest extends TestCase { - /** - * @var HealthCountsSnapshot - */ - protected $snapshot; + protected HealthCountsSnapshot $snapshot; - protected function setUp() + protected function setUp(): void { $this->snapshot = new HealthCountsSnapshot(1369760400, 12, 24); } public function testConstruct() { - $this->assertAttributeEquals(12, 'successful', $this->snapshot); - $this->assertAttributeEquals(24, 'failure', $this->snapshot); - $this->assertAttributeEquals(1369760400, 'time', $this->snapshot); + $this->assertEquals(12, $this->snapshot->getSuccessful()); + $this->assertEquals(24, $this->snapshot->getFailure()); + $this->assertEquals(1369760400, $this->snapshot->getTime()); } public function testGetTime() diff --git a/tests/Tests/Odesk/Phystrix/MetricsCounterTest.php b/tests/Tests/Odesk/Phystrix/MetricsCounterTest.php index 23f31f4..e0e3292 100644 --- a/tests/Tests/Odesk/Phystrix/MetricsCounterTest.php +++ b/tests/Tests/Odesk/Phystrix/MetricsCounterTest.php @@ -21,22 +21,18 @@ namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\MetricsCounter; +use Odesk\Phystrix\StateStorageInterface; +use Tests\Odesk\TestCase; -class MetricsCounterTest extends \PHPUnit_Framework_TestCase +class MetricsCounterTest extends TestCase { - /** - * @var MetricsCounter - */ - protected $counter; + protected MetricsCounter $counter; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $stateStorageMock; + protected StateStorageInterface $stateStorageMock; - protected function setUp() + protected function setUp(): void { - $this->stateStorageMock = $this->createMock('Odesk\Phystrix\StateStorageInterface'); + $this->stateStorageMock = $this->createMock(StateStorageInterface::class); // 10 seconds statistical window, 10 buckets. $this->counter = new MetricsCounter('TestCommand', $this->stateStorageMock, 10000, 10); // microtime is fixed @@ -44,20 +40,20 @@ protected function setUp() $globalUnitTestPhystrixMicroTime = 1369861562.1266; } - protected function tearDown() + protected function tearDown(): void { // making microtime to fallback to the default behavior global $globalUnitTestPhystrixMicroTime; $globalUnitTestPhystrixMicroTime = null; } - protected function getExpectedBucketIndex($bucketNumber) + protected function getExpectedBucketIndex(int $bucketNumber): float { $timeInMilliseconds = \Odesk\Phystrix\microtime() * 1000; return floor(($timeInMilliseconds - $bucketNumber * 1000) / 1000); } - public function testAdd() + public function testAdd(): void { // current bucket (0) index is calculated as follows, using the value from microtime: // floor((1369861562.126 - 0 * 1000) / 10000) = 1369861562 @@ -73,7 +69,7 @@ public function testAdd() $this->counter->add(MetricsCounter::SUCCESS); } - public function testGet() + public function testGet(): void { // going through each bucket, making sure the value for it is requested from the storage for ($bucketNumber = 0; $bucketNumber < 10; $bucketNumber++) { diff --git a/tests/Tests/Odesk/Phystrix/NoOpCircuitBreakerTest.php b/tests/Tests/Odesk/Phystrix/NoOpCircuitBreakerTest.php index dd18d66..0aa41cc 100644 --- a/tests/Tests/Odesk/Phystrix/NoOpCircuitBreakerTest.php +++ b/tests/Tests/Odesk/Phystrix/NoOpCircuitBreakerTest.php @@ -21,31 +21,28 @@ namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\NoOpCircuitBreaker; -use PHPUnit_Framework_TestCase; +use Tests\Odesk\TestCase; -class NoOpCircuitBreakerTest extends PHPUnit_Framework_TestCase +class NoOpCircuitBreakerTest extends TestCase { - /** - * @var NoOpCircuitBreaker - */ - protected $circuitBreaker; + protected NoOpCircuitBreaker $circuitBreaker; - protected function setUp() + protected function setUp(): void { $this->circuitBreaker = new NoOpCircuitBreaker(); } - public function testAllowSingleTest() + public function testAllowSingleTest(): void { $this->assertTrue($this->circuitBreaker->allowSingleTest()); } - public function testAllowRequest() + public function testAllowRequest(): void { $this->assertTrue($this->circuitBreaker->allowRequest()); } - public function testIsOpen() + public function testIsOpen(): void { $this->assertFalse($this->circuitBreaker->isOpen()); } diff --git a/tests/Tests/Odesk/Phystrix/RequestCacheTest.php b/tests/Tests/Odesk/Phystrix/RequestCacheTest.php index 798e8a0..9d188b9 100644 --- a/tests/Tests/Odesk/Phystrix/RequestCacheTest.php +++ b/tests/Tests/Odesk/Phystrix/RequestCacheTest.php @@ -21,49 +21,46 @@ namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\RequestCache; -use PHPUnit_Framework_TestCase; +use Tests\Odesk\TestCase; -class RequestCacheTest extends PHPUnit_Framework_TestCase +class RequestCacheTest extends TestCase { - /** - * @var RequestCache - */ - protected $requestCache; + protected RequestCache $requestCache; - protected function setUp() + protected function setUp(): void { $this->requestCache = new RequestCache(); } public function testGetAndPut() { - $result = (object) array('a' => 123); + $result = (object)['a' => 123]; $this->assertNull($this->requestCache->get('TestCommand' . 'cache-key-123')); $this->requestCache->set('TestCommand' . 'cache-key-123', $result); $this->assertEquals($result, $this->requestCache->get('TestCommand' . 'cache-key-123')); } - public function testClear() + public function testClear(): void { - $result = (object) array('a' => 123); + $result = (object)['a' => 123]; $this->requestCache->set('TestCommand' . 'cache-key-123', $result); $this->assertEquals($result, $this->requestCache->get('TestCommand' . 'cache-key-123')); $this->requestCache->clear(); $this->assertNull($this->requestCache->get('TestCommand' . 'cache-key-123')); } - public function testClearAll() + public function testClearAll(): void { - $result = (object) array('a' => 123); + $result = (object)['a' => 123]; $this->requestCache->set('TestCommand' . 'cache-key-123', $result); $this->assertEquals($result, $this->requestCache->get('TestCommand' . 'cache-key-123')); $this->requestCache->clear(); $this->assertNull($this->requestCache->get('TestCommand' . 'cache-key-123')); } - public function testExists() + public function testExists(): void { - $result = (object) array('a' => 123); + $result = (object)['a' => 123]; $this->assertFalse($this->requestCache->has('TestCommand' . 'cache-key-123')); $this->requestCache->set('TestCommand' . 'cache-key-123', $result); $this->assertTrue($this->requestCache->has('TestCommand' . 'cache-key-123')); diff --git a/tests/Tests/Odesk/Phystrix/RequestLogTest.php b/tests/Tests/Odesk/Phystrix/RequestLogTest.php index da1befe..37221a6 100644 --- a/tests/Tests/Odesk/Phystrix/RequestLogTest.php +++ b/tests/Tests/Odesk/Phystrix/RequestLogTest.php @@ -22,23 +22,21 @@ use Odesk\Phystrix\AbstractCommand; use Odesk\Phystrix\RequestLog; +use Tests\Odesk\TestCase; -class RequestLogTest extends \PHPUnit_Framework_TestCase +class RequestLogTest extends TestCase { - /** - * @var RequestLog - */ - protected $requestLog; + protected RequestLog $requestLog; - protected function setUp() + protected function setUp(): void { $this->requestLog = new RequestLog(); } - public function testAddAndGet() + public function testAddAndGet(): void { - $commandA = $this->createMock('Odesk\Phystrix\AbstractCommand', array('run')); - $commandB = $this->createMock('Odesk\Phystrix\AbstractCommand', array('run')); + $commandA = $this->createMock(AbstractCommand::class); + $commandB = $this->createMock(AbstractCommand::class); $this->assertEmpty($this->requestLog->getExecutedCommands()); $this->requestLog->addExecutedCommand($commandA); $this->requestLog->addExecutedCommand($commandB); @@ -50,24 +48,21 @@ public function testReadableEmptyLog() $this->assertSame('', $this->requestLog->getExecutedCommandsAsString()); } - public function testReadableLogWithExecutedCommands() + public function testReadableLogWithExecutedCommands(): void { - $this->addExecutedCommand('commandA', 100, array(AbstractCommand::EVENT_FAILURE)); - $this->addExecutedCommand('commandA', 50, array(AbstractCommand::EVENT_SUCCESS)); - $this->addExecutedCommand('commandA', 15, array(AbstractCommand::EVENT_SUCCESS)); - $this->addExecutedCommand('commandB', -1, array()); + $this->addExecutedCommand('commandA', 100, [AbstractCommand::EVENT_FAILURE]); + $this->addExecutedCommand('commandA', 50, [AbstractCommand::EVENT_SUCCESS]); + $this->addExecutedCommand('commandA', 15, [AbstractCommand::EVENT_SUCCESS]); + $this->addExecutedCommand('commandB', -1, []); $this->assertSame( 'commandA[FAILURE][100ms], commandA[SUCCESS][65ms]x2, commandB[Executed][0ms]', $this->requestLog->getExecutedCommandsAsString() ); } - protected function addExecutedCommand($commandKey, $executionTime, array $events) + protected function addExecutedCommand($commandKey, $executionTime, array $events): void { - $command = $this->createMock( - 'Odesk\Phystrix\AbstractCommand', - array('run', 'getCommandKey', 'getExecutionEvents', 'getExecutionTimeInMilliseconds') - ); + $command = $this->createMock(AbstractCommand::class); $command->expects($this->once()) ->method('getCommandKey') ->willReturn($commandKey); From 5aa3f37510ebf86937d4e7e06903960e2e882a0c Mon Sep 17 00:00:00 2001 From: Young-jin Yun Date: Fri, 6 Jan 2023 01:46:04 +0900 Subject: [PATCH 02/11] add github action --- .github/workflows/testing.yml | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .github/workflows/testing.yml diff --git a/.github/workflows/testing.yml b/.github/workflows/testing.yml new file mode 100644 index 0000000..4e0898d --- /dev/null +++ b/.github/workflows/testing.yml @@ -0,0 +1,35 @@ +name: Testing + +on: + push: + branches: + - '**' + +jobs: + testing: + runs-on: ubuntu-latest + strategy: + matrix: + php-version: ['7.4', '8.0', '8.1'] + env: + extensions: apcu, bcmath, gd, redis-phpredis/phpredis@5.3.5, sqlite, pdo_sqlite + steps: + - name: Setup PHP with tools + uses: shivammathur/setup-php@v2 + env: + RDKAFKA_LIBS: librdkafka-dev + with: + php-version: ${{ matrix.php-version }} + extensions: ${{ env.extensions }} + - name: Checkout + uses: actions/checkout@v3 + with: + # Disabling shallow clone is recommended for improving relevancy of reporting + fetch-depth: 0 + - name: Install Dependencies + run: composer install --prefer-dist + - name: Check code style + run: ./vendor/bin/phpcs + - name: Testing + run: ./vendor/bin/phpunit + From 7ea7375c425d4e476715017b7afe6b57806bd829 Mon Sep 17 00:00:00 2001 From: Young-jin Yun Date: Fri, 6 Jan 2023 01:47:28 +0900 Subject: [PATCH 03/11] fix error on Uncaught Error: Class 'Tests\Odesk\TestCase' not found in --- tests/Tests/Odesk/TestCase.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 tests/Tests/Odesk/TestCase.php diff --git a/tests/Tests/Odesk/TestCase.php b/tests/Tests/Odesk/TestCase.php new file mode 100644 index 0000000..3940222 --- /dev/null +++ b/tests/Tests/Odesk/TestCase.php @@ -0,0 +1,12 @@ + Date: Fri, 6 Jan 2023 01:55:26 +0900 Subject: [PATCH 04/11] fix error on php8, 8.1 --- .gitignore | 1 + composer.json | 2 +- library/Odesk/Phystrix/RequestCache.php | 5 ++--- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index f4dfe03..da019cb 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ composer.lock nbproject tmp/ vendor/ +.phpunit.result.cache \ No newline at end of file diff --git a/composer.json b/composer.json index 447b2a4..c5395bb 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,7 @@ "php": ">=7.4", "ext-json": "*", "psr/container": "^1.0|^2.0", - "psr/simple-cache": "^1.0|^2.0|^3.0", + "psr/simple-cache": "^1.0", "laminas/laminas-config": "^3.5" }, "require-dev": { diff --git a/library/Odesk/Phystrix/RequestCache.php b/library/Odesk/Phystrix/RequestCache.php index 44d25c9..b251f89 100644 --- a/library/Odesk/Phystrix/RequestCache.php +++ b/library/Odesk/Phystrix/RequestCache.php @@ -28,13 +28,12 @@ */ class RequestCache implements CacheInterface { - /** @var array */ - protected $storage = array(); + protected array $storage = []; public function clear() { unset($this->storage); - $this->storage = array(); + $this->storage = []; } public function delete($key) From 60f33fca2fd76d1ae01a00897b038e8c32e7b8df Mon Sep 17 00:00:00 2001 From: Young-jin Yun Date: Fri, 6 Jan 2023 02:01:28 +0900 Subject: [PATCH 05/11] fix readme --- README.md | 6 +++--- composer.json | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 36e0293..94870b7 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ ## Requirement -* PHP 7.1 above +* PHP 7.4, 8.0, 8.1 * Modern PHP ### About Phystrix @@ -21,7 +21,7 @@ In case of a service failing way too often, to not make the situation worse, Phy ### Differences from [older version(upwork/phystrix)](https://github.com/upwork/phystrix) -* Use PHP 7.1 above +* Use PHP 7.4 above * Change from 'Zend DI' to 'PSR DI', DI is optional. (for using Your framework) * Add [phystrix dashboard](https://github.com/upwork/phystrix-dashboard) library, and fix more. * Add Libraries of APCU @@ -42,7 +42,7 @@ Recommended way to install Phystrix is by using [Composer](https://getcomposer.o ```json "require": { - "yupmin/modern-phystrix": "~4.0" + "yupmin/modern-phystrix": "~5.0" }, ``` diff --git a/composer.json b/composer.json index c5395bb..807a8ea 100644 --- a/composer.json +++ b/composer.json @@ -14,6 +14,7 @@ "require": { "php": ">=7.4", "ext-json": "*", + "ext-apcu": "*", "psr/container": "^1.0|^2.0", "psr/simple-cache": "^1.0", "laminas/laminas-config": "^3.5" From 2ca6ec82398c7dc6489286adf1a7a86955b50740 Mon Sep 17 00:00:00 2001 From: Young-jin Yun Date: Fri, 6 Jan 2023 02:02:36 +0900 Subject: [PATCH 06/11] change testing github action --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 94870b7..2de6ed2 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Modern Phystrix -[![Build Status](https://travis-ci.org/yupmin/phystrix.svg)](https://travis-ci.org/yupmin/phystrix) +[![Testing](https://github.com/yupmin/phystrix/actions/workflows/testing.yml/badge.svg)](https://github.com/yupmin/phystrix/actions/workflows/testing.yml) [![Latest Stable Version](https://poser.pugx.org/yupmin/modern-phystrix/v/stable)](https://packagist.org/packages/yupmin/modern-phystrix) [![Total Downloads](https://poser.pugx.org/yupmin/modern-phystrix/downloads)](https://packagist.org/packages/yupmin/modern-phystrix) [![License](https://poser.pugx.org/yupmin/modern-phystrix/license)](https://packagist.org/packages/yupmin/modern-phystrix) From 90cf44edb2b9fb733356a30f162ae19121356c85 Mon Sep 17 00:00:00 2001 From: Young-jin Yun Date: Fri, 6 Jan 2023 02:32:56 +0900 Subject: [PATCH 07/11] add declare(strict_types=1); --- library/Odesk/Phystrix/AbstractCommand.php | 6 ++- library/Odesk/Phystrix/ApcStateStorage.php | 46 +++++-------------- library/Odesk/Phystrix/ApcuStateStorage.php | 2 + library/Odesk/Phystrix/ArrayStateStorage.php | 2 + library/Odesk/Phystrix/CircuitBreaker.php | 2 + .../Odesk/Phystrix/CircuitBreakerFactory.php | 2 + .../Phystrix/CircuitBreakerInterface.php | 2 + library/Odesk/Phystrix/CommandFactory.php | 2 + library/Odesk/Phystrix/CommandMetrics.php | 4 +- .../Odesk/Phystrix/CommandMetricsFactory.php | 2 + .../Exception/ApcNotLoadedException.php | 2 + .../Exception/BadRequestException.php | 2 + .../FallbackNotAvailableException.php | 2 + .../Phystrix/Exception/RuntimeException.php | 6 ++- .../Odesk/Phystrix/HealthCountsSnapshot.php | 2 + library/Odesk/Phystrix/MetricsCounter.php | 14 +++--- .../MetricsEventStream/ApcMetricsPoller.php | 10 ++-- .../MetricsEventStream/ApcuMetricsPoller.php | 10 ++-- .../MetricsPollerInterface.php | 2 + .../MetricsEventStream/MetricsServer.php | 2 + library/Odesk/Phystrix/NoOpCircuitBreaker.php | 2 + library/Odesk/Phystrix/RequestCache.php | 2 + library/Odesk/Phystrix/RequestLog.php | 31 +++++-------- .../Odesk/Phystrix/StateStorageInterface.php | 2 + .../Odesk/Phystrix/ArrayStateStorageTest.php | 2 + .../Phystrix/CircuitBreakerFactoryTest.php | 2 + .../Odesk/Phystrix/CircuitBreakerTest.php | 2 + .../Odesk/Phystrix/CommandFactoryTest.php | 2 + .../Phystrix/CommandMetricsFactoryTest.php | 2 + .../Odesk/Phystrix/CommandMetricsTest.php | 8 ++-- tests/Tests/Odesk/Phystrix/CommandMock.php | 2 + tests/Tests/Odesk/Phystrix/CommandTest.php | 3 +- .../Exception/RuntimeExceptionTest.php | 4 +- .../Odesk/Phystrix/FactoryCommandMock.php | 2 + .../Phystrix/HealthCountsSnapshotTest.php | 2 + .../Odesk/Phystrix/MetricsCounterTest.php | 2 + .../Odesk/Phystrix/NoOpCircuitBreakerTest.php | 2 + .../Tests/Odesk/Phystrix/RequestCacheTest.php | 2 + tests/Tests/Odesk/Phystrix/RequestLogTest.php | 2 + 39 files changed, 120 insertions(+), 78 deletions(-) diff --git a/library/Odesk/Phystrix/AbstractCommand.php b/library/Odesk/Phystrix/AbstractCommand.php index d803a9f..40dc316 100644 --- a/library/Odesk/Phystrix/AbstractCommand.php +++ b/library/Odesk/Phystrix/AbstractCommand.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; use Odesk\Phystrix\Exception\BadRequestException; @@ -420,9 +422,9 @@ public function getExecutionException(): ?Exception /** * Returns current time on the server in milliseconds */ - private function getTimeInMilliseconds(): float + private function getTimeInMilliseconds(): int { - return floor(microtime(true) * 1000); + return (int)floor(microtime(true) * 1000); } /** diff --git a/library/Odesk/Phystrix/ApcStateStorage.php b/library/Odesk/Phystrix/ApcStateStorage.php index dc51f6a..8e91bac 100644 --- a/library/Odesk/Phystrix/ApcStateStorage.php +++ b/library/Odesk/Phystrix/ApcStateStorage.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; /** @@ -46,37 +48,26 @@ public function __construct() /** * Prepends cache prefix and filters out invalid characters - * - * @param string $name - * @return string */ - protected function prefix($name) + protected function prefix(string $name): string { return self::CACHE_PREFIX . $name; } /** * Returns counter value for the given bucket - * - * @param string $commandKey - * @param string $type - * @param integer $index - * @return integer */ - public function getBucket($commandKey, $type, $index) + public function getBucket(string $commandKey, string $type, int $index): ?int { $bucketName = $this->prefix($commandKey . '_' . $type . '_' . $index); + return apc_fetch($bucketName); } /** * Increments counter value for the given bucket - * - * @param string $commandKey - * @param string $type - * @param integer $index */ - public function incrementBucket($commandKey, $type, $index) + public function incrementBucket(string $commandKey, string $type, int $index): void { $bucketName = $this->prefix($commandKey . '_' . $type . '_' . $index); if (!apc_add($bucketName, 1, self::BUCKET_EXPIRE_SECONDS)) { @@ -86,12 +77,8 @@ public function incrementBucket($commandKey, $type, $index) /** * If the given bucket is found, sets counter value to 0. - * - * @param string $commandKey Circuit breaker key - * @param string $type - * @param integer $index */ - public function resetBucket($commandKey, $type, $index) + public function resetBucket(string $commandKey, string $type, int $index): void { $bucketName = $this->prefix($commandKey . '_' . $type . '_' . $index); if (apc_exists($bucketName)) { @@ -103,9 +90,9 @@ public function resetBucket($commandKey, $type, $index) * Marks the given circuit as open * * @param string $commandKey Circuit key - * @param integer $sleepingWindowInMilliseconds In how much time we should allow a single test + * @param int $sleepingWindowInMilliseconds In how much time we should allow a single test */ - public function openCircuit($commandKey, $sleepingWindowInMilliseconds) + public function openCircuit(string $commandKey, int $sleepingWindowInMilliseconds): void { $openedKey = $this->prefix($commandKey . self::OPENED_NAME); $singleTestFlagKey = $this->prefix($commandKey . self::SINGLE_TEST_BLOCKED); @@ -120,12 +107,8 @@ public function openCircuit($commandKey, $sleepingWindowInMilliseconds) /** * Whether a single test is allowed - * - * @param string $commandKey Circuit breaker key - * @param integer $sleepingWindowInMilliseconds In how much time we should allow the next single test - * @return boolean */ - public function allowSingleTest($commandKey, $sleepingWindowInMilliseconds) + public function allowSingleTest(string $commandKey, int $sleepingWindowInMilliseconds): bool { $singleTestFlagKey = $this->prefix($commandKey . self::SINGLE_TEST_BLOCKED); // using 'add' enforces thread safety. @@ -136,11 +119,8 @@ public function allowSingleTest($commandKey, $sleepingWindowInMilliseconds) /** * Whether a circuit is open - * - * @param string $commandKey Circuit breaker key - * @return boolean */ - public function isCircuitOpen($commandKey) + public function isCircuitOpen(string $commandKey): bool { $openedKey = $this->prefix($commandKey . self::OPENED_NAME); return (bool)apc_fetch($openedKey); @@ -148,10 +128,8 @@ public function isCircuitOpen($commandKey) /** * Marks the given circuit as closed - * - * @param string $commandKey Circuit key */ - public function closeCircuit($commandKey) + public function closeCircuit(string $commandKey): void { $openedKey = $this->prefix($commandKey . self::OPENED_NAME); apc_store($openedKey, false); diff --git a/library/Odesk/Phystrix/ApcuStateStorage.php b/library/Odesk/Phystrix/ApcuStateStorage.php index 2fa390b..fa76b45 100644 --- a/library/Odesk/Phystrix/ApcuStateStorage.php +++ b/library/Odesk/Phystrix/ApcuStateStorage.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; /** diff --git a/library/Odesk/Phystrix/ArrayStateStorage.php b/library/Odesk/Phystrix/ArrayStateStorage.php index 5a667c5..3b0a0eb 100644 --- a/library/Odesk/Phystrix/ArrayStateStorage.php +++ b/library/Odesk/Phystrix/ArrayStateStorage.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; /** diff --git a/library/Odesk/Phystrix/CircuitBreaker.php b/library/Odesk/Phystrix/CircuitBreaker.php index 9522726..684255d 100644 --- a/library/Odesk/Phystrix/CircuitBreaker.php +++ b/library/Odesk/Phystrix/CircuitBreaker.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; use Laminas\Config\Config; diff --git a/library/Odesk/Phystrix/CircuitBreakerFactory.php b/library/Odesk/Phystrix/CircuitBreakerFactory.php index f4a2915..482e13a 100644 --- a/library/Odesk/Phystrix/CircuitBreakerFactory.php +++ b/library/Odesk/Phystrix/CircuitBreakerFactory.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; use Laminas\Config\Config; diff --git a/library/Odesk/Phystrix/CircuitBreakerInterface.php b/library/Odesk/Phystrix/CircuitBreakerInterface.php index cfb2428..6a76d1b 100644 --- a/library/Odesk/Phystrix/CircuitBreakerInterface.php +++ b/library/Odesk/Phystrix/CircuitBreakerInterface.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; use Laminas\Config\Config; diff --git a/library/Odesk/Phystrix/CommandFactory.php b/library/Odesk/Phystrix/CommandFactory.php index 5e22c9e..8a16e63 100644 --- a/library/Odesk/Phystrix/CommandFactory.php +++ b/library/Odesk/Phystrix/CommandFactory.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; use Psr\SimpleCache\CacheInterface; diff --git a/library/Odesk/Phystrix/CommandMetrics.php b/library/Odesk/Phystrix/CommandMetrics.php index dbc956d..f055d2d 100644 --- a/library/Odesk/Phystrix/CommandMetrics.php +++ b/library/Odesk/Phystrix/CommandMetrics.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; /** @@ -138,7 +140,7 @@ public function getHealthCounts(): HealthCountsSnapshot !$this->lastSnapshot || $now - $this->lastSnapshot->getTime() >= $this->healthSnapshotIntervalInMilliseconds ) { $this->lastSnapshot = new HealthCountsSnapshot( - $now, + (int)$now, $this->getRollingCount(MetricsCounter::SUCCESS), $this->getRollingCount(MetricsCounter::FAILURE) ); diff --git a/library/Odesk/Phystrix/CommandMetricsFactory.php b/library/Odesk/Phystrix/CommandMetricsFactory.php index 40d68c2..9cf8f7d 100644 --- a/library/Odesk/Phystrix/CommandMetricsFactory.php +++ b/library/Odesk/Phystrix/CommandMetricsFactory.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; use Laminas\Config\Config; diff --git a/library/Odesk/Phystrix/Exception/ApcNotLoadedException.php b/library/Odesk/Phystrix/Exception/ApcNotLoadedException.php index 02e0493..f64b2c7 100644 --- a/library/Odesk/Phystrix/Exception/ApcNotLoadedException.php +++ b/library/Odesk/Phystrix/Exception/ApcNotLoadedException.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix\Exception; /** diff --git a/library/Odesk/Phystrix/Exception/BadRequestException.php b/library/Odesk/Phystrix/Exception/BadRequestException.php index 82e62e1..122d434 100644 --- a/library/Odesk/Phystrix/Exception/BadRequestException.php +++ b/library/Odesk/Phystrix/Exception/BadRequestException.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix\Exception; /** diff --git a/library/Odesk/Phystrix/Exception/FallbackNotAvailableException.php b/library/Odesk/Phystrix/Exception/FallbackNotAvailableException.php index b5430e2..4998b05 100644 --- a/library/Odesk/Phystrix/Exception/FallbackNotAvailableException.php +++ b/library/Odesk/Phystrix/Exception/FallbackNotAvailableException.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix\Exception; /** diff --git a/library/Odesk/Phystrix/Exception/RuntimeException.php b/library/Odesk/Phystrix/Exception/RuntimeException.php index 06fdf9b..bae09f3 100644 --- a/library/Odesk/Phystrix/Exception/RuntimeException.php +++ b/library/Odesk/Phystrix/Exception/RuntimeException.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix\Exception; use Exception; @@ -40,8 +42,8 @@ class RuntimeException extends \RuntimeException /** * Constructor * - * @param Exception $originalException (Optional) Original exception. May be null if short-circuited - * @param Exception $fallbackException (Optional) Exception thrown while retrieving fallback + * @param Exception|null $originalException (Optional) Original exception. May be null if short-circuited + * @param Exception|null $fallbackException (Optional) Exception thrown while retrieving fallback */ public function __construct( string $message, diff --git a/library/Odesk/Phystrix/HealthCountsSnapshot.php b/library/Odesk/Phystrix/HealthCountsSnapshot.php index f42cf3b..730b717 100644 --- a/library/Odesk/Phystrix/HealthCountsSnapshot.php +++ b/library/Odesk/Phystrix/HealthCountsSnapshot.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; /** diff --git a/library/Odesk/Phystrix/MetricsCounter.php b/library/Odesk/Phystrix/MetricsCounter.php index ca46605..8011f02 100644 --- a/library/Odesk/Phystrix/MetricsCounter.php +++ b/library/Odesk/Phystrix/MetricsCounter.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; /** @@ -104,7 +106,7 @@ public function getBucketInMilliseconds(): float */ public function add(int $type): void { - $this->stateStorage->incrementBucket($this->commandKey, $type, $this->getCurrentBucketIndex()); + $this->stateStorage->incrementBucket($this->commandKey, (string)$type, $this->getCurrentBucketIndex()); } /** @@ -116,8 +118,8 @@ public function get(int $type): int $now = $this->getTimeInMilliseconds(); for ($i = 0; $i < $this->rollingStatisticalWindowBuckets; $i++) { - $bucketIndex = $this->getBucketIndex($i, $now); - $sum += $this->stateStorage->getBucket($this->commandKey, $type, $bucketIndex); + $bucketIndex = (int)$this->getBucketIndex($i, $now); + $sum += $this->stateStorage->getBucket($this->commandKey, (string)$type, $bucketIndex); } return $sum; @@ -136,16 +138,16 @@ private function getTimeInMilliseconds(): float */ private function getCurrentBucketIndex(): int { - return $this->getBucketIndex(0, $this->getTimeInMilliseconds()); + return (int)$this->getBucketIndex(0, $this->getTimeInMilliseconds()); } /** * Gets unique bucket index by current time and bucket sequential number in the statistical window * * @param int $bucketNumber - * @param int $time Current time in milliseconds + * @param float $time Current time in milliseconds */ - private function getBucketIndex(int $bucketNumber, int $time): float + private function getBucketIndex(int $bucketNumber, float $time): float { // Getting unique bucket index return floor(($time - $bucketNumber * $this->bucketInMilliseconds) / $this->bucketInMilliseconds); diff --git a/library/Odesk/Phystrix/MetricsEventStream/ApcMetricsPoller.php b/library/Odesk/Phystrix/MetricsEventStream/ApcMetricsPoller.php index 19e9401..307e6d5 100644 --- a/library/Odesk/Phystrix/MetricsEventStream/ApcMetricsPoller.php +++ b/library/Odesk/Phystrix/MetricsEventStream/ApcMetricsPoller.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix\MetricsEventStream; use APCIterator; @@ -163,11 +165,11 @@ public function getStatsForCommandsRunning(): array // Latency is not tracked in phystrix 'latencyExecute_mean' => 0, - 'latencyExecute' => array('0' => 0, '25' => 0, '50' => 0, '75' => 0, '90' => 0, '95' => 0, '99' => 0, - '99.5' => 0, '100' => 0), + 'latencyExecute' => ['0' => 0, '25' => 0, '50' => 0, '75' => 0, '90' => 0, '95' => 0, '99' => 0, + '99.5' => 0, '100' => 0], 'latencyTotal_mean' => 15, - 'latencyTotal' => array('0' => 0, '25' => 0, '50' => 0, '75' => 0, '90' => 0, '95' => 0, '99' => 0, - '99.5' => 0, '100' => 0), + 'latencyTotal' => ['0' => 0, '25' => 0, '50' => 0, '75' => 0, '90' => 0, '95' => 0, '99' => 0, + '99.5' => 0, '100' => 0], 'propertyValue_circuitBreakerRequestVolumeThreshold' => $commandConfig->get('circuitBreaker')->get('requestVolumeThreshold'), diff --git a/library/Odesk/Phystrix/MetricsEventStream/ApcuMetricsPoller.php b/library/Odesk/Phystrix/MetricsEventStream/ApcuMetricsPoller.php index 7fb2281..c892faf 100644 --- a/library/Odesk/Phystrix/MetricsEventStream/ApcuMetricsPoller.php +++ b/library/Odesk/Phystrix/MetricsEventStream/ApcuMetricsPoller.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix\MetricsEventStream; use APCUIterator; @@ -164,11 +166,11 @@ public function getStatsForCommandsRunning(): array // Latency is not tracked in phystrix 'latencyExecute_mean' => 0, - 'latencyExecute' => array('0' => 0, '25' => 0, '50' => 0, '75' => 0, '90' => 0, '95' => 0, '99' => 0, - '99.5' => 0, '100' => 0), + 'latencyExecute' => ['0' => 0, '25' => 0, '50' => 0, '75' => 0, '90' => 0, '95' => 0, '99' => 0, + '99.5' => 0, '100' => 0], 'latencyTotal_mean' => 15, - 'latencyTotal' => array('0' => 0, '25' => 0, '50' => 0, '75' => 0, '90' => 0, '95' => 0, '99' => 0, - '99.5' => 0, '100' => 0), + 'latencyTotal' => ['0' => 0, '25' => 0, '50' => 0, '75' => 0, '90' => 0, '95' => 0, '99' => 0, + '99.5' => 0, '100' => 0], 'propertyValue_circuitBreakerRequestVolumeThreshold' => $commandConfig->get('circuitBreaker')->get('requestVolumeThreshold'), diff --git a/library/Odesk/Phystrix/MetricsEventStream/MetricsPollerInterface.php b/library/Odesk/Phystrix/MetricsEventStream/MetricsPollerInterface.php index eee1558..095d22f 100644 --- a/library/Odesk/Phystrix/MetricsEventStream/MetricsPollerInterface.php +++ b/library/Odesk/Phystrix/MetricsEventStream/MetricsPollerInterface.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix\MetricsEventStream; /** diff --git a/library/Odesk/Phystrix/MetricsEventStream/MetricsServer.php b/library/Odesk/Phystrix/MetricsEventStream/MetricsServer.php index ed0d955..cc43c09 100644 --- a/library/Odesk/Phystrix/MetricsEventStream/MetricsServer.php +++ b/library/Odesk/Phystrix/MetricsEventStream/MetricsServer.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix\MetricsEventStream; /** diff --git a/library/Odesk/Phystrix/NoOpCircuitBreaker.php b/library/Odesk/Phystrix/NoOpCircuitBreaker.php index 10ba8c4..b521f8d 100644 --- a/library/Odesk/Phystrix/NoOpCircuitBreaker.php +++ b/library/Odesk/Phystrix/NoOpCircuitBreaker.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; use Laminas\Config\Config; diff --git a/library/Odesk/Phystrix/RequestCache.php b/library/Odesk/Phystrix/RequestCache.php index b251f89..ec18232 100644 --- a/library/Odesk/Phystrix/RequestCache.php +++ b/library/Odesk/Phystrix/RequestCache.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; use Exception; diff --git a/library/Odesk/Phystrix/RequestLog.php b/library/Odesk/Phystrix/RequestLog.php index ebfbf82..9c1ff81 100644 --- a/library/Odesk/Phystrix/RequestLog.php +++ b/library/Odesk/Phystrix/RequestLog.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; /** @@ -27,27 +29,21 @@ class RequestLog { /** * Executed commands - * - * @var array */ - protected $executedCommands = array(); + protected array $executedCommands = []; /** * Returns commands executed during the current request - * - * @return array */ - public function getExecutedCommands() + public function getExecutedCommands(): array { return $this->executedCommands; } /** * Adds an executed command - * - * @param AbstractCommand $command */ - public function addExecutedCommand(AbstractCommand $command) + public function addExecutedCommand(AbstractCommand $command): void { $this->executedCommands[] = $command; } @@ -74,15 +70,13 @@ public function addExecutedCommand(AbstractCommand $command) * For example, TestCommand[SUCCESS][15ms]x4 represents TestCommand being executed 4 times and * the sum of those 4 executions was 15ms. These 4 each executed the run() method since * RESPONSE_FROM_CACHE was not present as an event. - * - * @return string request log */ - public function getExecutedCommandsAsString() + public function getExecutedCommandsAsString(): string { - $output = ""; + $output = ''; $executedCommands = $this->getExecutedCommands(); - $aggregatedCommandsExecuted = array(); - $aggregatedCommandExecutionTime = array(); + $aggregatedCommandsExecuted = []; + $aggregatedCommandExecutionTime = []; /** @var AbstractCommand $executedCommand */ foreach ($executedCommands as $executedCommand) { @@ -126,11 +120,7 @@ public function getExecutedCommandsAsString() return $output; } - /** - * @param AbstractCommand $executedCommand - * @return string - */ - protected function getOutputForExecutedCommand(AbstractCommand $executedCommand) + protected function getOutputForExecutedCommand(AbstractCommand $executedCommand): string { $display = $executedCommand->getCommandKey() . "["; $events = $executedCommand->getExecutionEvents(); @@ -145,6 +135,7 @@ protected function getOutputForExecutedCommand(AbstractCommand $executedCommand) } $display .= "]"; + return $display; } } diff --git a/library/Odesk/Phystrix/StateStorageInterface.php b/library/Odesk/Phystrix/StateStorageInterface.php index 93c7af2..ef3a8f2 100644 --- a/library/Odesk/Phystrix/StateStorageInterface.php +++ b/library/Odesk/Phystrix/StateStorageInterface.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Odesk\Phystrix; /** diff --git a/tests/Tests/Odesk/Phystrix/ArrayStateStorageTest.php b/tests/Tests/Odesk/Phystrix/ArrayStateStorageTest.php index 9be5672..ce1c6c6 100644 --- a/tests/Tests/Odesk/Phystrix/ArrayStateStorageTest.php +++ b/tests/Tests/Odesk/Phystrix/ArrayStateStorageTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\ArrayStateStorage; diff --git a/tests/Tests/Odesk/Phystrix/CircuitBreakerFactoryTest.php b/tests/Tests/Odesk/Phystrix/CircuitBreakerFactoryTest.php index ad71657..819827a 100644 --- a/tests/Tests/Odesk/Phystrix/CircuitBreakerFactoryTest.php +++ b/tests/Tests/Odesk/Phystrix/CircuitBreakerFactoryTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Laminas\Config\Config; diff --git a/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php b/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php index 4eec2c5..e447af3 100644 --- a/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php +++ b/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Laminas\Config\Config; diff --git a/tests/Tests/Odesk/Phystrix/CommandFactoryTest.php b/tests/Tests/Odesk/Phystrix/CommandFactoryTest.php index 2cc38c9..f70babe 100644 --- a/tests/Tests/Odesk/Phystrix/CommandFactoryTest.php +++ b/tests/Tests/Odesk/Phystrix/CommandFactoryTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use DI\ContainerBuilder; diff --git a/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php b/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php index cdbcfab..fe6cfbe 100644 --- a/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php +++ b/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Laminas\Config\Config; diff --git a/tests/Tests/Odesk/Phystrix/CommandMetricsTest.php b/tests/Tests/Odesk/Phystrix/CommandMetricsTest.php index 74f3350..467fb1c 100644 --- a/tests/Tests/Odesk/Phystrix/CommandMetricsTest.php +++ b/tests/Tests/Odesk/Phystrix/CommandMetricsTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\CommandMetrics; @@ -34,7 +36,7 @@ class CommandMetricsTest extends TestCase protected function setUp(): void { - $this->counter = $this->createMock(\Odesk\Phystrix\MetricsCounter::class); + $this->counter = $this->createMock(MetricsCounter::class); $this->metrics = new CommandMetrics($this->counter, 1000); // microtime is fixed global $globalUnitTestPhystrixMicroTime; @@ -121,7 +123,7 @@ public function testGetHealthCountsReusingSnapshot(): void $now = \Odesk\Phystrix\microtime() * 1000; // current time in milliseconds // a snapshot created half a second ago, still valid at the moment - $snapshot = new HealthCountsSnapshot($now - 500, 11, 22); + $snapshot = new HealthCountsSnapshot((int)$now - 500, 11, 22); // setting it as the last snapshot into metrics $reflection = new ReflectionClass(CommandMetrics::class); @@ -139,7 +141,7 @@ public function testGetHealthCountsExpiringSnapshot(): void $now = \Odesk\Phystrix\microtime() * 1000; // current time in milliseconds // a snapshot created two seconds ago is no longer valid and we expect a new one - $snapshot = new HealthCountsSnapshot($now - 2000, 11, 22); + $snapshot = new HealthCountsSnapshot((int)$now - 2000, 11, 22); // setting it as the last snapshot into metrics $reflection = new ReflectionClass(CommandMetrics::class); diff --git a/tests/Tests/Odesk/Phystrix/CommandMock.php b/tests/Tests/Odesk/Phystrix/CommandMock.php index e1238a1..1b6d208 100644 --- a/tests/Tests/Odesk/Phystrix/CommandMock.php +++ b/tests/Tests/Odesk/Phystrix/CommandMock.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use DomainException; diff --git a/tests/Tests/Odesk/Phystrix/CommandTest.php b/tests/Tests/Odesk/Phystrix/CommandTest.php index b225dd9..76249a2 100644 --- a/tests/Tests/Odesk/Phystrix/CommandTest.php +++ b/tests/Tests/Odesk/Phystrix/CommandTest.php @@ -18,13 +18,14 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use DomainException; use Exception; use Laminas\Config\Config; use Odesk\Phystrix\AbstractCommand; -use Odesk\Phystrix\CircuitBreaker; use Odesk\Phystrix\CircuitBreakerFactory; use Odesk\Phystrix\CircuitBreakerInterface; use Odesk\Phystrix\CommandMetrics; diff --git a/tests/Tests/Odesk/Phystrix/Exception/RuntimeExceptionTest.php b/tests/Tests/Odesk/Phystrix/Exception/RuntimeExceptionTest.php index b2cf18a..73b2c9d 100644 --- a/tests/Tests/Odesk/Phystrix/Exception/RuntimeExceptionTest.php +++ b/tests/Tests/Odesk/Phystrix/Exception/RuntimeExceptionTest.php @@ -18,7 +18,9 @@ * limitations under the License. */ -namespace Tests\Odesk\Phystrix; +declare(strict_types=1); + +namespace Tests\Odesk\Phystrix\Exception; use Odesk\Phystrix\Exception\RuntimeException; use Tests\Odesk\TestCase; diff --git a/tests/Tests/Odesk/Phystrix/FactoryCommandMock.php b/tests/Tests/Odesk/Phystrix/FactoryCommandMock.php index b642f47..5e1a98d 100644 --- a/tests/Tests/Odesk/Phystrix/FactoryCommandMock.php +++ b/tests/Tests/Odesk/Phystrix/FactoryCommandMock.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\AbstractCommand; diff --git a/tests/Tests/Odesk/Phystrix/HealthCountsSnapshotTest.php b/tests/Tests/Odesk/Phystrix/HealthCountsSnapshotTest.php index e890f32..a29a43e 100644 --- a/tests/Tests/Odesk/Phystrix/HealthCountsSnapshotTest.php +++ b/tests/Tests/Odesk/Phystrix/HealthCountsSnapshotTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\HealthCountsSnapshot; diff --git a/tests/Tests/Odesk/Phystrix/MetricsCounterTest.php b/tests/Tests/Odesk/Phystrix/MetricsCounterTest.php index e0e3292..fabc34b 100644 --- a/tests/Tests/Odesk/Phystrix/MetricsCounterTest.php +++ b/tests/Tests/Odesk/Phystrix/MetricsCounterTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\MetricsCounter; diff --git a/tests/Tests/Odesk/Phystrix/NoOpCircuitBreakerTest.php b/tests/Tests/Odesk/Phystrix/NoOpCircuitBreakerTest.php index 0aa41cc..615213f 100644 --- a/tests/Tests/Odesk/Phystrix/NoOpCircuitBreakerTest.php +++ b/tests/Tests/Odesk/Phystrix/NoOpCircuitBreakerTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\NoOpCircuitBreaker; diff --git a/tests/Tests/Odesk/Phystrix/RequestCacheTest.php b/tests/Tests/Odesk/Phystrix/RequestCacheTest.php index 9d188b9..c0a565d 100644 --- a/tests/Tests/Odesk/Phystrix/RequestCacheTest.php +++ b/tests/Tests/Odesk/Phystrix/RequestCacheTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\RequestCache; diff --git a/tests/Tests/Odesk/Phystrix/RequestLogTest.php b/tests/Tests/Odesk/Phystrix/RequestLogTest.php index 37221a6..f67271f 100644 --- a/tests/Tests/Odesk/Phystrix/RequestLogTest.php +++ b/tests/Tests/Odesk/Phystrix/RequestLogTest.php @@ -18,6 +18,8 @@ * limitations under the License. */ +declare(strict_types=1); + namespace Tests\Odesk\Phystrix; use Odesk\Phystrix\AbstractCommand; From d6f94d9588cb268ed3ace6737e869bb0e5b9557a Mon Sep 17 00:00:00 2001 From: Young-jin Yun Date: Fri, 6 Jan 2023 02:35:52 +0900 Subject: [PATCH 08/11] fix test directory --- phpunit.xml.dist | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index da720e0..1cc42fe 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -17,7 +17,7 @@ > - ./tests/Tests + ./tests/Tests/Odesk/Phystrix From f5117770fdb29f71dc93e1fd4dab67144bed4d35 Mon Sep 17 00:00:00 2001 From: Young-jin Yun Date: Fri, 6 Jan 2023 02:48:57 +0900 Subject: [PATCH 09/11] remove old array style --- .../Odesk/Phystrix/CircuitBreakerTest.php | 18 +-- .../Phystrix/CommandMetricsFactoryTest.php | 8 +- tests/Tests/Odesk/Phystrix/CommandTest.php | 133 +++++++++--------- tests/Tests/Odesk/Phystrix/RequestLogTest.php | 2 +- 4 files changed, 79 insertions(+), 82 deletions(-) diff --git a/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php b/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php index e447af3..e53eae7 100644 --- a/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php +++ b/tests/Tests/Odesk/Phystrix/CircuitBreakerTest.php @@ -41,23 +41,23 @@ protected function setUp(): void $this->stateStorage = $this->createMock(StateStorageInterface::class); } - protected function getCircuitBreaker($config = array()): CircuitBreaker + protected function getCircuitBreaker(array $config = []): CircuitBreaker { - $commandConfig = new Config(array( - 'circuitBreaker' => array( + $commandConfig = new Config([ + 'circuitBreaker' => [ 'enabled' => true, 'errorThresholdPercentage' => 50, 'forceOpen' => false, 'forceClosed' => false, 'requestVolumeThreshold' => 50, 'sleepWindowInMilliseconds' => 5000, - 'metrics' => array( + 'metrics' => [ 'healthSnapshotIntervalInMilliseconds' => 1000, 'rollingStatisticalWindowInMilliseconds' => 10000, 'rollingStatisticalWindowBuckets' => 10, - ) - ), - ), true); + ], + ], + ], true); $commandConfig->merge(new Config($config, true)); return new CircuitBreaker('TestCommand', $this->metrics, $commandConfig, $this->stateStorage); @@ -154,7 +154,7 @@ public function testAllowRequestForceOpen(): void { $this->stateStorage->expects($this->never()) ->method('isCircuitOpen'); // making sure it doesn't get to checking if the circuit is open - $circuitBreaker = $this->getCircuitBreaker(array('circuitBreaker' => array('forceOpen' => true))); + $circuitBreaker = $this->getCircuitBreaker(['circuitBreaker' => ['forceOpen' => true]]); $this->assertFalse($circuitBreaker->allowRequest()); } @@ -162,7 +162,7 @@ public function testAllowRequestForceClose(): void { $this->stateStorage->expects($this->never()) ->method('isCircuitOpen'); // making sure it doesn't get to checking if the circuit is open - $circuitBreaker = $this->getCircuitBreaker(array('circuitBreaker' => array('forceClosed' => true))); + $circuitBreaker = $this->getCircuitBreaker(['circuitBreaker' => ['forceClosed' => true]]); $this->assertTrue($circuitBreaker->allowRequest()); } diff --git a/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php b/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php index fe6cfbe..d68328a 100644 --- a/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php +++ b/tests/Tests/Odesk/Phystrix/CommandMetricsFactoryTest.php @@ -34,13 +34,13 @@ class CommandMetricsFactoryTest extends TestCase { public function testGet(): void { - $config = new Config(array( - 'metrics' => array( + $config = new Config([ + 'metrics' => [ 'rollingStatisticalWindowInMilliseconds' => 10000, 'rollingStatisticalWindowBuckets' => 10, 'healthSnapshotIntervalInMilliseconds' => 2000, - ) - )); + ] + ]); $factory = new CommandMetricsFactory(new ArrayStateStorage()); $metrics = $factory->get('TestCommand', $config); $this->assertEquals(2000, $metrics->getHealthSnapshotIntervalInMilliseconds()); diff --git a/tests/Tests/Odesk/Phystrix/CommandTest.php b/tests/Tests/Odesk/Phystrix/CommandTest.php index 76249a2..f2e09de 100644 --- a/tests/Tests/Odesk/Phystrix/CommandTest.php +++ b/tests/Tests/Odesk/Phystrix/CommandTest.php @@ -30,6 +30,7 @@ use Odesk\Phystrix\CircuitBreakerInterface; use Odesk\Phystrix\CommandMetrics; use Odesk\Phystrix\CommandMetricsFactory; +use Odesk\Phystrix\Exception\BadRequestException; use Odesk\Phystrix\Exception\RuntimeException; use Odesk\Phystrix\RequestCache; use Odesk\Phystrix\RequestLog; @@ -117,20 +118,20 @@ public function testSetTestMergesConfig(): void $this->assertEquals(new Config(['c' => 3], true), $command->getConfig()); } - public function testExecuteDefaultCommandKey() + public function testExecuteDefaultCommandKey(): void { // default command key is the class name $this->setUpCommonExpectations(); $this->command->execute(); } - public function testExecutePresetCommandKey() + public function testExecutePresetCommandKey(): void { $this->commandMetricsFactory->expects($this->atLeastOnce()) ->method('get') ->with('PresetTestCommandKey') ->will($this->returnValue($this->commandMetrics)); - $reflection = new ReflectionClass('Tests\Odesk\Phystrix\CommandMock'); + $reflection = new ReflectionClass(CommandMock::class); $property = $reflection->getProperty('commandKey'); $property->setAccessible(true); $property->setValue($this->command, 'PresetTestCommandKey'); @@ -150,7 +151,7 @@ public function testExecutePresetCommandKey() $this->command->execute(); } - public function testExecute() + public function testExecute(): void { $this->setUpCommonExpectations(); $this->setUpExecutionDelayExpectations(); @@ -161,19 +162,19 @@ public function testExecute() $this->assertEmpty($this->requestLog->getExecutedCommands()); $this->assertEquals(null, $this->command->getExecutionTimeInMilliseconds()); $this->assertEquals('run result', $this->command->execute()); - $this->assertEquals(array(AbstractCommand::EVENT_SUCCESS), $this->command->getExecutionEvents()); - $this->assertEquals(array($this->command), $this->requestLog->getExecutedCommands()); + $this->assertEquals([AbstractCommand::EVENT_SUCCESS], $this->command->getExecutionEvents()); + $this->assertEquals([$this->command], $this->requestLog->getExecutedCommands()); $this->assertEquals(555, $this->command->getExecutionTimeInMilliseconds()); } - public function testRequestLogOff() + public function testRequestLogOff(): void { $this->setUpCommonExpectations(); - $this->command->setConfig(new Config(array( - 'requestLog' => array( + $this->command->setConfig(new Config([ + 'requestLog' => [ 'enabled' => false, - ), - ))); + ], + ])); $this->assertEmpty($this->requestLog->getExecutedCommands()); $this->assertEquals('run result', $this->command->execute()); $this->assertEmpty($this->requestLog->getExecutedCommands()); @@ -188,7 +189,7 @@ public function testRequestLogOff() * @throws Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ - public function testRequestLogNotInjected($logEnabled) + public function testRequestLogNotInjected(bool $logEnabled): void { // Duplicate some of the class setup in order to bypass requestLog generation $command = new CommandMock(); @@ -196,11 +197,11 @@ public function testRequestLogNotInjected($logEnabled) $command->setCircuitBreakerFactory($this->circuitBreakerFactory); $command->setRequestCache(new RequestCache()); - $command->setConfig(new Config(array( - 'requestLog' => array( + $command->setConfig(new Config([ + 'requestLog' => [ 'enabled' => $logEnabled, - ), - ), true)); + ], + ], true)); $this->setUpCommonExpectations(); @@ -216,7 +217,7 @@ public function testRequestLogNotInjected($logEnabled) * @throws Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ - public function testRequestCacheNotInjected($cacheEnabled) + public function testRequestCacheNotInjected(bool $cacheEnabled): void { // Duplicate some of the class setup in order to bypass requestLog generation $command = new CommandMock(); @@ -224,34 +225,30 @@ public function testRequestCacheNotInjected($cacheEnabled) $command->setCircuitBreakerFactory($this->circuitBreakerFactory); $command->setRequestLog($this->requestLog); - $command->setConfig(new Config(array( - 'requestCache' => array( + $command->setConfig(new Config([ + 'requestCache' => [ 'enabled' => $cacheEnabled, - ), - ), true)); + ], + ], true)); $this->setUpCommonExpectations(); $this->assertEquals('run result', $this->command->execute()); } - - /** - * @return array - */ - public function configBoolProvider() + public function configBoolProvider(): array { - return array( - 'config enabled' => array(true), - 'config disabled' => array(false), - ); + return [ + 'config enabled' => [true], + 'config disabled' => [false], + ]; } /** * @throws Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ - public function testExecuteRequestNotAllowed() + public function testExecuteRequestNotAllowed(): void { $this->setUpCommonExpectations(false); @@ -266,7 +263,7 @@ public function testExecuteRequestNotAllowed() $this->assertEquals('fallback result', $this->command->execute()); $this->assertEquals( - array(AbstractCommand::EVENT_SHORT_CIRCUITED, AbstractCommand::EVENT_FALLBACK_SUCCESS), + [AbstractCommand::EVENT_SHORT_CIRCUITED, AbstractCommand::EVENT_FALLBACK_SUCCESS], $this->command->getExecutionEvents() ); // execution time is not recorded @@ -277,7 +274,7 @@ public function testExecuteRequestNotAllowed() * @throws Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ - public function testExecuteRunException() + public function testExecuteRunException(): void { $this->setUpCommonExpectations(); $this->setUpExecutionDelayExpectations(); @@ -290,14 +287,14 @@ public function testExecuteRunException() $this->command->throwException = true; $this->assertEquals('fallback result', $this->command->execute()); $this->assertEquals( - array(AbstractCommand::EVENT_FAILURE, AbstractCommand::EVENT_FALLBACK_SUCCESS), + [AbstractCommand::EVENT_FAILURE, AbstractCommand::EVENT_FALLBACK_SUCCESS], $this->command->getExecutionEvents() ); $this->assertEquals(555, $this->command->getExecutionTimeInMilliseconds()); $this->assertEquals(new DomainException('could not run'), $this->command->getExecutionException()); } - public function testExecuteFallbackFailed() + public function testExecuteFallbackFailed(): void { $this->setUpCommonExpectations(); $this->commandMetrics->expects($this->never()) @@ -316,14 +313,14 @@ public function testExecuteFallbackFailed() } catch (Exception $exception) { // } - $this->assertInstanceOf('Odesk\Phystrix\Exception\RuntimeException', $exception); + $this->assertInstanceOf(RuntimeException::class, $exception); $this->assertEquals('could not run and failed retrieving fallback', $exception->getMessage()); $this->assertEquals( - array( + [ AbstractCommand::EVENT_FAILURE, AbstractCommand::EVENT_FALLBACK_FAILURE, AbstractCommand::EVENT_EXCEPTION_THROWN - ), + ], $this->command->getExecutionEvents() ); $this->assertEquals($exception->getPrevious(), $this->command->getExecutionException()); @@ -333,7 +330,7 @@ public function testExecuteFallbackFailed() * @throws Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ - public function testRuntimeExceptionPopulated() + public function testRuntimeExceptionPopulated(): void { $this->setUpCommonExpectations(); $this->command->throwException = true; @@ -342,10 +339,10 @@ public function testRuntimeExceptionPopulated() $this->command->execute(); $this->fail('Odesk\Phystrix\Exception\RuntimeException was expected'); } catch (RuntimeException $exception) { - $this->assertInstanceOf('Odesk\Phystrix\Exception\RuntimeException', $exception); - $this->assertInstanceOf('DomainException', $exception->getPrevious()); - $this->assertInstanceOf('DomainException', $exception->getFallbackException()); - $this->assertEquals('Tests\Odesk\Phystrix\CommandMock', $exception->getCommandClass()); + $this->assertInstanceOf(RuntimeException::class, $exception); + $this->assertInstanceOf(DomainException::class, $exception->getPrevious()); + $this->assertInstanceOf(DomainException::class, $exception->getFallbackException()); + $this->assertEquals(CommandMock::class, $exception->getCommandClass()); $this->assertEquals('could not run and failed retrieving fallback', $exception->getMessage()); $this->assertEquals('error falling back', $exception->getFallbackException()->getMessage()); } @@ -355,7 +352,7 @@ public function testRuntimeExceptionPopulated() * @throws Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ - public function testBadRequestExceptionTracksNoMetrics() + public function testBadRequestExceptionTracksNoMetrics(): void { $this->setUpCommonExpectations(); $this->commandMetrics->expects($this->never()) @@ -367,11 +364,11 @@ public function testBadRequestExceptionTracksNoMetrics() $this->commandMetrics->expects($this->never()) ->method('markFailure'); $this->command->throwBadRequestException = true; - $this->expectException('Odesk\Phystrix\Exception\BadRequestException'); + $this->expectException(BadRequestException::class); $this->expectExceptionMessage('special treatment'); $this->command->execute(); // no events logged in this case - $this->assertEquals(array(), $this->command->getExecutionEvents()); + $this->assertEquals([], $this->command->getExecutionEvents()); // execution time is not recorded $this->assertEquals(null, $this->command->getExecutionTimeInMilliseconds()); } @@ -380,7 +377,7 @@ public function testBadRequestExceptionTracksNoMetrics() * @throws Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ - public function testShortCircuitedExceptionMessage() + public function testShortCircuitedExceptionMessage(): void { $this->setUpCommonExpectations(false); $this->command->throwException = true; @@ -389,15 +386,15 @@ public function testShortCircuitedExceptionMessage() $this->command->execute(); $this->fail('Odesk\Phystrix\Exception\RuntimeException was expected'); } catch (RuntimeException $exception) { - $this->assertInstanceOf('Odesk\Phystrix\Exception\RuntimeException', $exception); + $this->assertInstanceOf(RuntimeException::class, $exception); $this->assertEquals('Short-circuited and failed retrieving fallback', $exception->getMessage()); } } - public function testExecuteFallbackDisabled() + public function testExecuteFallbackDisabled(): void { $this->setUpCommonExpectations(); - $this->command->setConfig(new Config(array('fallback' => array('enabled' => false)))); + $this->command->setConfig(new Config(['fallback' => ['enabled' => false]])); $this->commandMetrics->expects($this->never()) // because fallback is disabled ->method('markFallbackSuccess'); $this->commandMetrics->expects($this->never()) // because fallback is disabled @@ -413,13 +410,13 @@ public function testExecuteFallbackDisabled() } catch (Exception $exception) { // } - $this->assertInstanceOf('Odesk\Phystrix\Exception\RuntimeException', $exception); + $this->assertInstanceOf(RuntimeException::class, $exception); $this->assertEquals('could not run and fallback disabled', $exception->getMessage()); $this->assertEquals( - array( + [ AbstractCommand::EVENT_FAILURE, AbstractCommand::EVENT_EXCEPTION_THROWN - ), + ], $this->command->getExecutionEvents() ); } @@ -434,8 +431,8 @@ public function testRequestCacheHit() ->method('get') ->with('Tests.Odesk.Phystrix.CommandMock') ->will($this->returnValue($this->commandMetrics)); - /** @var RequestCache|\PHPUnit_Framework_MockObject_MockObject $requestCache */ - $requestCache = $this->createMock('Odesk\Phystrix\RequestCache'); + /** @var RequestCache $requestCache */ + $requestCache = $this->createMock(RequestCache::class); $requestCache->expects($this->once()) ->method('has') ->with('Tests.Odesk.Phystrix.CommandMock' . '.' . 'test-cache-key') @@ -449,7 +446,7 @@ public function testRequestCacheHit() $this->circuitBreakerFactory->expects($this->never())->method('get'); $this->commandMetrics->expects($this->once())->method('markResponseFromCache'); $this->assertEquals('result from cache', $this->command->execute()); - $this->assertEquals(array(AbstractCommand::EVENT_RESPONSE_FROM_CACHE), $this->command->getExecutionEvents()); + $this->assertEquals([AbstractCommand::EVENT_RESPONSE_FROM_CACHE], $this->command->getExecutionEvents()); } /** @@ -460,8 +457,8 @@ public function testRequestCacheHit() public function testRequestCacheMiss() { $this->setUpCommonExpectations(); - /** @var RequestCache|\PHPUnit_Framework_MockObject_MockObject $requestCache */ - $requestCache = $this->createMock('Odesk\Phystrix\RequestCache'); + /** @var RequestCache $requestCache */ + $requestCache = $this->createMock(RequestCache::class); $requestCache->expects($this->once()) ->method('has') ->with('Tests.Odesk.Phystrix.CommandMock' . '.' . 'test-cache-key') @@ -475,7 +472,7 @@ public function testRequestCacheMiss() $this->command->setRequestCache($requestCache); $this->commandMetrics->expects($this->never())->method('markResponseFromCache'); $this->assertEquals('run result', $this->command->execute()); - $this->assertEquals(array('SUCCESS'), $this->command->getExecutionEvents()); + $this->assertEquals(['SUCCESS'], $this->command->getExecutionEvents()); } /** @@ -485,8 +482,8 @@ public function testRequestCacheMiss() public function testSavesResultToCache() { $this->setUpCommonExpectations(); - /** @var RequestCache|\PHPUnit_Framework_MockObject_MockObject $requestCache */ - $requestCache = $this->createMock('Odesk\Phystrix\RequestCache'); + /** @var RequestCache $requestCache */ + $requestCache = $this->createMock(RequestCache::class); $requestCache->expects($this->once()) ->method('set') ->with('Tests.Odesk.Phystrix.CommandMock' . '.' . 'test-cache-key', 'run result'); @@ -499,12 +496,12 @@ public function testSavesResultToCache() * @throws Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ - public function testRequestCacheDisabled() + public function testRequestCacheDisabled(): void { $this->setUpCommonExpectations(); - $this->command->setConfig(new Config(array('requestCache' => array('enabled' => false)))); - /** @var RequestCache|\PHPUnit_Framework_MockObject_MockObject $requestCache */ - $requestCache = $this->createMock('Odesk\Phystrix\RequestCache'); + $this->command->setConfig(new Config(['requestCache' => ['enabled' => false]])); + /** @var RequestCache $requestCache */ + $requestCache = $this->createMock(RequestCache::class); $requestCache->expects($this->never()) ->method('get'); $requestCache->expects($this->never()) @@ -519,11 +516,11 @@ public function testRequestCacheDisabled() * @throws Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ - public function testRequestCacheGetCacheKeyNotImplemented() + public function testRequestCacheGetCacheKeyNotImplemented(): void { $this->setUpCommonExpectations(); - /** @var RequestCache|\PHPUnit_Framework_MockObject_MockObject $requestCache */ - $requestCache = $this->createMock('Odesk\Phystrix\RequestCache'); + /** @var RequestCache $requestCache */ + $requestCache = $this->createMock(RequestCache::class); $requestCache->expects($this->never()) ->method('get'); $requestCache->expects($this->never()) diff --git a/tests/Tests/Odesk/Phystrix/RequestLogTest.php b/tests/Tests/Odesk/Phystrix/RequestLogTest.php index f67271f..f2aff4f 100644 --- a/tests/Tests/Odesk/Phystrix/RequestLogTest.php +++ b/tests/Tests/Odesk/Phystrix/RequestLogTest.php @@ -42,7 +42,7 @@ public function testAddAndGet(): void $this->assertEmpty($this->requestLog->getExecutedCommands()); $this->requestLog->addExecutedCommand($commandA); $this->requestLog->addExecutedCommand($commandB); - $this->assertEquals(array($commandA, $commandB), $this->requestLog->getExecutedCommands()); + $this->assertEquals([$commandA, $commandB], $this->requestLog->getExecutedCommands()); } public function testReadableEmptyLog() From 3776f82c750524e5cf5ce9f3b9ddf5cdf05b1139 Mon Sep 17 00:00:00 2001 From: Young-jin Yun Date: Fri, 6 Jan 2023 02:50:04 +0900 Subject: [PATCH 10/11] for 8.2 --- .github/workflows/testing.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/testing.yml b/.github/workflows/testing.yml index 4e0898d..7b85f51 100644 --- a/.github/workflows/testing.yml +++ b/.github/workflows/testing.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - php-version: ['7.4', '8.0', '8.1'] + php-version: ['7.4', '8.0', '8.1', '8.2'] env: extensions: apcu, bcmath, gd, redis-phpredis/phpredis@5.3.5, sqlite, pdo_sqlite steps: From f0b3d8cec773f6c469a73c31c8bba4e5f96c4dcb Mon Sep 17 00:00:00 2001 From: Young-jin Yun Date: Fri, 6 Jan 2023 02:51:50 +0900 Subject: [PATCH 11/11] for 8.2 --- .github/workflows/testing.yml | 2 -- README.md | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/testing.yml b/.github/workflows/testing.yml index 7b85f51..e561109 100644 --- a/.github/workflows/testing.yml +++ b/.github/workflows/testing.yml @@ -16,8 +16,6 @@ jobs: steps: - name: Setup PHP with tools uses: shivammathur/setup-php@v2 - env: - RDKAFKA_LIBS: librdkafka-dev with: php-version: ${{ matrix.php-version }} extensions: ${{ env.extensions }} diff --git a/README.md b/README.md index 2de6ed2..3678fff 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ ## Requirement -* PHP 7.4, 8.0, 8.1 +* PHP 7.4, 8.0, 8.1, 8.2 * Modern PHP ### About Phystrix