Completed
Push — master ( 2d5a04...ae10c9 )
by Gaetano
06:49
created

TrashManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use Kaliop\eZMigrationBundle\API\Collection\TrashedItemCollection;
6
use Kaliop\eZMigrationBundle\Core\Matcher\TrashMatcher;
7
8
/**
9
 * Handles trash migrations.
10
 */
11
class TrashManager extends RepositoryExecutor
12
{
13
    protected $supportedActions = array('purge', 'recover', 'delete');
14
    protected $supportedStepTypes = array('trash');
15
16
    /** @var TrashMatcher $trashMatcher */
17
    protected $trashMatcher;
18
19
    /**
20
     * @param TrashMatcher $trashMatcher
21
     */
22
    public function __construct(TrashMatcher $trashMatcher)
23
    {
24
        $this->trashMatcher = $trashMatcher;
25
    }
26
27
    /**
28
     * Handles emptying the trash
29
     */
30
    protected function purge($step)
0 ignored issues
show
Unused Code introduced by
The parameter $step is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
31
    {
32
        $trashService = $this->repository->getTrashService();
33
34
        $trashService->emptyTrash();
35
36
        return true;
37
    }
38
39
    /**
40
     * Handles the trash-restore migration action
41
     */
42 View Code Duplication
    protected function restore($step)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
43
    {
44
        $itemsCollection = $this->matchItems('restore', $step);
45
46
        if (count($itemsCollection) > 1 && array_key_exists('references', $step->dsl)) {
47
            throw new \Exception("Can not execute Trash restore because multiple types match, and a references section is specified in the dsl. References can be set when only 1 section matches");
48
        }
49
50
        $trashService = $this->repository->getTrashService();
51
        foreach ($itemsCollection as $key => $item) {
0 ignored issues
show
Bug introduced by
The expression $itemsCollection of type object<Kaliop\eZMigratio...hedItemCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
52
            /// @todo support handling of custom restoration locations
53
            $trashService->recover($item);
54
        }
55
56
        $this->setReferences($itemsCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $itemsCollection defined by $this->matchItems('restore', $step) on line 44 can be null; however, Kaliop\eZMigrationBundle...anager::setReferences() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
57
58
        return $itemsCollection;
59
    }
60
61
    /**
62
     * Handles the trash-restore migration action
63
     */
64 View Code Duplication
    protected function delete($step)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
65
    {
66
        $itemsCollection = $this->matchItems('delete', $step);
67
68
        if (count($itemsCollection) > 1 && array_key_exists('references', $step->dsl)) {
69
            throw new \Exception("Can not execute Trash restore because multiple types match, and a references section is specified in the dsl. References can be set when only 1 section matches");
70
        }
71
72
        $this->setReferences($itemsCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $itemsCollection defined by $this->matchItems('delete', $step) on line 66 can be null; however, Kaliop\eZMigrationBundle...anager::setReferences() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
73
74
        $trashService = $this->repository->getTrashService();
75
        foreach ($itemsCollection as $key => $item) {
0 ignored issues
show
Bug introduced by
The expression $itemsCollection of type object<Kaliop\eZMigratio...hedItemCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
76
            $trashService->deleteTrashItem($item);
77
        }
78
79
        $this->setReferences($itemsCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $itemsCollection defined by $this->matchItems('delete', $step) on line 66 can be null; however, Kaliop\eZMigrationBundle...anager::setReferences() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
80
81
        return $itemsCollection;
82
    }
83
84
    /**
85
     * @param string $action
86
     * @return TrashedItemCollection
87
     * @throws \Exception
88
     */
89 View Code Duplication
    protected function matchItems($action, $step)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
90
    {
91
        if (!isset($step->dsl['match'])) {
92
            throw new \Exception("A match condition is required to $action trash items");
93
        }
94
95
        // convert the references passed in the match
96
        $match = $this->resolveReferencesRecursively($step->dsl['match']);
0 ignored issues
show
Deprecated Code introduced by
The method Kaliop\eZMigrationBundle...ReferencesRecursively() has been deprecated with message: will be moved into the reference resolver classes

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
97
98
        return $this->trashMatcher->match($match);
99
    }
100
101
    /**
102
     * Sets references to certain trashed-item attributes.
103
     *
104
     * @param \eZ\Publish\API\Repository\Values\Content\TrashItem|TrashedItemCollection $item
105
     * @param $step
106
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
107
     * @return boolean
108
     */
109
    protected function setReferences($item, $step)
110
    {
111
        if (!array_key_exists('references', $step->dsl)) {
112
            return false;
113
        }
114
115
        $references = $this->setReferencesCommon($item, $step->dsl['references']);
116
        $item = $this->insureSingleEntity($item, $references);
0 ignored issues
show
Unused Code introduced by
$item is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
117
118
        foreach ($references as $reference) {
119
            switch ($reference['attribute']) {
120
                /// @todo a trashed item extends a location, so in theory everything 'location' here should work
121
                /*case 'section_id':
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
122
                case 'id':
123
                    $value = $section->id;
124
                    break;
125
                case 'section_identifier':
126
                case 'identifier':
127
                    $value = $section->identifier;
128
                    break;
129
                case 'section_name':
130
                case 'name':
131
                    $value = $section->name;
132
                    break;*/
133
                default:
0 ignored issues
show
Unused Code introduced by
/// @todo a trashed item...eference['attribute']); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
134
                    throw new \InvalidArgumentException('Trash Manager does not support setting references for attribute ' . $reference['attribute']);
135
            }
136
137
            $overwrite = false;
138
            if (isset($reference['overwrite'])) {
139
                $overwrite = $reference['overwrite'];
140
            }
141
            $this->referenceResolver->addReference($reference['identifier'], $value, $overwrite);
0 ignored issues
show
Bug introduced by
The variable $value does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
142
        }
143
144
        return true;
145
    }
146
}
147