Passed
Push — master ( b30c75...6d865c )
by Michael
02:36
created

HelperMethodTrait::getTableWithAlias()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace Blasttech\EloquentRelatedPlus;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Relations\BelongsTo;
8
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
9
use Illuminate\Database\Eloquent\Relations\Relation;
10
11
/**
12
 * Trait HelperMethodTrait
13
 *
14
 * @property array order_fields
15
 * @property array order_defaults
16
 * @property array order_relations
17
 * @property array order_with
18
 * @property array search_fields
19
 * @property string connection
20
 */
21
trait HelperMethodTrait
22
{
23
24
    /**
25
     * Get relation table name and alias
26
     *
27
     * @param Relation $relation
28
     * @return \stdClass
29
     */
30
    protected function getRelationTables($relation)
31
    {
32
        $table = new \stdClass();
33
        $table->name = $relation->getRelated()->getTable();
34
        // if using a 'table' AS 'tableAlias' in a from statement, otherwise alias will be the table name
35
        $from = explode(' ', $relation->getQuery()->getQuery()->from);
36
        $table->alias = array_pop($from);
37
38
        return $table;
39
    }
40
41
    /**
42
     * Get the join columns for a relation
43
     *
44
     * @param Relation|BelongsTo|HasOneOrMany $relation
45
     * @return \stdClass
46
     */
47
    protected function getJoinColumns($relation)
48
    {
49
        // Get keys with table names
50
        if ($relation instanceof BelongsTo) {
51
            $first = $relation->getOwnerKey();
52
            $second = $relation->getForeignKey();
53
        } else {
54
            $first = $relation->getQualifiedParentKeyName();
55
            $second = $relation->getQualifiedForeignKeyName();
56
        }
57
58
        return (object)['first' => $first, 'second' => $second];
59
    }
60
61
    /**
62
     * Get the relations from a relation name
63
     * $relationName can be a single relation
64
     * Usage for User model:
65
     * parseRelationNames('customer') returns [$user->customer()]
66
     * parseRelationNames('customer.contact') returns [$user->customer(), $user->customer->contact()]
67
     *
68
     * @param string $relationName
69
     * @return Relation[]
70
     */
71
    protected function parseRelationNames($relationName)
72
    {
73
        $relationNames = explode('.', $relationName);
74
        $parentRelationName = null;
75
        $relations = [];
76
77
        foreach ($relationNames as $relationName) {
78
            if (is_null($parentRelationName)) {
79
                $relations[] = $this->$relationName();
80
                $parentRelationName = $this->$relationName()->getRelated();
81
            } else {
82
                $relations[] = $parentRelationName->$relationName();
83
            }
84
        }
85
86
        return $relations;
87
    }
88
89
    /**
90
     * Add backticks to a table/column
91
     *
92
     * @param string $column
93
     * @return string
94
     */
95
    protected function addBackticks($column)
96
    {
97
        return preg_match('/^[0-9a-zA-Z\.]*$/', $column) ?
98
            '`' . str_replace(['`', '.'], ['', '`.`'], $column) . '`' : $column;
99
    }
100
101
    /**
102
     * Return the sql for a query with the bindings replaced with the binding values
103
     *
104
     * @param Builder $builder
105
     * @return string
106
     */
107
    protected function toSqlWithBindings(Builder $builder)
108
    {
109
        $replacements = array_map('addslashes', $builder->getBindings());
110
        $sql = $builder->toSql();
111
112
        foreach ($replacements as &$replacement) {
113
            if (!is_numeric($replacement)) {
114
                $replacement = '"' . $replacement . '"';
115
            }
116
        }
117
118
        return preg_replace_callback(
119
            '/(\?)(?=(?:[^\'"]|["\'][^\'"]*["\'])*$)/',
120
            function () use (&$replacements) {
121
                return array_shift($replacements);
122
            },
123
            $sql
124
        );
125
    }
126
127
    /**
128
     * Add table name to column name if table name not already included in column name
129
     *
130
     * @param string $table
131
     * @param string $column
132
     * @return string
133
     */
134
    protected function columnWithTableName($table, $column)
135
    {
136
        return (preg_match('/(' . $table . '\.|`' . $table . '`)/i', $column) > 0 ? '' : $table . '.') . $column;
137
    }
138
139
    /**
140
     * Get table name from column name
141
     *
142
     * @param string $column
143
     * @return string
144
     */
145
    protected function getTableFromColumn($column)
146
    {
147
        $periodPos = strpos($column, '.');
148
149
        return ($periodPos !== false ? substr($column, 0, $periodPos) : $column);
150
    }
151
152
    /**
153
     * Get table name with alias if different to table name
154
     *
155
     * @param \stdClass $table
156
     * @return string
157
     */
158
    protected function getTableWithAlias($table)
159
    {
160
        if ($table->alias !== '' && $table->name !== $table->alias) {
161
            return $table->name . ' AS ' . $table->alias;
162
        } else {
163
            return $table->name;
164
        }
165
    }
166
167
    /**
168
     * Remove a global scope if it exists
169
     *
170
     * @param Builder $query
171
     * @param string $scopeName
172
     * @return Builder
173
     */
174
    protected function removeGlobalScope($query, $scopeName)
175
    {
176
        /** @var Model $this */
177
        $globalScopes = $this->getGlobalScopes();
178
        if (isset($globalScopes[$scopeName])) {
179
            $query->withoutGlobalScope($scopeName);
180
        }
181
182
        return $query;
183
    }
184
185
    /**
186
     * Check if relation exists in eager loads
187
     *
188
     * @param Builder $builder
189
     * @param \Illuminate\Database\Eloquent\Relations\Relation $relation
190
     * @return bool
191
     */
192
    protected function isEagerLoaded(Builder $builder, $relation)
193
    {
194
        $eagerLoads = $builder->getEagerLoads();
195
196
        return !is_null($eagerLoads) && in_array($relation, $eagerLoads);
197
    }
198
}
199