Completed
Push — develop-3.0 ( 4fe777...24fc5d )
by Mohamed
09:15
created

Fetcher::getActiveProjects()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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\Model\Project;
18
use Tinyissue\Model\User;
19
use Tinyissue\Repository\Repository;
20
21
class Fetcher extends Repository
22
{
23
    public function __construct(Project $model)
24
    {
25
        $this->model = $model;
0 ignored issues
show
Documentation Bug introduced by
It seems like $model of type object<Tinyissue\Model\Project> is incompatible with the declared type object<Tinyissue\Repository\Model> of property $model.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
26
    }
27
28
    /**
29
     * Returns collection of active projects.
30
     *
31
     * @return Eloquent\Collection
32
     */
33
    public function getActiveProjects()
34
    {
35
        return $this->model->active()->orderBy('name', 'ASC')->get();
36
    }
37
38
    public function getNotes()
39
    {
40
        return $this->model->notes()->with('createdBy')->get();
41
    }
42
43
    /**
44
     * Returns collection of public projects.
45
     *
46
     * @return Eloquent\Collection
47
     */
48
    public function getPublicProjects()
49
    {
50
        return $this->model->public()->orderBy('name', 'ASC')->get();
51
    }
52
53
    /**
54
     * Returns all users that are not assigned in the current project.
55
     *
56
     * @return array
57
     */
58
    public function getNotMembers()
59
    {
60
        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...
61
    }
62
63
    /**
64
     * Fetch and filter issues in the project.
65
     *
66
     * @param int   $status
67
     * @param array $filter
68
     *
69
     * @return \Illuminate\Database\Eloquent\Collection
70
     */
71
    public function getIssues($status = Project\Issue::STATUS_OPEN, array $filter = [])
72
    {
73
        $sortOrder = array_get($filter, 'sort.sortorder', 'desc');
74
        $sortBy = array_get($filter, 'sort.sortby', null);
75
76
        $query = $this->model->issues()
77
            ->with('countComments', 'user', 'updatedBy', 'tags', 'tags.parent')
78
            ->with([
79
                'tags' => function (Relation $query) use ($sortOrder) {
80
                    $query->orderBy('name', $sortOrder);
81
                },
82
            ])
83
            ->status($status)
84
            ->assignedTo(array_get($filter, 'assignto'))
85
            ->searchContent(array_get($filter, 'keyword'))
86
            ->createdBy(array_get($filter, 'created_by'))
87
            ->whereTags(array_get($filter, 'tag_status'), array_get($filter, 'tag_type'));
88
89
        // Sort
90 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...
91
            $this->sortByUpdated($query, $sortOrder);
92
        } elseif (($tagGroup = substr($sortBy, strlen('tag:'))) > 0) {
93
            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 documented by Tinyissue\Repository\Project\Fetcher::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...
94
        }
95
96
        return $query->get();
97
    }
98
99
    /**
100
     * Fetch and filter issues in the project.
101
     *
102
     * @param int   $status
103
     * @param array $filter
104
     *
105
     * @return \Illuminate\Database\Eloquent\Collection
106
     */
107
    public function getIssuesForLoggedUser($status = Project\Issue::STATUS_OPEN, array $filter = [])
108
    {
109
        if ($this->model->isPrivateInternal() && $this->getLoggedUser()->isUser()) {
110
            $request['created_by'] = $this->getLoggedUser()->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...
Coding Style Comprehensibility introduced by
$request was never initialized. Although not strictly required by PHP, it is generally a good practice to add $request = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
111
        }
112
113
        return $this->getIssues($status, $filter);
114
    }
115
116
    /**
117
     * Fetch issues assigned to a user.
118
     *
119
     * @param UserInterface $user
120
     *
121
     * @return \Illuminate\Database\Eloquent\Collection
122
     */
123
    public function getAssignedOrCreatedIssues(UserInterface $user)
124
    {
125
        if ($user->isUser()) {
126
            return $this->getCreatedIssues($user);
127
        }
128
129
        return $this->getAssignedIssues($user);
130
    }
131
132
    public function getCreatedIssues(UserInterface $user)
133
    {
134
        return $this->model->openIssues()
135
            ->with('countComments', 'user', 'updatedBy')
136
            ->createdBy($user)
137
            ->orderBy('updated_at', 'DESC')
138
            ->get();
139
    }
140
141
    public function getAssignedIssues(UserInterface $user)
142
    {
143
        return $this->model->openIssues()
144
            ->with('countComments', 'user', 'updatedBy')
145
            ->assignedTo($user)
146
            ->orderBy('updated_at', 'DESC')
147
            ->get();
148
    }
149
150
    public function getRecentActivities(UserInterface $user = null, $limit = 10)
151
    {
152
        $activities = $this->model->activities()
153
            ->with('activity', 'issue', 'user', 'assignTo', 'comment', 'note')
154
            ->orderBy('users_activity.created_at', 'DESC')
155
            ->take($limit);
156
157
        // Internal project and logged user can see created only
158
        if ($this->model->isPrivateInternal() && $user instanceof UserInterface && $user->isUser()) {
159
            $activities->join('projects_issues', 'projects_issues.id', '=', 'item_id');
160
            $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...
161
        }
162
163
        return $activities->get();
164
    }
165
166
    /**
167
     * Returns projects with issues details eager loaded.
168
     *
169
     * @return Relations\HasMany
170
     */
171
    public function getPublicProjectsWithRecentIssues()
172
    {
173
        return $this->model
174
            ->active()
175
            ->public()
176
            ->with('openIssuesWithUpdater', 'issues.user', 'issues.countComments')
177
            ->orderBy('name')
178
            ->get();
179
    }
180
181
    /**
182
     * Returns collection of tags for Kanban view.
183
     *
184
     * @param UserInterface $user
185
     *
186
     * @return mixed
187
     */
188
    public function getKanbanTagsForUser(UserInterface $user)
189
    {
190
        return $this->model->kanbanTags()->accessibleToUser($user)->get();
191
    }
192
193
    public function getKanbanTags()
194
    {
195
        return $this->model->kanbanTags()->get();
196
    }
197
198
    /**
199
     * Returns users assigned to the project that can fix issues (with edit permission).
200
     *
201
     * @return Relations\BelongsToMany
202
     */
203
    public function getUsersCanFixIssue()
204
    {
205
        //        $r = $this->users()->where('users.role_id', '>', 1)->where('users.deleted', '=', User::NOT_DELETED_USERS);//->get();
206
//return $r;
207
        return $this->model->users()->developerOrHigher()->notDeleted()->get();
208
//return $r2->get();
209
//        dd($r->toSql(), $r2->toSql());
210
    }
211
212
    public function getUsers()
213
    {
214
        return $this->model->users()->notDeleted()->get();
215
    }
216
217
    /**
218
     * Sort by updated_at column.
219
     *
220
     * @param HasMany $query
221
     * @param string  $order
222
     *
223
     * @return void
224
     */
225
    protected function sortByUpdated(HasMany $query, $order = 'asc')
226
    {
227
        $query->orderBy('updated_at', $order);
228
    }
229
230
    /**
231
     * Sort by issues tag group
232
     * Note: this sort will return the collection.
233
     *
234
     * @param HasMany $query
235
     * @param string  $tagGroup
236
     * @param string  $order
237
     *
238
     * @return Eloquent\Collection
239
     */
240 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...
241
    {
242
        // If tag group is string prefixed with tag:
243
        if (!is_numeric($tagGroup)) {
244
            $tagGroup = substr($tagGroup, strlen('tag:'));
245
        }
246
247
        $results = $query->get()
248
            ->sort(function (Project\Issue $issue1, Project\Issue $issue2) use ($tagGroup, $order) {
249
                $tag1 = $issue1->tags->where('parent.id', $tagGroup)->first();
250
                $tag2 = $issue2->tags->where('parent.id', $tagGroup)->first();
251
                $tag1 = $tag1 ? $tag1->name : '';
252
                $tag2 = $tag2 ? $tag2->name : '';
253
254
                if ($order === 'asc') {
255
                    return strcmp($tag1, $tag2);
256
                }
257
258
                return strcmp($tag2, $tag1);
259
            });
260
261
        return $results;
262
    }
263
264
    /**
265
     * Returns projects with open issue count.
266
     *
267
     * @param int $status
268
     * @param int $private
269
     *
270
     * @return Collection
271
     */
272 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...
273
    {
274
        $query = $this->model->with('openIssuesCount')->status($status);
275
276
        if ($private !== Project::PRIVATE_ALL) {
277
            $query->where('private', '=', $private);
278
        }
279
280
        return $query->get();
281
    }
282
283
    /**
284
     * Return projects with count of open & closed issues.
285
     *
286
     * @param array $projectIds
287
     *
288
     * @return Collection
289
     */
290
    public function getProjectsWithCountIssues(array $projectIds)
291
    {
292
        return $this->model
293
            ->with('openIssuesCount', 'closedIssuesCount')
294
            ->whereIn('id', $projectIds)
295
            ->get();
296
    }
297
}
298