Completed
Push — master ( 7949b1...be02a5 )
by Nick
07:10
created

EloquentJsQueries::scopeUseEloquentJs()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

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.4286
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
namespace EloquentJs\Laravel\Model;
4
5
use Carbon\Carbon;
6
use DateTime;
7
use InvalidArgumentException;
8
use EloquentJs\Laravel\Events\EloquentJsWasCalled;
9
use UnexpectedValueException;
10
11
trait EloquentJsQueries
12
{
13
    /**
14
     * Scope to results that satisfy the string-encoded list of query methods described by $stack.
15
     *
16
     * @param \Illuminate\Database\Eloquent\Builder $query
17
     * @param string $stack
18
     */
19
    public function scopeUseEloquentJs($query, $stack = null)
20
    {
21
        if ( ! static::$dispatcher) {
22
            throw new UnexpectedValueException(
23
                'Event dispatcher not found. Install illuminate/events package for EloquentJS usage without Laravel.'
24
            );
25
        }
26
27
        static::$dispatcher->fire(new EloquentJsWasCalled($query, $stack));
28
    }
29
30
    /**
31
     * Handle dynamic calls to scope methods.
32
     *
33
     * Yes, this is indeed a scope for calling another scope method.
34
     * While there are other ways we could support scopes, this has
35
     * the benefit of requiring no special treatment in our BaseQueryTranslator
36
     * - no different from how we handle `where`, `orderBy`, etc.
37
     *
38
     * @param \Illuminate\Database\Eloquent\Builder $query
39
     * @param string $name
40
     * @param array $parameters
41
     */
42
    public function scopeScope($query, $name, $parameters = [])
43
    {
44
        $methodName = 'scope'.ucfirst($name);
45
46
        if ( ! method_exists($this, $methodName)) {
47
            throw new InvalidArgumentException("No such scope [$name]");
48
        }
49
50
        array_unshift($parameters, $query);
51
        call_user_func_array([$this, $methodName], $parameters);
52
    }
53
54
    /**
55
     * Prepare a date for array / JSON serialization.
56
     *
57
     * Overrides the date serializer to ensure our Javascript can
58
     * understand the format.
59
     *
60
     * @todo  implement date handling without global side effects
61
     * @param DateTime $date
62
     * @return string
63
     */
64
    protected function serializeDate(DateTime $date)
65
    {
66
        return $date->toIso8601String();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DateTime as the method toIso8601String() does only exist in the following sub-classes of DateTime: Carbon\Carbon, Tests\Carbon\Fixtures\MyCarbon. 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...
67
    }
68
69
    /**
70
     * Return a timestamp as DateTime object.
71
     *
72
     * Accept dates from Javascript in any format that Carbon recognises.
73
     *
74
     * @param  string $value
75
     * @return Carbon
76
     */
77
    protected function asDateTime($value)
78
    {
79
        if (is_string($value)) {
80
            return Carbon::parse($value);
81
        }
82
83
        return parent::asDateTime($value);
84
    }
85
86
    /**
87
     * Get the endpoint defined on this model.
88
     *
89
     * @return string|null
90
     */
91
    public function getEndpoint()
92
    {
93
        if (property_exists($this, 'endpoint')) {
94
            return $this->endpoint;
95
        }
96
97
        return null;
98
    }
99
}
100