Skip to content

Commit

Permalink
introducing watch
Browse files Browse the repository at this point in the history
  • Loading branch information
henzeb committed Feb 24, 2024
1 parent ca6872a commit fc11720
Show file tree
Hide file tree
Showing 4 changed files with 325 additions and 0 deletions.
29 changes: 29 additions & 0 deletions playground/watch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

use Laravel\Prompts\Prompt;
use function Laravel\Prompts\table;
use function Laravel\Prompts\watch;

require __DIR__ . '/../vendor/autoload.php';

watch(
function () {
static $iteration = 0;
static $items = [];

if (count($items) == 5) {
array_shift($items);
}

$items[] = [$iteration += 1, (new Datetime())->format(DateTime::RFC850)];

table(
[
'Iteration',
'DateTime'
],
$items
);
},
1,
);
142 changes: 142 additions & 0 deletions src/Watch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
<?php

namespace Laravel\Prompts;

use Closure;
use Laravel\Prompts\Output\BufferedConsoleOutput;
use PHPUnit\Framework\Assert;
use RuntimeException;
use ValueError;

class Watch extends Prompt
{
/**
* How many times to fake an iteration
*/
protected static int $fakeTimes = 1;

/**
* count of faked iterations
*/
protected int $fakedTimes = 0;

/**
* Faking sleep or not
*/
protected static bool $fakeSleep = true;

/**
* the amount of seconds slept during intervals in total
*/
protected static int $sleptSeconds = 0;

private Closure $watch;
private int $interval;

/**
* Create a new Watch instance.
*/
public function __construct(callable $watch, ?int $interval = 2)
{
static::$sleptSeconds = 0;
$this->watch = $watch(...);
$this->interval = $interval ?? 2;

if ($this->interval < 0) {
throw new ValueError('watch interval must be greater than or equal to 0');
}
}

/**
* displays the watched output and updates after the specified interval.
*/
public function display(): void
{
$faked = static::output() instanceof BufferedConsoleOutput;

while (!$faked || $this->fakedTimes < static::$fakeTimes) {

$this->render();

if ($faked) {
$this->fakedTimes++;

if ($this->fakedTimes >= static::$fakeTimes) {
static::$fakeSleep = true;
break;
}

if (static::$fakeSleep) {
static::$sleptSeconds += $this->interval;
continue;
}
}

sleep($this->interval);
}
}

/**
* Buffers the output from the callable and flushes the output to Prompts
* in order to utilize Prompts neat way of updating lines
*/
protected function renderTheme(): string
{
$originalOutput = static::output();

$bufferedOutput = new BufferedConsoleOutput();

self::setOutput($bufferedOutput);

($this->watch)();

static::setOutput($originalOutput);

return $bufferedOutput->fetch();
}

/**
* Get the value of the prompt.
*/
public function value(): bool
{
return true;
}

/**
* Tell Prompt how many iterations to fake
*/
public static function fakeTimes(int $times): void
{
if (!static::output() instanceof BufferedConsoleOutput) {
throw new RuntimeException('Prompt must be faked before faking iterations.');
}

static::$fakeTimes = $times;
}

/**
* Asserts the amount of seconds slept during intervals in total.
*/
public static function assertSecondsSleptBetweenIntervals(int $seconds): void
{
if (!static::output() instanceof BufferedConsoleOutput) {
throw new RuntimeException('Prompt must be faked before asserting.');
}

Assert::assertEquals($seconds, static::$sleptSeconds);
}

/**
* By default, when Prompt is faked, the intervals are faked..
* This tells Prompt to actually sleep between updates.
*/
public static function shouldNotFakeIntervalSleep(): void
{
if (!static::output() instanceof BufferedConsoleOutput) {
throw new RuntimeException('Not faking sleep makes no sense when not faking Prompt.');
}

static::$fakeSleep = false;
}
}
10 changes: 10 additions & 0 deletions src/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,13 @@ function progress(string $label, iterable|int $steps, ?Closure $callback = null,

return $progress;
}

/**
* Continuously updates output on each interval.
*
* @param callable(): void $watch
*/
function watch(callable $watch, ?int $interval = 2): void
{
(new Watch($watch, $interval))->display();
}
144 changes: 144 additions & 0 deletions tests/Feature/WatchTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?php

use Laravel\Prompts\Output\ConsoleOutput;
use Laravel\Prompts\Prompt;
use Laravel\Prompts\Watch;
use function Laravel\Prompts\note;
use function Laravel\Prompts\watch;

it('it should render', function () {
Prompt::fake();

watch(function () {
note('This should render');
});

Watch::assertSecondsSleptBetweenIntervals(0);

Prompt::assertOutputContains('This should render');
});

it('it should render callable array', function () {
Prompt::fake();

$watch = new class() {
public function watch(): void
{
note('This should render through array');
}
};

watch([$watch, 'watch']);

Watch::assertSecondsSleptBetweenIntervals(0);

Prompt::assertOutputContains('This should render through array');
});

it('it should render invokable', function () {
Prompt::fake();

$watch = new class() {
public function __invoke(): void
{
note('This should render through invokable');
}
};

watch($watch);

Watch::assertSecondsSleptBetweenIntervals(0);

Prompt::assertOutputContains('This should render through invokable');
});

it('it should render buffered', function () {
Prompt::fake();

watch(function () {

note('This should not render');

(fn() => Watch::output())
->bindTo(null, Watch::class)()->fetch();
});

Prompt::assertOutputDoesntContain('This should not render');
});

it('it should fake sleep when faking', function (
int $expected,
int $iteration,
int $interval = null
) {
Prompt::fake();

Watch::fakeTimes($iteration);

watch(function () {
}, $interval);

Watch::assertSecondsSleptBetweenIntervals($expected);
})->with(
[
['expected' => 2, 'iteration' => 2, 'interval' => 2],
['expected' => 3, 'iteration' => 2, 'interval' => 3],
['expected' => 6, 'iteration' => 3, 'interval' => 3],
['expected' => 4, 'iteration' => 3, 'interval' => null],
]
);

it('should throw exception with a negative interval ', function () {
Prompt::fake();

watch(fn() => null, -1);

})->throws(ValueError::class);

it('should sleep 2 seconds by default', function () {
Prompt::fake();

Watch::fakeTimes(2);

watch(function () {
});

Watch::assertSecondsSleptBetweenIntervals(2);
});

it('should actually sleep at intervals', function () {

Prompt::fake();

Watch::fakeTimes(2);

Watch::shouldNotFakeIntervalSleep();

$start = time();

watch(function () {
note('This should render');
}, 1);

$end = time();

expect($end - $start)->toBe(1);

Prompt::assertOutputContains('This should render');
});

it('should throw exception when invoking fakeTimes when not faked', function () {
(function () {
Prompt::$output = new ConsoleOutput();
})->bindTo(null, Prompt::class)();
Watch::fakeTimes(2);
})->throws(RuntimeException::class);

it('should throw exception when invoking assertSlept when not faked', function () {

(function () {
Prompt::$output = new ConsoleOutput();
})->bindTo(null, Prompt::class)();

Watch::assertSecondsSleptBetweenIntervals(2);
})->throws(RuntimeException::class);

0 comments on commit fc11720

Please sign in to comment.