Completed
Pull Request — master (#79)
by Jacob
02:58
created

Collection::getIdentifiers()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.2
cc 4
eloc 6
nc 3
nop 1
1
<?php
2
3
namespace As3\Modlr\Models\Collections;
4
5
use As3\Modlr\Models\AbstractModel;
6
7
/**
8
 * Model collection that contains record representations from a persistence (database) layer.
9
 *
10
 * @author Jacob Bare <[email protected]>
11
 */
12
class Collection extends ModelCollection
13
{
14
    /**
15
     * {@inheritDoc}
16
     */
17
    public function getIdentifiers($onlyUnloaded = true)
18
    {
19
        $identifiers = [];
20
        foreach ($this->models as $model) {
21
            if (true === $onlyUnloaded && true === $model->getState()->is('empty')) {
22
                $identifiers[] = $model->getId();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class As3\Modlr\Models\AbstractModel as the method getId() does only exist in the following sub-classes of As3\Modlr\Models\AbstractModel: As3\Modlr\Models\Model. 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...
23
            }
24
        }
25
        return $identifiers;
26
    }
27
28
    /**
29
     * {@inheritDoc}
30
     */
31
    public function getQueryField()
32
    {
33
        return 'id';
0 ignored issues
show
Bug Best Practice introduced by
The return type of return 'id'; (string) is incompatible with the return type declared by the abstract method As3\Modlr\Models\Collect...llection::getQueryField of type boolean.

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...
34
    }
35
}
36