Completed
Push — master ( 085b0c...5fa401 )
by
unknown
02:48
created

RemoveJoinAction::run()   C

Complexity

Conditions 10
Paths 22

Size

Total Lines 67

Duplication

Lines 10
Ratio 14.93 %

Importance

Changes 0
Metric Value
dl 10
loc 67
rs 6.8533
c 0
b 0
f 0
cc 10
nc 22
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Charcoal\Admin\Action;
4
5
use Exception;
6
7
// From PSR-7
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
11
// From 'charcoal-admin'
12
use Charcoal\Admin\AdminAction;
13
14
// From 'charcoal-core'
15
use Charcoal\Loader\CollectionLoader;
16
17
// From 'charcoal-attachment'
18
use Charcoal\Attachment\Object\Attachment;
19
use Charcoal\Attachment\Object\Join;
20
21
/**
22
 * Disconnect two objects
23
 */
24
class RemoveJoinAction extends AdminAction
25
{
26
    /**
27
     * @param RequestInterface  $request  A PSR-7 compatible Request instance.
28
     * @param ResponseInterface $response A PSR-7 compatible Response instance.
29
     * @return ResponseInterface
30
     */
31
    public function run(RequestInterface $request, ResponseInterface $response)
32
    {
33
        $params = $request->getParams();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Http\Message\RequestInterface as the method getParams() does only exist in the following implementations of said interface: Slim\Http\Request.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
34
35 View Code Duplication
        if (
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...
36
            !isset($params['attachment_id']) ||
37
            !isset($params['obj_id']) ||
38
            !isset($params['obj_type']) ||
39
            !isset($params['group'])
40
        ) {
41
            $this->setSuccess(false);
42
43
            return $response;
44
        }
45
46
        $attachmentId = $params['attachment_id'];
47
        $objId        = $params['obj_id'];
48
        $objType      = $params['obj_type'];
49
        $group        = $params['group'];
50
51
        // Try loading the object
52
        try {
53
            $obj = $this->modelFactory()->create($objType)->load($objId);
0 ignored issues
show
Unused Code introduced by
$obj 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...
54
        } catch (Exception $e) {
55
            $this->setSuccess(false);
56
57
            return $response;
58
        }
59
60
        $joinProto = $this->modelFactory()->create(Join::class);
61
        if (!$joinProto->source()->tableExists()) {
62
            $joinProto->source()->createTable();
63
        }
64
65
        $loader = new CollectionLoader([
66
            'logger'  => $this->logger,
67
            'factory' => $this->modelFactory()
68
        ]);
69
        $loader
70
            ->setModel($joinProto)
71
            ->addFilter('object_type', $objType)
72
            ->addFilter('object_id', $objId)
73
            ->addFilter('attachment_id', $attachmentId)
74
            ->addFilter('group', $group);
75
76
        $existingJoins = $loader->load();
77
78
        // Should be just one, tho.
79
        foreach ($existingJoins as $joinModel) {
80
            $joinModel->delete();
81
        }
82
83
        // Try loading the attachment
84
        try {
85
            $attachment = $this->modelFactory()->create(Attachment::class)->load($attachmentId);
86
            if ($attachment['id'] !== null) {
87
                $attachment->delete();
88
            }
89
        } catch (Exception $error) {
90
            $this->setSuccess(false);
91
            return $response;
92
        }
93
94
        $this->setSuccess(true);
95
96
        return $response;
97
    }
98
}
99