Completed
Branch develop-3.0 (4fe777)
by Mohamed
11:06
created

ProjectRepository::getAssignedIssues()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
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\Repository\Project;
13
14
use Illuminate\Database\Eloquent\Collection;
15
use Illuminate\Database\Eloquent\Relations\Relation;
16
use Tinyissue\Contracts\Model\UserInterface;
17
use Tinyissue\Contracts\Repository\Project\ProjectRepository as ProjectContract;
18
use Tinyissue\Model\Project;
19
use Tinyissue\Model\User;
20
use Tinyissue\Repository\Repository;
21
22
class ProjectRepository extends Repository implements ProjectContract
23
{
24
    protected $updaterClass = UpdaterRepository::class;
25
    protected $counterClass = CounterRepository::class;
26
27
    public function __construct(Project $model)
28
    {
29
        $this->model = $model;
30
    }
31
32
    /**
33
     * Returns collection of active projects.
34
     *
35
     * @return Eloquent\Collection
36
     */
37
    public function getActiveProjects()
38
    {
39
        return $this->model->active()->orderBy('name', 'ASC')->get();
40
    }
41
42
    public function getNotes()
43
    {
44
        return $this->model->notes()->with('createdBy')->get();
45
    }
46
47
    /**
48
     * Returns collection of public projects.
49
     *
50
     * @return Eloquent\Collection
51
     */
52
    public function getPublicProjects()
53
    {
54
        return $this->model->public()->orderBy('name', 'ASC')->get();
55
    }
56
57
    /**
58
     * Returns all users that are not assigned in the current project.
59
     *
60
     * @return array
61
     */
62
    public function getNotMembers()
63
    {
64
        return (new User())->notDeleted()->notMemberOfProject($this->model)->get();
0 ignored issues
show
Bug introduced by
The method notDeleted() does not exist on Tinyissue\Model\User. Did you maybe mean delete()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
65
    }
66
67
    /**
68
     * Fetch and filter issues in the project.
69
     *
70
     * @param int   $status
71
     * @param array $filter
72
     *
73
     * @return \Illuminate\Database\Eloquent\Collection
74
     */
75
    public function getIssues($status = Project\Issue::STATUS_OPEN, array $filter = [])
76
    {
77
        $sortOrder = array_get($filter, 'sort.sortorder', 'desc');
78
        $sortBy    = array_get($filter, 'sort.sortby', null);
79
80
        $query = $this->model->issues()
81
            ->with('countComments', 'user', 'updatedBy', 'tags', 'tags.parent')
82
            ->with([
83
                'tags' => function (Relation $query) use ($sortOrder) {
84
                    $query->orderBy('name', $sortOrder);
85
                },
86
            ])
87
            ->status($status)
88
            ->assignedTo(array_get($filter, 'assignto'))
89
            ->searchContent(array_get($filter, 'keyword'))
90
            ->createdBy(array_get($filter, 'created_by'))
91
            ->whereTags(array_get($filter, 'tag_status'), array_get($filter, 'tag_type'));
92
93
        // Sort
94 View Code Duplication
        if ($sortBy === 'updated') {
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...
95
            $this->sortByUpdated($query, $sortOrder);
96
        } elseif (($tagGroup = substr($sortBy, strlen('tag:'))) > 0) {
97
            return $this->sortByTag($query, $tagGroup, $sortOrder);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->sortByTag(...$tagGroup, $sortOrder); (Tinyissue\Repository\Project\Eloquent\Collection) is incompatible with the return type declared by the interface Tinyissue\Contracts\Repo...ctRepository::getIssues of type Illuminate\Database\Eloquent\Collection.

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...
98
        }
99
100
        return $query->get();
101
    }
102
103
    /**
104
     * Fetch issues assigned to a user.
105
     *
106
     * @param UserInterface $user
107
     *
108
     * @return \Illuminate\Database\Eloquent\Collection
109
     */
110
    public function getAssignedOrCreatedIssues(UserInterface $user)
111
    {
112
        if ($user->isUser()) {
113
            return $this->getCreatedIssues($user);
114
        }
115
116
        return $this->getAssignedIssues($user);
117
    }
118
119
    public function getCreatedIssues(UserInterface $user)
120
    {
121
        return $this->model->openIssues()
122
            ->with('countComments', 'user', 'updatedBy')
123
            ->createdBy($user)
124
            ->orderBy('updated_at', 'DESC')
125
            ->get();
126
    }
127
128
    public function getAssignedIssues(UserInterface $user)
129
    {
130
        return $this->model->openIssues()
131
            ->with('countComments', 'user', 'updatedBy')
132
            ->assignedTo($user)
133
            ->orderBy('updated_at', 'DESC')
134
            ->get();
135
    }
136
137
    public function getRecentActivities(UserInterface $user, $limit = 10)
138
    {
139
        $activities = $this->model->activities()
140
            ->with('activity', 'issue', 'user', 'assignTo', 'comment', 'note')
141
            ->orderBy('users_activity.created_at', 'DESC')
142
            ->take($limit);
143
144
        // Internal project and logged user can see created only
145
        if ($this->isPrivateInternal() && $user->isUser()) {
0 ignored issues
show
Documentation Bug introduced by
The method isPrivateInternal does not exist on object<Tinyissue\Reposit...ject\ProjectRepository>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
146
            $activities->join('projects_issues', 'projects_issues.id', '=', 'item_id');
147
            $activities->where('created_by', '=', $user->id);
0 ignored issues
show
Bug introduced by
Accessing id on the interface Tinyissue\Contracts\Model\UserInterface 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...
148
        }
149
150
        return $activities;
151
    }
152
153
    /**
154
     * Returns projects with issues details eager loaded.
155
     *
156
     * @return Relations\HasMany
157
     */
158
    public function getPublicProjectsWithRecentIssues()
159
    {
160
        return $this->model
161
            ->active()
162
            ->public()
163
            ->with('openIssuesWithUpdater', 'issues.user', 'issues.countComments')
164
            ->orderBy('name')
165
            ->get();
166
    }
167
168
    /**
169
     * Returns collection of tags for Kanban view.
170
     *
171
     * @param UserInterface $user
172
     *
173
     * @return mixed
174
     */
175
    public function getKanbanTagsForUser(UserInterface $user)
176
    {
177
        return $this->model->kanbanTags()->accessibleToUser($user)->get();
178
    }
179
180
    public function getKanbanTags()
181
    {
182
        return $this->model->kanbanTags()->get();
183
    }
184
185
    /**
186
     * Returns users assigned to the project that can fix issues (with edit permission).
187
     *
188
     * @return Relations\BelongsToMany
189
     */
190
    public function getUsersCanFixIssue()
191
    {
192
        //        $r = $this->users()->where('users.role_id', '>', 1)->where('users.deleted', '=', User::NOT_DELETED_USERS);//->get();
193
//return $r;
194
        return $this->model->users()->developerOrHigher()->notDeleted()->get();
195
//return $r2->get();
196
//        dd($r->toSql(), $r2->toSql());
197
    }
198
199
    /**
200
     * Sort by updated_at column.
201
     *
202
     * @param HasMany $query
203
     * @param string  $order
204
     *
205
     * @return void
206
     */
207
    protected function sortByUpdated(HasMany $query, $order = 'asc')
208
    {
209
        $query->orderBy('updated_at', $order);
210
    }
211
212
    /**
213
     * Sort by issues tag group
214
     * Note: this sort will return the collection.
215
     *
216
     * @param HasMany $query
217
     * @param string  $tagGroup
218
     * @param string  $order
219
     *
220
     * @return Eloquent\Collection
221
     */
222 View Code Duplication
    protected function sortByTag(HasMany $query, $tagGroup, $order = 'asc')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
223
    {
224
        // If tag group is string prefixed with tag:
225
        if (!is_numeric($tagGroup)) {
226
            $tagGroup = substr($tagGroup, strlen('tag:'));
227
        }
228
229
        $results = $query->get()
230
            ->sort(function (Project\Issue $issue1, Project\Issue $issue2) use ($tagGroup, $order) {
231
                $tag1 = $issue1->tags->where('parent.id', $tagGroup, false)->first();
232
                $tag2 = $issue2->tags->where('parent.id', $tagGroup, false)->first();
233
                $tag1 = $tag1 ? $tag1->name : '';
234
                $tag2 = $tag2 ? $tag2->name : '';
235
236
                if ($order === 'asc') {
237
                    return strcmp($tag1, $tag2);
238
                }
239
240
                return strcmp($tag2, $tag1);
241
            });
242
243
        return $results;
244
    }
245
246
    /**
247
     * Returns projects with open issue count.
248
     *
249
     * @param int $status
250
     * @param int $private
251
     *
252
     * @return Collection
253
     */
254 View Code Duplication
    public function getProjectsWithOpenIssuesCount($status = Project::STATUS_OPEN, $private = Project::PRIVATE_YES)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
255
    {
256
        $query = $this->model->with('countOpenIssues')->status($status);
257
258
        if ($private !== Project::PRIVATE_ALL) {
259
            $query->where('private', '=', $private);
260
        }
261
262
        return $query->get();
263
    }
264
265
    /**
266
     * Return projects with count of open & closed issues.
267
     *
268
     * @param array $projectIds
269
     *
270
     * @return Collection
271
     */
272
    public function getProjectsWithCountIssues(array $projectIds)
273
    {
274
        return $this->model
275
            ->with('countOpenIssues', 'countOpenIssues')
276
            ->whereIn('id', $projectIds)
277
            ->get();
278
    }
279
}
280