Transactional::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 12
cts 12
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 4
nop 1
crap 3
1
<?php
2
3
/**
4
 * Copyright 2016 Inneair
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 *
18
 * @license http://www.apache.org/licenses/LICENSE-2.0.html Apache-2.0
19
 */
20
21
namespace Inneair\TransactionBundle\Annotation;
22
23
use Doctrine\Common\Annotations\Annotation\Attribute;
24
use Doctrine\Common\Annotations\Annotation\Attributes;
25
use Doctrine\Common\Annotations\AnnotationException;
26
use Exception;
27
use ReflectionClass;
28
use ReflectionException;
29
30
/**
31
 * This class handles properties of the @Transactional annotation.
32
 * This annotation can be applied on classes or public methods. When applied on classes, all public methods inherit this
33
 * setting. By default, if the annotation exists with no explicit policy, the REQUIRED policy is set.
34
 *
35
 * @Annotation
36
 * @Target({"METHOD", "CLASS"})
37
 * @Attributes({
38
 *     @Attribute("policy", type="integer"),
39
 *     @Attribute("noRollbackExceptions", type="string[]")
40
 * })
41
 */
42
class Transactional
43
{
44
    /**
45
     * A transactional context is not required for this method execution.
46
     * No transactional context will be created, and the method will be executed in the outer transactional context, if
47
     * any.
48
     * @var integer
49
     */
50
    const NOT_REQUIRED = 1;
51
    /**
52
     * A transactional context is required for this method execution.
53
     * - If there is no transactional context in the call stack, this will lead to the creation of a new transaction.
54
     * - If there is a transactional context in the call stack, the method will be executed in this outer transactional
55
     * context.
56
     * @var integer
57
     */
58
    const REQUIRED = 2;
59
    /**
60
     * A new transactional context is required for this method execution.
61
     * Note that this behaviour is not strictly supported by default, and requires use of save points is enabled at
62
     * connection-level (see connection options).
63
     * - If there is no transactional context in the call stack, this will lead to the creation of a new transaction.
64
     * - If there is a transactional context in the call stack, this will 'only' lead to the incrementation of the
65
     * nesting level, and optionally to the creation of a nested transaction (with a save point), if enabled in the
66
     * connection configuration.
67
     * @var integer
68
     */
69
    const NESTED = 3;
70
71
    /**
72
     * Transaction policy.
73
     * @var integer
74
     */
75
    private $policy;
76
    /**
77
     * An array of exceptions that will not lead to a transaction rollback, if thrown during the method execution.
78
     * @var string[]
79
     */
80
    private $noRollbackExceptions;
81
82
    /**
83
     * Builds an instance of this annotation.
84
     *
85
     * @param array $options Options (defaults to an empty array).
86
     * @throws AnnotationException If the policy is set and has an invalid value, or if a no rollback exception does not
87
     * exist, or is not a valid exception.
88
     */
89 28
    public function __construct(array $options = [])
90
    {
91 28
        if (isset($options['policy'])) {
92 17
            $policy = $this->validatePolicy($options['policy']);
93 15
        } else {
94 11
            $policy = null;
95
        }
96 26
        $this->policy = $policy;
97
98 26
        if (isset($options['noRollbackExceptions'])) {
99 8
            $noRollbackExceptions = $this->validateNoRollbackExceptions(array_unique($options['noRollbackExceptions']));
100 4
        } else {
101 18
            $noRollbackExceptions = null;
102
        }
103 22
        $this->noRollbackExceptions = $noRollbackExceptions;
0 ignored issues
show
Documentation Bug introduced by
It seems like $noRollbackExceptions can be null. However, the property $noRollbackExceptions is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
104 22
    }
105
106
    /**
107
     * Gets the transaction policy.
108
     *
109
     * @return integer Policy.
110
     */
111 20
    public function getPolicy()
112
    {
113 20
        return $this->policy;
114
    }
115
116
    /**
117
     * Gets the exception class names which does not trigger a rollback.
118
     *
119
     * @return string[] Exception class names. If <code>null</code>, the option was not set in the annotation, otherwise
120
     * the returned value is an array.
121
     */
122 14
    public function getNoRollbackExceptions()
123
    {
124 14
        return $this->noRollbackExceptions;
125
    }
126
127
    /**
128
     * Validates a policy specified in the annotation.
129
     *
130
     * @param integer $annotationPolicy Policy.
131
     * @return int Validated policy ID.
132
     * @throws AnnotationException If the policy is invalid.
133
     */
134 17
    private function validatePolicy($annotationPolicy)
135
    {
136 17
        $policies = [static::NOT_REQUIRED, static::REQUIRED, static::NESTED];
137 17
        if (in_array($annotationPolicy, $policies)) {
138 15
            $policy = $annotationPolicy;
139 15
        } else {
140 2
            throw new AnnotationException(
141 2
                'Invalid policy: "' . $annotationPolicy . '", must be one of the constants [' .
142 2
                implode(', ', $policies) . ']'
143 2
            );
144
        }
145 15
        return $policy;
146
    }
147
148
    /**
149
     * Validates the no rollback exceptions in the annotation.
150
     *
151
     * @param string[] $annotationNoRollbackExceptions Exception class names.
152
     * @return array Rollback exceptions.
153
     * @throws AnnotationException If a class is not found, or is not an exception.
154
     */
155 8
    private function validateNoRollbackExceptions($annotationNoRollbackExceptions)
156
    {
157 8
        $noRollbackExceptions = [];
158 8 View Code Duplication
        foreach ($annotationNoRollbackExceptions as $exceptionClassName) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
159
            try {
160 8
                $exceptionClass = new ReflectionClass($exceptionClassName);
161 8
            } catch (ReflectionException $e) {
162 2
                throw new AnnotationException('Class not found: \'' . $exceptionClassName . '\'', null, $e);
163
            }
164
165 6
            if (($exceptionClassName !== Exception::class) && !$exceptionClass->isSubclassOf(Exception::class)) {
166 2
                throw new AnnotationException('Not an exception: \'' . $exceptionClassName . '\'');
167
            }
168
169 4
            $noRollbackExceptions[] = $exceptionClassName;
170 4
        }
171 4
        return $noRollbackExceptions;
172
    }
173
}
174