Passed
Push — master ( 76636e...a7cce5 )
by Kevin
03:12
created

WithoutOverlappingHandler::__construct()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 4.25

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 10
cc 4
nc 2
nop 1
crap 4.25
1
<?php
2
3
namespace Zenstruck\ScheduleBundle\Schedule\Extension\Handler;
4
5
use Symfony\Component\Lock\LockFactory;
6
use Symfony\Component\Lock\PersistingStoreInterface;
7
use Symfony\Component\Lock\Store\FlockStore;
8
use Symfony\Component\Lock\Store\SemaphoreStore;
9
use Zenstruck\ScheduleBundle\Schedule\Exception\MissingDependency;
10
use Zenstruck\ScheduleBundle\Schedule\Exception\SkipTask;
11
use Zenstruck\ScheduleBundle\Schedule\Extension\ExtensionHandler;
12
use Zenstruck\ScheduleBundle\Schedule\Extension\WithoutOverlappingExtension;
13
use Zenstruck\ScheduleBundle\Schedule\Task\TaskRunContext;
14
15
/**
16
 * @author Kevin Bond <[email protected]>
17
 */
18
final class WithoutOverlappingHandler extends ExtensionHandler
19
{
20
    private $lockFactory;
21
22 2
    public function __construct(LockFactory $lockFactory = null)
23
    {
24 2
        if (null === $lockFactory && !\class_exists(LockFactory::class)) {
25
            throw new MissingDependency(WithoutOverlappingExtension::getMissingDependencyMessage());
26
        }
27
28 2
        $this->lockFactory = $lockFactory ?: new LockFactory(self::createLocalStore());
29 2
    }
30
31
    /**
32
     * @param WithoutOverlappingExtension $extension
33
     */
34 2
    public function filterTask(TaskRunContext $context, object $extension): void
35
    {
36 2
        if (!$extension->acquireLock($this->lockFactory, $context->getTask()->getId())) {
37 1
            throw new SkipTask('Task running in another process.');
38
        }
39 2
    }
40
41
    /**
42
     * @param WithoutOverlappingExtension $extension
43
     */
44 1
    public function afterTask(TaskRunContext $context, object $extension): void
45
    {
46 1
        $extension->releaseLock();
47 1
    }
48
49 1
    public function supports(object $extension): bool
50
    {
51 1
        return $extension instanceof WithoutOverlappingExtension;
52
    }
53
54 1
    private static function createLocalStore(): PersistingStoreInterface
55
    {
56 1
        if (SemaphoreStore::isSupported()) {
57 1
            return new SemaphoreStore();
58
        }
59
60
        return new FlockStore();
61
    }
62
}
63