SingleServerHandler::createMutex()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Zenstruck\ScheduleBundle\Schedule\Extension\Handler;
4
5
use Symfony\Component\Lock\LockFactory;
6
use Zenstruck\ScheduleBundle\Schedule\Exception\SkipSchedule;
7
use Zenstruck\ScheduleBundle\Schedule\Exception\SkipTask;
8
use Zenstruck\ScheduleBundle\Schedule\Extension\ExtensionHandler;
9
use Zenstruck\ScheduleBundle\Schedule\Extension\SingleServerExtension;
10
use Zenstruck\ScheduleBundle\Schedule\ScheduleRunContext;
11
use Zenstruck\ScheduleBundle\Schedule\Task\TaskRunContext;
12
13
/**
14
 * @author Kevin Bond <[email protected]>
15
 */
16
final class SingleServerHandler extends ExtensionHandler
17
{
18
    /** @var LockFactory */
19
    private $lockFactory;
20 4
21
    public function __construct(LockFactory $lockFactory)
22 4
    {
23 4
        $this->lockFactory = $lockFactory;
24
    }
25
26
    /**
27
     * @param SingleServerExtension $extension
28 2
     */
29
    public function filterSchedule(ScheduleRunContext $context, object $extension): void
30 2
    {
31 1
        if (!$extension->acquireLock($this->lockFactory, self::createMutex($context->getSchedule()->getId(), $context->getStartTime()))) {
32
            throw new SkipSchedule('Schedule running on another server.');
33 2
        }
34
    }
35
36
    /**
37
     * @param SingleServerExtension $extension
38 2
     */
39
    public function filterTask(TaskRunContext $context, object $extension): void
40 2
    {
41 1
        if (!$extension->acquireLock($this->lockFactory, self::createMutex($context->getTask()->getId(), $context->getScheduleRunContext()->getStartTime()))) {
42
            throw new SkipTask('Task running on another server.');
43 2
        }
44
    }
45 2
46
    public function supports(object $extension): bool
47 2
    {
48
        return $extension instanceof SingleServerExtension;
49
    }
50 4
51
    private static function createMutex(string $id, \DateTimeInterface $timestamp): string
52 4
    {
53
        return $id.$timestamp->format('Hi');
54
    }
55
}
56