Completed
Push — master ( b5e5c9...2e8748 )
by Mathieu
02:26
created

LockSet::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
rs 9.4285
cc 3
eloc 7
nc 3
nop 2
1
<?php
2
3
namespace TH\Lock;
4
5
use Psr\Log\LoggerInterface;
6
use Psr\Log\NullLogger;
7
8
class LockSet implements Lock
9
{
10
    private $locks = [];
11
12
    private $logger;
13
14
    /**
15
     * @param Lock[]               $locks  array of Lock
16
     * @param LoggerInterface|null $logger
17
     */
18
    public function __construct(
19
        array $locks,
20
        LoggerInterface $logger = null
21
    ) {
22
        if (empty($locks)) {
23
            throw new RuntimeException("Lock set cannot be empty");
24
        }
25
        $this->locks = $locks;
26
        $this->logger = $logger ?: new NullLogger;
27
    }
28
29
    /**
30
     * @inherit
31
     */
32
    public function acquire()
33
    {
34
        $acquiredLocks = [];
35
        try {
36
            foreach ($this->locks as $lock) {
37
                $lock->acquire();
38
                $acquiredLocks[] = $lock;
39
            }
40
        } catch (RuntimeException $e) {
41
            foreach ($acquiredLocks as $lock) {
42
                $lock->release();
43
            }
44
            throw $e;
45
        }
46
    }
47
48
    public function release()
49
    {
50
        $exceptions = [];
51
        foreach ($this->locks as $lock) {
52
            try {
53
                $lock->release();
54
            } catch (RuntimeException $e) {
55
                $exceptions[] = $e;
56
            }
57
        }
58
        if (!empty($exceptions)) {
59
            throw new AggregationException($exceptions, "Some locks were not released");
60
        }
61
    }
62
63
    public function __destruct()
64
    {
65
        $this->release();
66
    }
67
}
68