Completed
Branch master (d6051c)
by Roman
09:56
created

Model::getQualifiedKeyName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace lroman242\LaravelCassandra\Eloquent;
4
5
use Carbon\Carbon;
6
use Cassandra\Date;
7
use Cassandra\Rows;
8
use Cassandra\Time;
9
use Cassandra\Timestamp;
10
use lroman242\LaravelCassandra\CassandraTypesTrait;
11
use lroman242\LaravelCassandra\Collection;
12
use lroman242\LaravelCassandra\Query\Builder as QueryBuilder;
13
use Illuminate\Database\Eloquent\Model as BaseModel;
14
15
abstract class Model extends BaseModel
16
{
17
    use CassandraTypesTrait;
18
19
    /**
20
     * The connection name for the model.
21
     *
22
     * @var string
23
     */
24
    protected $connection = 'cassandra';
25
26
    /**
27
     * Indicates if the IDs are auto-incrementing.
28
     * This is not possible in cassandra so we override this
29
     *
30
     * @var bool
31
     */
32
    public $incrementing = false;
33
34
    /**
35
     * The storage format of the model's time columns.
36
     *
37
     * @var string
38
     */
39
    protected $timeFormat;
40
41
    /**
42
     * @inheritdoc
43
     */
44 58
    public function newEloquentBuilder($query)
45
    {
46 58
        return new Builder($query);
47
    }
48
49
    /**
50
     * @inheritdoc
51
     */
52 58
    protected function newBaseQueryBuilder()
53
    {
54 58
        $connection = $this->getConnection();
55
56 58
        return new QueryBuilder($connection, null, $connection->getPostProcessor());
0 ignored issues
show
Compatibility introduced by
$connection of type object<Illuminate\Database\Connection> is not a sub-type of object<lroman242\LaravelCassandra\Connection>. It seems like you assume a child class of the class Illuminate\Database\Connection to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
Documentation introduced by
$connection->getPostProcessor() is of type object<Illuminate\Databa...y\Processors\Processor>, but the function expects a null|object<lroman242\La...sandra\Query\Processor>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
57
    }
58
59
    /**
60
     * @inheritdoc
61
     */
62 13
    public function freshTimestamp()
63
    {
64 13
        return new Timestamp();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Cassandra\Timestamp(); (Cassandra\Timestamp) is incompatible with the return type of the parent method Illuminate\Database\Eloquent\Model::freshTimestamp of type Illuminate\Support\Carbon.

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...
65
    }
66
67
    /**
68
     * @inheritdoc
69
     */
70 13
    public function fromDateTime($value)
71
    {
72
        // If the value is already a Timestamp instance, we don't need to parse it.
73 13
        if ($value instanceof Timestamp) {
0 ignored issues
show
Bug introduced by
The class Cassandra\Timestamp 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...
74 13
            return $value;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $value; (Cassandra\Timestamp) is incompatible with the return type of the parent method Illuminate\Database\Eloquent\Model::fromDateTime of type integer|string.

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...
75
        }
76
77
        // Let Eloquent convert the value to a DateTime instance.
78 1
        if (!$value instanceof \DateTime) {
79 1
            $value = parent::asDateTime($value);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (asDateTime() instead of fromDateTime()). Are you sure this is correct? If so, you might want to change this to $this->asDateTime().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
80
        }
81
82 1
        return new Timestamp($value->getTimestamp() * 1000);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Cassandra\Ti...getTimestamp() * 1000); (Cassandra\Timestamp) is incompatible with the return type of the parent method Illuminate\Database\Eloquent\Model::fromDateTime of type integer|string.

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...
83
    }
84
85
    /**
86
     * @inheritdoc
87
     */
88 8
    protected function asDateTime($value)
89
    {
90
        // Convert UTCDateTime instances.
91 8
        if ($value instanceof Timestamp || $value instanceof Date) {
0 ignored issues
show
Bug introduced by
The class Cassandra\Timestamp 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...
Bug introduced by
The class Cassandra\Date 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...
92 8
            return Carbon::instance($value->toDateTime());
93
        }
94
95
        return parent::asDateTime($value);
96
    }
97
98
    /**
99
     * Get the table qualified key name.
100
     * Cassandra does not support the table.column annotation so
101
     * we override this
102
     *
103
     * @return string
104
     */
105 8
    public function getQualifiedKeyName()
106
    {
107 8
        return $this->getKeyName();
108
    }
109
110
    /**
111
     * Qualify the given column name by the model's table.
112
     *
113
     * @param  string  $column
114
     * @return string
115
     */
116 2
    public function qualifyColumn($column)
117
    {
118 2
        return $column;
119
    }
120
121
    /**
122
     * @inheritdoc
123
     */
124 58
    public function __call($method, $parameters)
125
    {
126
        // Unset method
127 58
        if ($method == 'unset') {
128
            return call_user_func_array([$this, 'drop'], $parameters);
129
        }
130
131 58
        return parent::__call($method, $parameters);
132
    }
133
134
    /**
135
     * Create a new Eloquent Collection instance.
136
     *
137
     * @param  Rows|array  $rows
138
     *
139
     * @return Collection
140
     *
141
     * @throws \Exception
142
     */
143 53
    public function newCassandraCollection($rows)
144
    {
145 53
        if (!is_array($rows) && !$rows instanceof Rows) {
0 ignored issues
show
Bug introduced by
The class Cassandra\Rows 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...
146
            throw new \Exception('Wrong type to create collection');//TODO: customize error
147
        }
148
149 53
        $items = [];
150 53
        foreach ($rows as $row) {
151 50
            $items[] = $this->newFromBuilder($row);
152
        }
153
154 53
        $collection = new Collection($items);
155
156 53
        if ($rows instanceof Rows) {
0 ignored issues
show
Bug introduced by
The class Cassandra\Rows 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...
157 19
            $collection->setRowsInstance($rows);
158
        }
159
160 53
        return $collection;
161
    }
162
163
    /**
164
     * Determine if the new and old values for a given key are equivalent.
165
     *
166
     * @param string $key
167
     * @param mixed $current
168
     *
169
     * @return bool
170
     *
171
     * @throws \Exception
172
     */
173 13
    public function originalIsEquivalent($key, $current)
174
    {
175 13
        if (!array_key_exists($key, $this->original)) {
176 13
            return false;
177
        }
178
179 2
        $original = $this->getOriginal($key);
180
181 2
        if ($current === $original) {
182 2
            return true;
183 2
        } elseif (is_null($current)) {
184
            return false;
185 2
        } elseif ($this->isDateAttribute($key)) {
186 2
            return $this->fromDateTime($current) ===
187 2
                $this->fromDateTime($original);
188 1
        } elseif ($this->hasCast($key)) {
189
            return $this->castAttribute($key, $current) ===
190
                $this->castAttribute($key, $original);
191 1
        } elseif ($this->isCassandraValueObject($current)) {
192
            return $this->valueFromCassandraObject($current) ===
193
                $this->valueFromCassandraObject($original);
194
        }
195
196 1
        return is_numeric($current) && is_numeric($original)
197 1
            && strcmp((string) $current, (string) $original) === 0;
198
    }
199
200
    /**
201
     * Get the value of the model's primary key.
202
     *
203
     * @return mixed
204
     */
205 16
    public function getKey()
206
    {
207 16
        $value = $this->getAttribute($this->getKeyName());
208
209 16
        if ($this->isCassandraValueObject($value)) {
210
            return $this->valueFromCassandraObject($this->getAttribute($this->getKeyName()));
211
        }
212
213 16
        return $value;
214
    }
215
216
    /**
217
     * Cast an attribute to a native PHP type.
218
     *
219
     * @param  string  $key
220
     * @param  mixed  $value
221
     *
222
     * @return mixed
223
     *
224
     * @throws \Exception
225
     */
226 3
    protected function castAttribute($key, $value)
227
    {
228 3
        if ($this->getCastType($key) == 'string' && $value instanceof Time) {
0 ignored issues
show
Bug introduced by
The class Cassandra\Time 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...
229 1
            return (new \DateTime('today', new \DateTimeZone("+0")))
230 1
                ->modify('+' . $value->seconds() . ' seconds')
231 1
                ->format($this->getTimeFormat());
232
        }
233
234 2
        if ($this->getCastType($key) == 'int' && $value instanceof Time) {
0 ignored issues
show
Bug introduced by
The class Cassandra\Time 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...
235
            return $value->seconds();
236
        }
237
238 2
        return parent::castAttribute($key, $value);
239
    }
240
241
    /**
242
     * Get the format for time stored in database.
243
     *
244
     * @return string
245
     */
246 1
    public function getTimeFormat()
247
    {
248 1
        return $this->timeFormat ?: 'H:i:s';
249
    }
250
251
    /**
252
     * Get the format for time stored in database.
253
     *
254
     * @param string $format
255
     *
256
     * @return self
257
     */
258
    public function setTimeFormat($format)
259
    {
260
        $this->timeFormat = $format;
261
262
        return $this;
263
    }
264
}
265