Completed
Pull Request — master (#79)
by Jacob
03:06
created

ModelCollection   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 129
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 13
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 129
rs 10

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A allWithoutLoad() 0 4 1
getIdentifiers() 0 1 ?
A getMetadata() 0 4 1
getQueryField() 0 1 ?
A getSingleResult() 0 5 1
A getType() 0 4 1
A rewind() 0 5 1
A loadFromStore() 0 9 2
A modelsMatch() 0 6 2
A validateAdd() 0 5 1
A validateModelClass() 0 6 2
1
<?php
2
3
namespace As3\Modlr\Models\Collections;
4
5
use As3\Modlr\Metadata\EntityMetadata;
6
use As3\Modlr\Models\AbstractModel;
7
use As3\Modlr\Store\Store;
8
9
/**
10
 * Model collection that contains record representations from a persistence (database) layer.
11
 *
12
 * @author Jacob Bare <[email protected]>
13
 */
14
abstract class ModelCollection extends AbstractCollection
15
{
16
    /**
17
     * @var EntityMetadata
18
     */
19
    protected $metadata;
20
21
    /**
22
     * Constructor.
23
     *
24
     * @param   EntityMetadata  $metadata
25
     * @param   Store           $store
26
     * @param   AbstractModel[] $models
27
     */
28
    public function __construct(EntityMetadata $metadata, Store $store, array $models = [])
29
    {
30
        $this->metadata = $metadata;
31
        parent::__construct($store, $models);
32
    }
33
34
    /**
35
     * Returns all models in this collection without triggering auto-loading.
36
     *
37
     * @return  Model[]
38
     */
39
    public function allWithoutLoad()
40
    {
41
        return $this->models;
42
    }
43
44
    /**
45
     * Gets the identifiers for this collection.
46
     *
47
     * @param   bool    $onlyUnloaded   Whether to only include unloaded models in the results.
48
     * @return  array
49
     */
50
    abstract public function getIdentifiers($onlyUnloaded = true);
51
52
    /**
53
     * Gets the metadata for the model collection.
54
     *
55
     * @return  EntityMetadata
56
     */
57
    public function getMetadata()
58
    {
59
        return $this->metadata;
60
    }
61
62
    /**
63
     * Gets the query field for this collection.
64
     *
65
     * @return  bool
66
     */
67
    abstract public function getQueryField();
68
69
    /**
70
     * {@inheritdoc}
71
     *
72
     * Overloaded to ensure models are loaded from the store.
73
     *
74
     */
75
    public function getSingleResult()
76
    {
77
        $this->loadFromStore();
78
        return parent::getSingleResult();
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function getType()
85
    {
86
        return $this->getMetadata()->type;
87
    }
88
89
    /**
90
     * {@inheritDoc}
91
     */
92
    public function rewind()
93
    {
94
        $this->loadFromStore();
95
        parent::rewind();
96
    }
97
98
    /**
99
     * Loads this collection from the store.
100
     */
101
    protected function loadFromStore()
102
    {
103
        if (false === $this->isLoaded()) {
104
            // Loads collection from the database on iteration.
105
            $models = $this->store->loadCollection($this);
106
            $this->setModels($models);
107
            $this->loaded = true;
108
        }
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    protected function modelsMatch(AbstractModel $model, AbstractModel $loaded)
115
    {
116
        $this->validateModelClass($model);
117
        $this->validateModelClass($loaded);
118
        return $model->getType() === $loaded->getType() && $model->getId() === $loaded->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 getType() 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...
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...
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    protected function validateAdd(AbstractModel $model)
125
    {
126
        $this->validateModelClass($model);
127
        $this->store->validateRelationshipSet($this->getMetadata(), $model->getType());
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 getType() 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...
128
    }
129
130
    /**
131
     * Validates that the model class instance is supported.
132
     *
133
     * @param   AbstractModel   $model
134
     * @throws  \InvalidArgumentException
135
     */
136
    protected function validateModelClass(AbstractModel $model)
137
    {
138
        if (!$model instanceof Model) {
0 ignored issues
show
Bug introduced by
The class As3\Modlr\Models\Collections\Model does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
139
            throw new \InvalidArgumentExcepton('The model must be an instanceof of Model');
140
        }
141
    }
142
}
143