Skip to content

Commit

Permalink
Job: getName()
Browse files Browse the repository at this point in the history
  • Loading branch information
mabar committed Mar 9, 2023
1 parent 03ddac2 commit 4e9b2a4
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,12 @@ use Orisai\Scheduler\Job\Job;
final class CustomJob implements Job
{

public function getName(): string
{
// Provide (preferably unique) name of the job. It will be used in jobs overview
return static::class;
}

public function run(): void
{
// Do whatever you need to
Expand Down
15 changes: 15 additions & 0 deletions src/Job/CallbackJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Orisai\Scheduler\Job;

use Closure;
use ReflectionFunction;
use function str_ends_with;

final class CallbackJob implements Job
{
Expand All @@ -18,6 +20,19 @@ public function __construct(Closure $callback)
$this->callback = $callback;
}

public function getName(): string
{
$ref = new ReflectionFunction($this->callback);
$refName = $ref->getName();

$class = $ref->getClosureScopeClass();
if ($class !== null && !str_ends_with($refName, '{closure}')) {
return "{$class->getName()}::$refName()";
}

return $refName;
}

public function run(): void
{
($this->callback)();
Expand Down
2 changes: 2 additions & 0 deletions src/Job/Job.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
interface Job
{

public function getName(): string;

public function run(): void;

}
16 changes: 16 additions & 0 deletions tests/Unit/Job/CallbackJobTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Tests\Orisai\Scheduler\Unit\Job;

use Closure;
use Orisai\Scheduler\Job\CallbackJob;
use PHPUnit\Framework\TestCase;

Expand All @@ -18,11 +19,26 @@ static function () use (&$i): void {
},
);

self::assertSame(
'Tests\Orisai\Scheduler\Unit\Job\{closure}',
$job->getName(),
);

$job->run();
self::assertSame(1, $i);

$job->run();
self::assertSame(2, $i);
}

public function testStaticName(): void
{
$job = new CallbackJob(Closure::fromCallable([$this, 'testStaticName']));

self::assertSame(
'Tests\Orisai\Scheduler\Unit\Job\CallbackJobTest::testStaticName()',
$job->getName(),
);
}

}

0 comments on commit 4e9b2a4

Please sign in to comment.