Completed
Push — master ( 1056fe...110432 )
by Michael
05:27
created

HelperMethodTrait   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 144
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 18
c 5
b 0
f 0
lcom 1
cbo 3
dl 0
loc 144
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getRelationTables() 0 10 1
A parseRelationNames() 0 17 3
A addBackticks() 0 5 2
A toSqlWithBindings() 0 19 3
A columnWithTableName() 0 4 2
A getTableFromColumn() 0 6 2
A getTableWithAlias() 0 8 3
A removeGlobalScope() 0 10 2
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\Relation;
8
9
/**
10
 * Trait HelperMethodTrait
11
 *
12
 * @property array order_fields
13
 * @property array order_defaults
14
 * @property array order_relations
15
 * @property array order_with
16
 * @property array search_fields
17
 * @property string connection
18
 */
19
trait HelperMethodTrait
20
{
21
22
    /**
23
     * Get relation table name and alias
24
     *
25
     * @param Relation $relation
26
     * @return \stdClass
27
     */
28
    protected function getRelationTables($relation)
29
    {
30
        $table = new \stdClass();
31
        $table->name = $relation->getRelated()->getTable();
32
        // if using a 'table' AS 'tableAlias' in a from statement, otherwise alias will be the table name
33
        $from = explode(' ', $relation->getQuery()->getQuery()->from);
34
        $table->alias = array_pop($from);
35
36
        return $table;
37
    }
38
39
    /**
40
     * Get the relations from a relation name
41
     * $relationName can be a single relation
42
     * Usage for User model:
43
     * parseRelationNames('customer') returns [$user->customer()]
44
     * parseRelationNames('customer.contact') returns [$user->customer(), $user->customer->contact()]
45
     *
46
     * @param string $relationName
47
     * @return Relation[]
48
     */
49
    protected function parseRelationNames($relationName)
50
    {
51
        $relationNames = explode('.', $relationName);
52
        $parentRelationName = null;
53
        $relations = [];
54
55
        foreach ($relationNames as $relationName) {
56
            if (is_null($parentRelationName)) {
57
                $relations[] = $this->$relationName();
58
                $parentRelationName = $this->$relationName()->getRelated();
59
            } else {
60
                $relations[] = $parentRelationName->$relationName();
61
            }
62
        }
63
64
        return $relations;
65
    }
66
67
    /**
68
     * Add backticks to a table/column
69
     *
70
     * @param string $column
71
     * @return string
72
     */
73
    protected function addBackticks($column)
74
    {
75
        return preg_match('/^[0-9a-zA-Z\.]*$/', $column) ?
76
            '`' . str_replace(['`', '.'], ['', '`.`'], $column) . '`' : $column;
77
    }
78
79
    /**
80
     * Return the sql for a query with the bindings replaced with the binding values
81
     *
82
     * @param Builder $builder
83
     * @return string
84
     */
85
    protected function toSqlWithBindings(Builder $builder)
86
    {
87
        $replacements = array_map('addslashes', $builder->getBindings());
88
        $sql = $builder->toSql();
89
90
        foreach ($replacements as &$replacement) {
91
            if (!is_numeric($replacement)) {
92
                $replacement = '"' . $replacement . '"';
93
            }
94
        }
95
96
        return preg_replace_callback(
97
            '/(\?)(?=(?:[^\'"]|["\'][^\'"]*["\'])*$)/',
98
            function () use (&$replacements) {
99
                return array_shift($replacements);
100
            },
101
            $sql
102
        );
103
    }
104
105
    /**
106
     * Add table name to column name if table name not already included in column name
107
     *
108
     * @param string $table
109
     * @param string $column
110
     * @return string
111
     */
112
    protected function columnWithTableName($table, $column)
113
    {
114
        return (preg_match('/(' . $table . '\.|`' . $table . '`)/i', $column) > 0 ? '' : $table . '.') . $column;
115
    }
116
117
    /**
118
     * Get table name from column name
119
     *
120
     * @param string $column
121
     * @return string
122
     */
123
    protected function getTableFromColumn($column)
124
    {
125
        $periodPos = strpos($column, '.');
126
127
        return ($periodPos !== false ? substr($column, 0, $periodPos) : $column);
128
    }
129
130
    /**
131
     * Get table name with alias if different to table name
132
     *
133
     * @param \stdClass $table
134
     * @return string
135
     */
136
    protected function getTableWithAlias($table)
137
    {
138
        if ($table->alias !== '' && $table->name !== $table->alias) {
139
            return $table->name . ' AS ' . $table->alias;
140
        } else {
141
            return $table->name;
142
        }
143
    }
144
145
    /**
146
     * Remove a global scope if it exists
147
     *
148
     * @param Builder $query
149
     * @param string $scopeName
150
     * @return Builder
151
     */
152
    protected function removeGlobalScope($query, $scopeName)
153
    {
154
        /** @var Model $this */
155
        $globalScopes = $this->getGlobalScopes();
156
        if (isset($globalScopes[$scopeName])) {
157
            $query->withoutGlobalScope($scopeName);
158
        }
159
160
        return $query;
161
    }
162
}
163