1: <?php
2:
3: /**
4: * Deep
5: *
6: * @package rsanchez\Deep
7: * @author Rob Sanchez <info@robsanchez.com>
8: */
9:
10: namespace rsanchez\Deep\Model;
11:
12: use Illuminate\Database\Eloquent\Builder;
13: use Illuminate\Database\Eloquent\ScopeInterface;
14:
15: /**
16: * Global Joinable scope to automatically join the specified tables
17: */
18: class JoinableScope implements ScopeInterface
19: {
20: /**
21: * List of Join objects created
22: * @var array
23: */
24: protected $joins = [];
25:
26: /**
27: * Join the default join tables
28: *
29: * @param \Illuminate\Database\Eloquent\Builder $builder
30: * @return void
31: */
32: public function apply(Builder $builder)
33: {
34: $model = $builder->getModel();
35:
36: foreach ($model->defaultJoinTables() as $table) {
37: $model->requireTable($builder, $table);
38: $this->joins[] = end($builder->getQuery()->joins);
39: }
40: }
41:
42: /**
43: * Unjoin the tables
44: *
45: * @param \Illuminate\Database\Eloquent\Builder $builder
46: * @return void
47: */
48: public function remove(Builder $builder)
49: {
50: foreach ($this->joins as $join) {
51: $index = array_search($join, $builder->getQuery()->joins, true);
52:
53: if ($index !== false) {
54: unset($builder->getQuery()->joins[$index]);
55: }
56: }
57: }
58: }
59: