Failed Conditions
Pull Request — master (#13)
by Mathieu
01:39
created

LockSet   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 62
wmc 12
lcom 1
cbo 2
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A acquire() 0 15 4
A release() 0 16 4
A __destruct() 0 4 1
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