Passed
Push — master ( 6760ee...9e3b1c )
by Ion
02:46
created

BaseService::applySearch()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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