Skip to content

Commit

Permalink
Refactor (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
samdark committed Apr 29, 2021
1 parent 810fb9a commit d89e1cb
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 104 deletions.
24 changes: 8 additions & 16 deletions config/common.php
Expand Up @@ -24,24 +24,16 @@
},
LogTarget::class => static function (LoggerInterface $logger) use ($params) {
$params = $params['yiisoft/profiler']['targets'][LogTarget::class];
$target = new LogTarget($logger, $params['level']);

if ((bool)$params['enabled']) {
$target = $target->enable();
} else {
$target = $target->disable();
}
return $target->include($params['include'])->exclude($params['exclude']);
return (new LogTarget($logger, $params['level']))
->enable((bool)$params['enabled'])
->include($params['include'])
->exclude($params['exclude']);
},
FileTarget::class => static function (Aliases $aliases) use ($params) {
$params = $params['yiisoft/profiler']['targets'][FileTarget::class];
$target = new FileTarget($aliases->get($params['filename']), $params['requestBeginTime'], $params['directoryMode']);

if ((bool)$params['enabled']) {
$target = $target->enable();
} else {
$target = $target->disable();
}
return $target->include($params['include'])->exclude($params['exclude']);
return (new FileTarget($aliases->get($params['filename']), $params['requestBeginTime'], $params['directoryMode']))
->enable((bool)$params['enabled'])
->include($params['include'])
->exclude($params['exclude']);
},
];
58 changes: 24 additions & 34 deletions src/Profiler.php
Expand Up @@ -8,7 +8,7 @@
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use RuntimeException;
use Yiisoft\Profiler\Target\AbstractTarget;
use Yiisoft\Profiler\Target\TargetInterface;

use function get_class;
use function is_object;
Expand All @@ -20,13 +20,13 @@
final class Profiler implements ProfilerInterface
{
/**
* @var bool whether to profiler is enabled. Defaults to true.
* @var bool Whether to profiler is enabled. Defaults to true.
* You may use this field to disable writing of the profiling messages and thus save the memory usage.
*/
private bool $enabled = true;

/**
* @var Message[] complete profiling messages.
* @var Message[] Complete profiling messages.
* Each message has a following keys:
*
* - message: string, profiling token.
Expand All @@ -42,30 +42,31 @@ final class Profiler implements ProfilerInterface
private array $messages = [];

/**
* @var LoggerInterface logger to be used for message export.
* @var LoggerInterface Logger to be used for message export.
*/
private LoggerInterface $logger;

/**
* @var array pending profiling messages, e.g. the ones which have begun but not ended yet.
* @var array Pending profiling messages, e.g. the ones which have begun but not ended yet.
*/
private array $pendingMessages = [];

/**
* @var int current profiling messages nested level.
* @var int Current profiling messages nested level.
*/
private int $nestedLevel = 0;

/**
* @var AbstractTarget[]|array the profiling targets. Each array element represents a single {@see Target} instance.
* @var array|TargetInterface[] Profiling targets. Each array element represents
* a single {@see TargetInterface} instance.
*/
private array $targets = [];

/**
* Initializes the profiler by registering {@see flush()} as a shutdown function.
*
* @param LoggerInterface $logger
* @param array $targets
* @param LoggerInterface $logger Logger to use.
* @param array $targets Profiling targets to use.
*/
public function __construct(LoggerInterface $logger, array $targets = [])
{
Expand All @@ -75,33 +76,21 @@ public function __construct(LoggerInterface $logger, array $targets = [])
}

/**
* Enable profiler.
* Enable or disable profiler.
*
* @return $this
*/
public function enable(): self
public function enable(bool $value = true): self
{
$new = clone $this;
$new->enabled = true;
$new->enabled = $value;
return $new;
}

/**
* Disable profiler.
* @return bool If profiler is enabled.
*
* @return $this
*/
public function disable(): self
{
$new = clone $this;
$new->enabled = false;
return $new;
}

/**
* @return bool the profiler enabled.
*
* {@see enabled}
* {@see enable}
*/
public function isEnabled(): bool
{
Expand All @@ -111,33 +100,34 @@ public function isEnabled(): bool
/**
* Returns profiler messages.
*
* @return Message[] the messages profiler.
* @return Message[] The profiler messages.
*/
public function getMessages(): array
{
return $this->messages;
}

/**
* @return AbstractTarget[] the profiling targets. Each array element represents a single {@see AbstractTarget|profiling target}
* instance.
* @return TargetInterface[] Profiling targets. Each array element represents
* a single {@see TargetInterface|profiling target} instance.
*/
public function getTargets(): array
{
return $this->targets;
}

/**
* @param AbstractTarget[] $targets the profiling targets. Each array element represents a single {@see AbstractTarget} instance.
* @param TargetInterface[] $targets Profiling targets. Each array element represents
* a single {@see TargetInterface} instance.
*/
private function setTargets(array $targets): void
{
foreach ($targets as $name => $target) {
/** @psalm-suppress DocblockTypeContradiction */
if (!($target instanceof AbstractTarget)) {
if (!($target instanceof TargetInterface)) {
$type = is_object($target) ? get_class($target) : gettype($target);
throw new InvalidArgumentException(
"Target \"$name\" should be an instance of \Yiisoft\Profiler\Target\AbstractTarget, \"$type\" given."
"Target \"$name\" should be an instance of \Yiisoft\Profiler\Target\TargetInterface, \"$type\" given."
);
}
}
Expand Down Expand Up @@ -237,7 +227,7 @@ public function flush(): void

$messages = $this->messages;

// new messages could appear while the existing ones are being handled by targets
// New messages could appear while the existing ones are being handled by targets.
$this->messages = [];

$this->dispatch($messages);
Expand All @@ -246,7 +236,7 @@ public function flush(): void
/**
* Dispatches the profiling messages to {@see targets}.
*
* @param array $messages the profiling messages.
* @param array $messages The profiling messages.
*/
private function dispatch(array $messages): void
{
Expand Down
14 changes: 7 additions & 7 deletions src/ProfilerInterface.php
Expand Up @@ -13,10 +13,10 @@ interface ProfilerInterface
* Marks the beginning of a code block for profiling.
*
* This has to be matched with a call to {@see end()} with the same category name.
* The begin- and end- calls must also be properly nested. For example,
* The begin- and end- calls must also be properly nested.
*
* @param string $token token for the code block
* @param array $context the context data of this profile block
* @param string $token Token for the code block.
* @param array $context The context data of this profile block.
*/
public function begin(string $token, array $context = []): void;

Expand All @@ -25,8 +25,8 @@ public function begin(string $token, array $context = []): void;
*
* This has to be matched with a previous call to {@see begin()} with the same category name.
*
* @param string $token token for the code block
* @param array $context the context data of this profile block
* @param string $token Token for the code block.
* @param array $context The context data of this profile block.
*
* {@see begin()}
*/
Expand All @@ -35,9 +35,9 @@ public function end(string $token, array $context = []): void;
/**
* Find messages with a given token.
*
* @param string $token
* @param string $token Code block token.
*
* @return Message[] the messages profiler.
* @return Message[] The messages profiler.
*/
public function findMessages(string $token): array;

Expand Down
26 changes: 7 additions & 19 deletions src/Target/AbstractTarget.php
Expand Up @@ -16,7 +16,7 @@
* For more details and usage information on Target,
* see the [guide article on profiling & targets](guide:runtime-profiling).
*/
abstract class AbstractTarget
abstract class AbstractTarget implements TargetInterface
{
/**
* @var array List of message categories that this target is interested in. Defaults to empty, meaning all
Expand Down Expand Up @@ -108,26 +108,14 @@ public function exclude(array $exclude): self
}

/**
* Enable target.
* Enable or disable target.
*
* @return $this
*/
public function enable(): self
public function enable(bool $value = true): self
{
$new = clone $this;
$new->enabled = true;
return $new;
}

/**
* Disable target.
*
* @return $this
*/
public function disable(): self
{
$new = clone $this;
$new->enabled = false;
$new->enabled = $value;
return $new;
}

Expand All @@ -144,17 +132,17 @@ public function isEnabled(): bool
*
* Child classes must implement this method.
*
* @param Message[] $messages profiling messages to be exported.
* @param Message[] $messages Profiling messages to be exported.
*/
abstract public function export(array $messages): void;

/**
* Filters the given messages according to their categories.
*
* @param Message[] $messages messages to be filtered.
* @param Message[] $messages Messages to be filtered.
* The message structure follows that in {@see Profiler::$messages}.
*
* @return array the filtered messages.
* @return array The filtered messages.
*/
protected function filterMessages(array $messages): array
{
Expand Down
6 changes: 3 additions & 3 deletions src/Target/FileTarget.php
Expand Up @@ -112,7 +112,7 @@ public function export(array $messages): void
/**
* Resolves value of {@see filename} processing path alias and placeholders.
*
* @return string actual target filename.
* @return string Actual target filename.
*/
private function resolveFilename(): string
{
Expand All @@ -136,10 +136,10 @@ static function (array $matches) {
/**
* Formats a profiling message for display as a string.
*
* @param Message $message the profiling message to be formatted.
* @param Message $message Profiling message to be formatted.
* The message structure follows that in {@see Profiler::$messages}.
*
* @return string the formatted message.
* @return string Formatted message.
*/
private function formatMessage(Message $message): string
{
Expand Down
8 changes: 2 additions & 6 deletions src/Target/LogTarget.php
Expand Up @@ -6,7 +6,6 @@

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Yiisoft\Profiler\Message;

/**
* LogTarget saves profiling messages as a log messages.
Expand All @@ -33,12 +32,12 @@
final class LogTarget extends AbstractTarget
{
/**
* @var LoggerInterface logger to be used for message export.
* @var LoggerInterface Logger to be used for message export.
*/
private LoggerInterface $logger;

/**
* @var string log level to be used for messages export.
* @var string Log level to be used for messages export.
*/
private string $logLevel;

Expand All @@ -48,9 +47,6 @@ public function __construct(LoggerInterface $logger, string $logLevel = LogLevel
$this->logLevel = $logLevel;
}

/**
* @param Message[] $messages
*/
public function export(array $messages): void
{
foreach ($messages as $message) {
Expand Down
23 changes: 23 additions & 0 deletions src/Target/TargetInterface.php
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Profiler\Target;

/**
* Target interface defines a profiling target.
*
* The target receives profiling messages and is sending these
* to a certain medium or system. It may, as well, filter out
* messages it does not need.
*/
interface TargetInterface
{
/**
* Processes the given log messages.
*
* @param array $messages Profiling messages to be processed. See {@see Profiler::$messages} for the structure
* of each message.
*/
public function collect(array $messages): void;
}
12 changes: 1 addition & 11 deletions tests/AbstractTargetTest.php
Expand Up @@ -106,16 +106,6 @@ public function testEnable(): void
$this->assertEquals($target, $target->enable());
}

public function testDisable(): void
{
/* @var $target AbstractTarget|\PHPUnit\Framework\MockObject\MockObject */
$target = $this->getMockBuilder(AbstractTarget::class)->onlyMethods(['disable'])->getMockForAbstractClass();

$target->expects($this->once())->method('disable')->willReturnSelf();

$this->assertEquals($target, $target->disable());
}

public function testEnabled(): void
{
/* @var $target AbstractTarget|\PHPUnit\Framework\MockObject\MockObject */
Expand All @@ -141,7 +131,7 @@ public function testDisabled(): void

$target->expects($this->exactly(0))->method('export');

$target = $target->disable();
$target = $target->enable(false);

$target->collect([new Message('foo', 'test', ['category' => 'foo'])]);

Expand Down

0 comments on commit d89e1cb

Please sign in to comment.