Passed
Push — master ( 534b0c...8bd354 )
by Matt
05:44
created

Action   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 64
ccs 0
cts 16
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A setId() 0 4 1
B getRequest() 0 23 6
1
<?php
2
namespace Billow\Actions;
3
use GuzzleHttp\Psr7\Request;
4
use GuzzleHttp\Psr7\Stream;
5
use RuntimeException;
6
7
/**
8
 * @author Matt Frost<[email protected]>
9
 * @package Billow
10
 * @subpackage Actions
11
 * @license http://opensource.org/licenses/MIT MIT
12
 */
13
class Action implements ActionInterface
14
{
15
    /**
16
     * Endpoint for the action
17
     *
18
     * @const ENDPOINT
19
     */
20
    const ENDPOINT = 'https://api.digitalocean.com/v2/droplets/[:id:]/actions';
21
22
    /**
23
     * HTTP Method
24
     *
25
     * @const METHOD
26
     */
27
    const METHOD = 'POST';
28
29
    /**
30
     * ID of the droplet to perform the action on
31
     *
32
     * @var mixed $id
33
     */
34
    protected $id;
35
36
    /**
37
     * Set the droplet id
38
     *
39
     * @param mixed $id
40
     */
41
    public function setId($id)
42
    {
43
       $this->id = $id; 
44
    }
45
46
    /**
47
     * Method to return the action request object
48
     *
49
     * @param Array $headers
50
     * @param string $body
51
     * @return \GuzzleHttp\Message\Request
52
     */
53
    public function getRequest(Array $headers = [], $body = '')
54
    {
55
        if ($this->id === null) {
56
            throw new RuntimeException('You must provide the Droplet ID you want to perform an action on');
57
        }
58
59
        if (method_exists($this, 'getBody') && $body === '') {
60
            $body = $this->getBody();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Billow\Actions\Action as the method getBody() does only exist in the following sub-classes of Billow\Actions\Action: Billow\Actions\ChangeKernel, Billow\Actions\CreateSnapshot, Billow\Actions\DisableBackups, Billow\Actions\EnableBackups, Billow\Actions\EnableIPv6, Billow\Actions\EnablePrivateNetworking, Billow\Actions\PasswordReset, Billow\Actions\PowerCycle, Billow\Actions\PowerOff, Billow\Actions\PowerOn, Billow\Actions\Reboot, Billow\Actions\Rebuild, Billow\Actions\Rename, Billow\Actions\Resize, Billow\Actions\Restore, Billow\Actions\ShutDown, Billow\Actions\Upgrade. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
61
        }
62
63
        if ($body === '' || json_decode($body, true) === []) {
64
            throw new RuntimeException('Body cannot be empty');
65
        }
66
67
        $endpoint = str_replace('[:id:]', $this->id, self::ENDPOINT);
68
69
        return new Request(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \GuzzleHttp\P...oint, $headers, $body); (GuzzleHttp\Psr7\Request) is incompatible with the return type declared by the interface Billow\Actions\ActionInterface::getRequest of type GuzzleHttp\Message\Request.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
70
            static::METHOD,
71
            $endpoint,
72
            $headers,
73
            $body
74
        );
75
    }
76
}
77