Completed
Push — develop ( 544b7b...88e84c )
by Mohamed
08:50 queued 47s
created

QueryTrait::projectsWidthActivities()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 24
ccs 9
cts 9
cp 1
rs 8.9713
cc 2
eloc 14
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Tinyissue package.
5
 *
6
 * (c) Mohamed Alsharaf <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Tinyissue\Model\Traits\User;
13
14
use Illuminate\Database\Eloquent;
15
use Illuminate\Database\Eloquent\Relations;
16
use Tinyissue\Model\Project;
17
use Tinyissue\Model\Role;
18
19
/**
20
 * QueryTrait is trait class containing the database queries methods for the User model.
21
 *
22
 * @author Mohamed Alsharaf <[email protected]>
23
 *
24
 * @property int                 $id
25
 * @property Eloquent\Collection $permission
26
 *
27
 * @method   Relations\HasMany projects($status = Project::STATUS_OPEN)
28
 * @method   Relations\HasMany permissions()
29
 */
30
trait QueryTrait
31
{
32
    /**
33
     * Returns public users.
34
     *
35
     * @return Eloquent\Collection
36
     */
37 4
    public function activeUsers()
38
    {
39 4
        return $this->with('role')
0 ignored issues
show
Bug introduced by
It seems like with() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
40 4
            ->where('private', '=', false)
41 4
            ->orderBy('firstname', 'ASC')->get();
42
    }
43
44
    /**
45
     * Returns user projects with activities details eager loaded.
46
     *
47
     * @param int $status
48
     *
49
     * @return Relations\HasMany
50
     */
51 10
    public function projectsWidthActivities($status = Project::STATUS_OPEN)
52
    {
53 10
        return $this->projects($status)
54 10
            ->with([
55
                'activities' => function (Relations\Relation $query) {
56 2
                    $query->with('activity', 'issue', 'user', 'assignTo', 'comment', 'note');
57 2
                    $query->orderBy('users_activity.created_at', 'DESC');
58 10
59
                    // For logged users with role User, show issues that are created by them in internal projects
60
                    // of issue create by any for other project statuses
61
                    if (auth()->user()->isUser()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Auth\Authenticatable as the method isUser() does only exist in the following implementations of said interface: Tinyissue\Model\User.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
62
                        $query->join('projects_issues', 'projects_issues.id', '=', 'item_id');
63
                        $query->join('projects', 'projects.id', '=', 'parent_id');
64
                        $query->where(function (Eloquent\Builder $query) {
65
                            $query->where(function (Eloquent\Builder $query) {
66
                                $query->where('created_by', '=', auth()->user()->id);
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
67
                                $query->where('private', '=', Project::INTERNAL_YES);
68
                            });
69 1
                            $query->orWhere('private', '<>', Project::INTERNAL_YES);
70
                        });
71 1
                    }
72
                },
73
            ]);
74 1
    }
75 1
76
    /**
77 1
     * Returns projects with issues details eager loaded.
78 1
     *
79 1
     * @param int $status
80 1
     *
81
     * @return Relations\HasMany
82 1
     */
83
    public function projectsWidthIssues($status = Project::STATUS_OPEN)
84
    {
85
        $assignedOrCreate = $this->isUser() ? 'created_by' : 'assigned_to';
0 ignored issues
show
Bug introduced by
It seems like isUser() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
86
87
        return $this
88
            ->projects($status)
89
            ->with([
90 View Code Duplication
                'issues' => function (Relations\Relation $query) use ($status, $assignedOrCreate) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
91
                    $query->with('updatedBy');
92
                    $query->where($assignedOrCreate, '=', $this->id);
93
                    if ($status === Project::STATUS_OPEN) {
94
                        $query->where('status', '=', Project\Issue::STATUS_OPEN);
95
                    }
96
                },
97
                'issues.user'          => function () {},
98
                'issues.countComments' => function () {},
99
            ]);
100
    }
101
102
    /**
103
     * Returns collection of issues grouped by tags.
104
     *
105
     * @param $tagIds
106
     * @param int $projectId
107
     *
108
     * @return mixed
109
     */
110
    public function issuesGroupByTags($tagIds, $projectId = null)
111
    {
112
        $assignedOrCreate = $this->isUser() ? 'issuesCreatedBy' : 'issues';
0 ignored issues
show
Bug introduced by
It seems like isUser() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
113
        $issues           = $this->$assignedOrCreate()
114
            ->with('user', 'tags')
115
            ->where('status', '=', Project\Issue::STATUS_OPEN)
116
            ->whereIn('projects_issues_tags.tag_id', $tagIds)
117
            ->join('projects_issues_tags', 'issue_id', '=', 'id')
118
            ->orderBy('id');
119
120
        // Limit by project id
121
        if ($projectId > 0) {
122
            $issues->where('project_id', '=', $projectId);
123 60
        }
124
125 60
        $issues = $issues->get()->groupBy(function (Project\Issue $issue) {
126 60
            return $issue->getStatusTag()->name;
127
        });
128
129 60
        return $issues;
130
    }
131
132
    /**
133
     * Load user permissions.
134
     *
135
     * @return Eloquent\Collection
136
     */
137
    protected function loadPermissions()
138
    {
139
        if (null === $this->permission) {
140
            $this->permission = $this->permissions()->with('permission')->get();
141
        }
142
143
        return $this->permission;
144
    }
145
}
146