1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the Laravel MultiLang package. |
4
|
|
|
* |
5
|
|
|
* (c) Avtandil Kikabidze aka LONGMAN <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Longman\LaravelMultiLang\Models; |
12
|
|
|
|
13
|
|
|
use Illuminate\Database\Eloquent\Builder; |
14
|
|
|
use Illuminate\Database\Eloquent\Model; |
15
|
|
|
use Illuminate\Database\Eloquent\Scope; |
16
|
|
|
|
17
|
|
|
class LocalizableScope implements Scope |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Apply the scope to a given Eloquent query builder. |
21
|
|
|
* |
22
|
|
|
* @param \Illuminate\Database\Eloquent\Builder $builder |
23
|
|
|
* @param \Illuminate\Database\Eloquent\Model $model |
24
|
|
|
* @return void |
25
|
|
|
*/ |
26
|
|
|
public function apply(Builder $builder, Model $model) |
27
|
|
|
{ |
28
|
|
|
|
29
|
|
|
if (!$this->queryHasLocalizableColumn($builder)) { |
30
|
|
|
$builder->where($model->getQualifiedLocalizableColumn(), '=', app()->getLocale()); |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Check if query has "localizable" column |
36
|
|
|
* |
37
|
|
|
* @param \Illuminate\Database\Eloquent\Builder $builder |
38
|
|
|
* @return bool |
39
|
|
|
*/ |
40
|
|
|
protected function queryHasLocalizableColumn(Builder $builder) |
41
|
|
|
{ |
42
|
|
|
$wheres = $builder->getQuery()->wheres; |
43
|
|
|
$column = $this->getLocalizableColumn($builder); |
44
|
|
|
if (!empty($wheres)) { |
45
|
|
|
foreach ($wheres as $where) { |
46
|
|
|
if (isset($where['column']) && $where['column'] == $column) { |
47
|
|
|
return true; |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
return false; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Get the "localizable" column for the builder. |
56
|
|
|
* |
57
|
|
|
* @param \Illuminate\Database\Eloquent\Builder $builder |
58
|
|
|
* @return string |
59
|
|
|
*/ |
60
|
|
|
protected function getLocalizableColumn(Builder $builder) |
61
|
|
|
{ |
62
|
|
|
if (count($builder->getQuery()->joins) > 0) { |
63
|
|
|
return $builder->getModel()->getQualifiedLocalizableColumn(); |
64
|
|
|
} else { |
65
|
|
|
return $builder->getModel()->getLocalizableColumn(); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
} |
70
|
|
|
|