Failed Conditions
Pull Request — master (#13)
by Mathieu
01:39
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
use TH\Lock\RuntimeException;
8
9
class LockSet implements Lock
10
{
11
    private $locks = [];
12
13
    private $logger;
14
15
    /**
16
     * @param Lock[]               $locks  array of Lock
17
     * @param LoggerInterface|null $logger
18
     */
19
    public function __construct(
20
        array $locks,
21
        LoggerInterface $logger = null
22
    ) {
23
        if (empty($locks)) {
24
            throw new RuntimeException("Lock set cannot be empty");
25
        }
26
        $this->locks = $locks;
27
        $this->logger = $logger ?: new NullLogger;
28
    }
29
30
    /**
31
     * @inherit
32
     */
33
    public function acquire()
34
    {
35
        $acquiredLocks = [];
36
        try {
37
            foreach ($this->locks as $lock) {
38
                $lock->acquire();
39
                $acquiredLocks[] = $lock;
40
            }
41
        } catch (RuntimeException $e) {
42
            foreach ($acquiredLocks as $lock) {
43
                $lock->release();
44
            }
45
            throw $e;
46
        }
47
    }
48
49
    public function release()
50
    {
51
        $exceptions = [];
52
        foreach ($this->locks as $lock) {
53
            try {
54
                $lock->release();
55
            } catch (RuntimeException $e) {
56
                $exceptions[] = $e;
57
            }
58
        }
59
        if (!empty($exceptions)) {
60
            $e = new RuntimeException("Some locks were not released");
61
            $e->exceptions = $exceptions;
0 ignored issues
show
Bug introduced by
The property exceptions does not seem to exist in TH\Lock\RuntimeException.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
62
            throw $e;
63
        }
64
    }
65
66
    public function __destruct()
67
    {
68
        $this->release();
69
    }
70
}
71