Passed
Push — master ( f1a782...17ae54 )
by Ion
04:19 queued 45s
created

BaseService::getPaginationData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 11
rs 10
1
<?php
2
3
namespace App\Services;
4
5
use App\Models\Language;
6
use App\Models\RolePermission;
7
use App\Models\User;
8
use Exception;
9
use Illuminate\Database\Eloquent\Builder;
10
use Illuminate\Http\Request;
11
use Illuminate\Support\Facades\Auth;
12
use Illuminate\Support\Facades\Cache;
13
use Illuminate\Support\Facades\File;
14
use Intervention\Image\Facades\Image;
15
16
/**
17
 * Class BaseService
18
 *
19
 * @package App\Services
20
 */
21
class BaseService
22
{
23
    /**
24
     * Apply search
25
     *
26
     * @param Builder $builder
27
     * @param $term
28
     *
29
     * @return Builder
30
     */
31
    public function applySearch(Builder $builder, $term)
32
    {
33
        $builder->where(function ($query) use ($term) {
34
            foreach ($query->getModel()->getSearchable() as $searchColumn) {
35
                if (in_array($searchColumn, $query->getModel()->getEncrypted())) {
36
                    $query->orWhereEncrypted($searchColumn, '%' . $term . '%');
37
                } else {
38
                    $query->orWhere($searchColumn, 'LIKE', '%' . $term . '%');
39
                }
40
            }
41
        });
42
43
        return $builder;
44
    }
45
46
    /**
47
     * Apply filters
48
     *
49
     * @param Builder $builder
50
     * @param array $filters
51
     *
52
     * @return Builder
53
     */
54
    public function applyFilters(Builder $builder, array $filters)
55
    {
56
        foreach ($filters as $filter => $value) {
57
            if (in_array($filter, $builder->getModel()->getFiltrable())) {
58
                if (in_array($filter, $builder->getModel()->getEncrypted())) {
59
                    $builder->whereEncrypted($filter, $value);
60
                } else {
61
                    $builder->where($filter, $value);
62
                }
63
            }
64
        }
65
66
        return $builder;
67
    }
68
69
    /**
70
     * Apply sort params.
71
     *
72
     * @param Request $request
73
     * @param $builder
74
     *
75
     * @return Builder
76
     */
77
    public function applySortParams(Request $request, Builder $builder)
78
    {
79
        if ($request->has('sortColumn') || $request->has('sortOrder')) {
80
            $sortColumn = strtolower($request->get('sortColumn', 'id'));
81
            $sortOrder = strtolower($request->get('sortOrder', 'asc'));
82
83
            if (in_array($sortColumn, $builder->getModel()->getSortable()) && in_array($sortOrder, ['asc', 'desc'])) {
84
                if (in_array($sortColumn, $builder->getModel()->getEncrypted())) {
85
                    return $builder->orderByEncrypted($sortColumn, $sortOrder);
86
                }
87
88
                return $builder->orderBy($sortColumn, $sortOrder);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $builder->orderBy($sortColumn, $sortOrder) also could return the type Illuminate\Database\Query\Builder which is incompatible with the documented return type Illuminate\Database\Eloquent\Builder.
Loading history...
89
            }
90
        }
91
92
        return $builder;
93
    }
94
95
    /**
96
     * Get pagination offset and limit.
97
     *
98
     * @param Request $request
99
     *
100
     * @return array
101
     */
102
    public function getPaginationParams(Request $request)
103
    {
104
        $limit = 10;
105
        if ($request->has('limit')) {
106
            $requestLimit = (int)$request->get('limit');
107
108
            if ($requestLimit > 0) {
109
                $limit = $requestLimit;
110
            }
111
        }
112
113
        $offset = 0;
114
        $page = 1;
115
116
        if ($request->has('page')) {
117
            $requestPage = (int)$request->get('page');
118
119
            if ($requestPage > 1) {
120
                $page = $requestPage;
121
            }
122
123
            $offset = ($page - 1) * $limit;
124
        }
125
126
        return [
127
            'page' => $page,
128
            'offset' => $offset,
129
            'limit' => $limit
130
        ];
131
    }
132
133
    /**
134
     * Get pagination data.
135
     *
136
     * @param Builder $builder
137
     * @param $page
138
     * @param $limit
139
     *
140
     * @return array
141
     */
142
    public function getPaginationData(Builder $builder, $page, $limit)
143
    {
144
        $totalEntries = $builder->count();
145
146
        $totalPages = ceil($totalEntries / $limit);
147
148
        return [
149
            'currentPage' => $page > $totalPages ? $totalPages : $page,
150
            'totalPages' => $totalPages,
151
            'limit' => $limit,
152
            'totalEntries' => $totalEntries
153
        ];
154
    }
155
156
    /**
157
     * Get language to use.
158
     *
159
     * @param Request $request
160
     *
161
     * @return Language
162
     *
163
     * @throws Exception
164
     */
165
    public function getLanguage(Request $request)
166
    {
167
        if ($request->has('language')) {
168
            /** @var Language $language */
169
            $language = Language::where('code', strtolower($request->get('language')))->first();
170
171
            if ($language) {
0 ignored issues
show
introduced by
$language is of type App\Models\Language, thus it always evaluated to true.
Loading history...
172
                return $language;
173
            }
174
        }
175
176
        /** @var User|null $user */
177
        $user = Auth::user();
178
179
        if ($user) {
0 ignored issues
show
introduced by
$user is of type App\Models\User, thus it always evaluated to true.
Loading history...
180
            /** @var Language $language */
181
            $language = Language::where('id', $user->language_id)->first();
182
183
            if ($language) {
0 ignored issues
show
introduced by
$language is of type App\Models\Language, thus it always evaluated to true.
Loading history...
184
                return $language;
185
            }
186
        }
187
188
        /** @var Language $language */
189
        $language = Language::where('code', env('APP_LOCALE'))->first();
190
191
        if ($language) {
192
            return $language;
193
        }
194
195
        throw new Exception('Application is bad configured!');
196
    }
197
198
    /**
199
     * Check if a logged user has permission on action
200
     *
201
     * @param $userId
202
     * @param $permissionId
203
     *
204
     * @return RolePermission
205
     */
206
    public function getUserPermissionActions($userId, $permissionId)
207
    {
208
        /** @var RolePermission $rolePermission */
209
        $rolePermission = Cache::tags(['permissions'])
210
            ->remember(
211
                'permission' . $userId . $permissionId,
212
                env('CACHE_PERIOD'),
213
                function () use ($userId, $permissionId) {
214
                    return RolePermission::where('permission_id', $permissionId)
215
                        ->whereHas('role', function ($query) use ($userId) {
216
                            $query->whereHas('users', function ($query) use ($userId) {
217
                                $query->where('id', $userId);
218
                            });
219
                        })->first();
220
                }
221
            );
222
223
        return $rolePermission;
224
    }
225
226
    /**
227
     * Process images.
228
     *
229
     * @param $path
230
     * @param $image
231
     * @param $name
232
     * @param bool $generateAvatar
233
     * @param bool $onlyAvatar
234
     *
235
     * @return false|string
236
     */
237
    public function processImage($path, $image, $name, $generateAvatar = false, $onlyAvatar = false)
238
    {
239
        $pictureData = [];
240
241
        if ($generateAvatar) {
242
            $avatarImage = Image::make($image)->resize(200, 200, function ($constraint) {
243
                $constraint->aspectRatio();
244
                $constraint->upsize();
245
            });
246
247
            $color = $this->getColorAverage($avatarImage);
248
249
            $avatarCanvas = Image::canvas(200, 200, $color);
250
251
            $avatarCanvas->insert($avatarImage, 'center');
252
253
            $avatarPath = $path . 'avatar/';
254
            File::makeDirectory($avatarPath, 0777, true, true);
255
256
            $avatarCanvas->save($avatarPath . $name, 100);
257
258
            $pictureData['avatar'] = $avatarPath . $name;
259
        }
260
261
        if ($onlyAvatar) {
262
            return json_encode($pictureData);
263
        }
264
265
        $mediumImage = Image::make($image)->resize(1024, 768, function ($constraint) {
266
            $constraint->aspectRatio();
267
            $constraint->upsize();
268
        });
269
270
        $mediumPath = $path . 'medium/';
271
        File::makeDirectory($mediumPath, 0777, true, true);
272
273
        $mediumImage->save($mediumPath . $name, 100);
274
        $pictureData['medium'] = $mediumPath . $name;
275
276
        $originalMaxImage = Image::make($image)->resize(1920, 1080, function ($constraint) {
277
            $constraint->aspectRatio();
278
            $constraint->upsize();
279
        });
280
281
        $originalPath = $path . 'original/';
282
        File::makeDirectory($originalPath, 0777, true, true);
283
284
        $originalMaxImage->save($originalPath . $name, 100);
285
        $pictureData['original'] = $originalPath . $name;
286
287
        return json_encode($pictureData);
288
    }
289
290
    /**
291
     * Get average image color.
292
     *
293
     * @param $image
294
     * @return array
295
     */
296
    private function getColorAverage($image)
297
    {
298
        $image = clone $image;
299
300
        $color = $image->limitColors(1)->pickColor(0, 0);
301
        $image->destroy();
302
303
        return $color;
304
    }
305
}
306