Skip to content

Commit

Permalink
Merge pull request #7 from tomloprod/feat/timewarden-summary
Browse files Browse the repository at this point in the history
Feat: timewarden summary
  • Loading branch information
tomloprod authored Aug 11, 2024
2 parents 6cb6b04 + 76b1452 commit 3aec4d4
Show file tree
Hide file tree
Showing 10 changed files with 255 additions and 10 deletions.
55 changes: 51 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ foreach ($customers as $customer) {
// Perform long process...
}

/**
* You can print the results directly or obtain a
* summary with the `getSummary()` method
*/
echo timeWarden()->output();
```
**Result:**
Expand Down Expand Up @@ -105,6 +109,10 @@ foreach ($customers as $customer) {
timeWarden()->task('Other customer process')->start();
Bar::foo();

/**
* You can print the results directly or obtain a
* summary with the `getSummary()` method
*/
echo timeWarden()->output();
```
**Result:**
Expand Down Expand Up @@ -159,8 +167,10 @@ TimeWarden::reset(): TimeWarden
// Creates a new group.
TimeWarden::group(string $groupName): TimeWarden

// Creates a new task inside the last created group
// or within the TimeWarden instance itself.
/**
* Creates a new task inside the last created group
* or within the TimeWarden instance itself.
*/
TimeWarden::task(string $taskName): TimeWarden

// Starts the last created task
Expand All @@ -172,8 +182,20 @@ TimeWarden::stop(): TimeWarden
// Obtains all the created groups
TimeWarden::getGroups(): array

// Returns a table with execution time debugging info
// (ideal for displaying in the console).
/**
* It allows you to obtain a TimeWardenSummary instance,
* which is useful for getting a summary of all groups
* and tasks generated by TimeWarden.
*
* Through that instance, you can retrieve the summary
* in array or string (JSON) format.
*/
TimeWarden::getSummary(): TimeWardenSummary;

/**
* Returns a table with execution time debugging info
* (ideal for displaying in the console).
*/
TimeWarden::output(): string
```
Additionally, it has all the methods of the [Taskable](#taskable) interface.
Expand Down Expand Up @@ -209,6 +231,9 @@ $task->getEndDateTime(): ?DateTimeImmutable
$task->getStartTimestamp(): float
$task->getEndTimestamp(): float

/** @return array<string, mixed> */
$task->toArray(): array

// Reactive execution time methods
$task->onExceedsMilliseconds(float $milliseconds, callable $fn): ?Task
$task->onExceedsSeconds(float $seconds, callable $fn): ?Task
Expand Down Expand Up @@ -245,6 +270,28 @@ $taskable->getLastTask(): ?Task;

// Return the total time in milliseconds of all tasks within the taskable.
$taskable->getDuration(): float;

$taskable->toArray(): array;

$taskable->toJson(): string;
```

### `TimeWardenSummary`
`Tomloprod\TimeWarden\TimeWardenSummary` is a class that allows obtaining a general summary of groups and their tasks generated with TimeWarden.

It is useful for obtaining a summary in array or string (JSON) format.

You can obtain an instance of `TimeWardenSummary` as follows:
```php
/** @var Tomloprod\TimeWarden\TimeWardenSummary $timeWardenSummary */
$timeWardenSummary = timeWarden()->getSummary();
```

#### Methods
```php

$timeWardenSummary->toArray(): array;
$timeWardenSummary->toJson(): string;
```

## **🚀 Installation & Requirements**
Expand Down
5 changes: 1 addition & 4 deletions rector.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,13 @@
declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php83\Rector\ClassMethod\AddOverrideAttributeToOverriddenMethodsRector;

return RectorConfig::configure()
->withPaths([
__DIR__.'/src',
__DIR__.'/tests',
])
->withSkip([
AddOverrideAttributeToOverriddenMethodsRector::class,
])
->withSkip([])
->withPreparedSets(
deadCode: true,
codeQuality: true,
Expand Down
24 changes: 24 additions & 0 deletions src/Concerns/HasTasks.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,28 @@ public function getLastTask(): ?Task

return ($lastTask instanceof Task) ? $lastTask : null;
}

public function toArray(): array
{
/** @var array<string, mixed> $tasksInfo */
$tasksInfo = [];

/** @var Task $task */
foreach ($this->getTasks() as $task) {
$tasksInfo[] = $task->toArray();
}

return [
'name' => $this->name,
'duration' => $this->getDuration(),
'tasks' => $tasksInfo,
];
}

public function toJson(): string
{
$json = json_encode($this->toArray());

return ($json === false) ? '[]' : $json;
}
}
5 changes: 5 additions & 0 deletions src/Contracts/Taskable.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,9 @@ public function getTasks(): array;
public function getLastTask(): ?Task;

public function getDuration(): float;

/** @return array<string, mixed> */
public function toArray(): array;

public function toJson(): string;
}
12 changes: 10 additions & 2 deletions src/Services/TimeWardenManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@
use Tomloprod\TimeWarden\Contracts\Taskable;
use Tomloprod\TimeWarden\Group;
use Tomloprod\TimeWarden\Task;
use Tomloprod\TimeWarden\TimeWardenSummary;

final class TimeWardenManager implements Taskable
{
use HasTasks;

public string $name = 'default';

private static TimeWardenManager $instance;

/**
Expand Down Expand Up @@ -125,6 +128,13 @@ public function getGroups(): array
return $this->groups;
}

public function getSummary(): TimeWardenSummary
{
$this->stop();

return new TimeWardenSummary();
}

public function output(): string
{
$this->stop();
Expand Down Expand Up @@ -200,9 +210,7 @@ public function output(): string
->setHeaders($columns)
->setRows($rows)
->setStyle('box-double')
// ->setFooterTitle('Thanks for using TimeWarden')
->setFooterTitle('Total: '.round($totalDuration, 2).' ms')

->setHeaderTitle('TIMEWARDEN');

$table->render();
Expand Down
21 changes: 21 additions & 0 deletions src/Task.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Tomloprod\TimeWarden;

use DateTime;
use DateTimeImmutable;
use Tomloprod\TimeWarden\Contracts\Taskable;

Expand Down Expand Up @@ -167,4 +168,24 @@ public function setTestEndTimestamp(float $microtime): void
{
$this->endTimestamp = $microtime;
}

/** @return array<string, mixed> */
public function toArray(): array
{
/** @var ?DateTimeImmutable $startDateTime */
$startDateTime = $this->getStartDateTime();

/** @var ?DateTimeImmutable $endDateTime */
$endDateTime = $this->getEndDateTime();

return [
'name' => $this->name,
'duration' => $this->getDuration(),
'friendly_duration' => $this->getFriendlyDuration(),
'start_timestamp' => $this->startTimestamp,
'end_timestamp' => $this->endTimestamp,
'start_datetime' => ($startDateTime instanceof DateTimeImmutable) ? $startDateTime->format(DateTime::ATOM) : null,
'end_datetime' => ($endDateTime instanceof DateTimeImmutable) ? $endDateTime->format(DateTime::ATOM) : null,
];
}
}
33 changes: 33 additions & 0 deletions src/TimeWardenSummary.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Tomloprod\TimeWarden;

final class TimeWardenSummary
{
/** @return array<string, mixed> */
public function toArray(): array
{
/** @var array<string, mixed> $tasksInfo */
$tasksInfo = [];

if (timeWarden()->getTasks() !== []) {
$tasksInfo[] = timeWarden()->toArray();
}

/** @var Group $group */
foreach (timeWarden()->getGroups() as $group) {
$tasksInfo[] = $group->toArray();
}

return $tasksInfo;
}

public function toJson(): string
{
$json = json_encode($this->toArray());

return ($json === false) ? '[]' : $json;
}
}
40 changes: 40 additions & 0 deletions tests/Contracts/TaskableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
$this->tasksClass = new class implements Taskable
{
use HasTasks;

public string $name = 'default';
};
});

Expand All @@ -31,3 +33,41 @@
expect($this->tasksClass->getLastTask())
->toBeNull();
});

it('can obtain an array/json', function (): void {
$task1 = $this->tasksClass->createTask('TaskName1');
$task1->setTestStartTimestamp(dateTimeToTimestamp(new DateTimeImmutable('2017-06-05 12:00:00.0000000')));
$task1->setTestEndTimestamp(dateTimeToTimestamp(new DateTimeImmutable('2017-06-05 12:00:00.0190000')));

$task2 = $this->tasksClass->createTask('TaskName2');
$task2->setTestStartTimestamp(dateTimeToTimestamp(new DateTimeImmutable('2017-06-05 12:00:00.0000000')));
$task2->setTestEndTimestamp(dateTimeToTimestamp(new DateTimeImmutable('2017-06-05 12:00:00.0230000')));

$summaryArray = [
'name' => 'default',
'duration' => 42.0,
'tasks' => [
[
'name' => 'TaskName1',
'duration' => 19.0,
'friendly_duration' => '19ms',
'start_timestamp' => 1496664000.0,
'end_timestamp' => 1496664000.019,
'start_datetime' => '2017-06-05T12:00:00+00:00',
'end_datetime' => '2017-06-05T12:00:00+00:00',
],
[
'name' => 'TaskName2',
'duration' => 23.0,
'friendly_duration' => '23ms',
'start_timestamp' => 1496664000.0,
'end_timestamp' => 1496664000.023,
'start_datetime' => '2017-06-05T12:00:00+00:00',
'end_datetime' => '2017-06-05T12:00:00+00:00',
],
],
];

expect($this->tasksClass->toArray())->toBe($summaryArray);
expect($this->tasksClass->toJson())->toBe(json_encode($summaryArray));
});
9 changes: 9 additions & 0 deletions tests/Services/TimeWardenManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Tomloprod\TimeWarden\Group;
use Tomloprod\TimeWarden\Services\TimeWardenManager;
use Tomloprod\TimeWarden\Task;
use Tomloprod\TimeWarden\TimeWardenSummary;

beforeEach(function (): void {
TimeWardenManager::instance()->reset();
Expand Down Expand Up @@ -189,3 +190,11 @@
->toContain('Group 2')
->toContain('G2 - Task 1');
});

it('can obtain a TimeWardenSummary', function (): void {
$instance = TimeWardenManager::instance();

$instance->task('Task1')->task('Task2');

expect($instance->getSummary())->toBeInstanceOf(TimeWardenSummary::class);
});
61 changes: 61 additions & 0 deletions tests/TimeWardenSummaryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

declare(strict_types=1);

use Tomloprod\TimeWarden\TimeWardenSummary;

it('can obtain an array/json', function (): void {
timeWarden()->reset();

timeWarden()->task('Generic Task')->start()->stop();

$task = timeWarden()->getTasks()[0];
$task->setTestStartTimestamp(dateTimeToTimestamp(new DateTimeImmutable('2017-06-05 12:00:00.0000000')));
$task->setTestEndTimestamp(dateTimeToTimestamp(new DateTimeImmutable('2017-06-05 12:00:00.0000000')));

timeWarden()->group('Group1')->task('TaskName1')->start()->stop();

$groupTask = timeWarden()->getGroups()[0]->getTasks()[0];
$groupTask->setTestStartTimestamp(dateTimeToTimestamp(new DateTimeImmutable('2017-06-05 12:00:00.0000000')));
$groupTask->setTestEndTimestamp(dateTimeToTimestamp(new DateTimeImmutable('2017-06-05 12:00:00.0320000')));

/** @var TimeWardenSummary $summary */
$summary = timeWarden()->getSummary();

$summaryArray = [
[
'name' => 'default',
'duration' => 0.0,
'tasks' => [
[
'name' => 'Generic Task',
'duration' => 0.0,
'friendly_duration' => '0ms',
'start_timestamp' => 1496664000.0,
'end_timestamp' => 1496664000.0,
'start_datetime' => '2017-06-05T12:00:00+00:00',
'end_datetime' => '2017-06-05T12:00:00+00:00',
],
],
],
[
'name' => 'Group1',
'duration' => 32.0,
'tasks' => [
[
'name' => 'TaskName1',
'duration' => 32.0,
'friendly_duration' => '32ms',
'start_timestamp' => 1496664000.0,
'end_timestamp' => 1496664000.032,
'start_datetime' => '2017-06-05T12:00:00+00:00',
'end_datetime' => '2017-06-05T12:00:00+00:00',
],
],
],
];

expect($summary->toArray())->toBe($summaryArray);

expect($summary->toJson())->toBe(json_encode($summaryArray));
});

0 comments on commit 3aec4d4

Please sign in to comment.