• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

RonasIT / laravel-helpers / 10508933565

22 Aug 2024 01:20PM UTC coverage: 77.706% (-0.2%) from 77.868%
10508933565

push

github

web-flow
Merge pull request #139 from RonasIT/feat/update-dependencies

Update dependencies

9 of 16 new or added lines in 8 files covered. (56.25%)

1 existing line in 1 file now uncovered.

962 of 1238 relevant lines covered (77.71%)

11.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

69.57
/src/Traits/ModelTrait.php
1
<?php
2

3
namespace RonasIT\Support\Traits;
4

5
use Illuminate\Support\Facades\Schema;
6
use Illuminate\Support\Str;
7
use BadMethodCallException;
8
use Illuminate\Support\Arr;
9
use Illuminate\Database\Eloquent\Relations\Relation;
10

11
trait ModelTrait
12
{
13
    protected bool $disableLazyLoading = true;
14

15
    public static function getFields(): array
16
    {
17
        $model = (new static());
21✔
18

19
        $keyName = $model->getKeyName();
21✔
20
        $guarded = $model->getGuarded();
21✔
21
        $fillable = $model->getFillable();
21✔
22
        $timeStamps = ($model->timestamps) ? ['created_at', 'updated_at'] : [];
21✔
23

24
        array_unshift($fillable, $keyName);
21✔
25

26
        return array_merge($fillable, $guarded, $timeStamps);
21✔
27
    }
28

29
    public function getAllFieldsWithTable(): array
30
    {
31
        $tableName = $this->getTable();
×
32
        $fields = Schema::getColumnListing($tableName);
×
33

34
        return array_map(function ($field) use ($tableName) {
×
35
            return "{$tableName}.{$field}";
×
36
        }, $fields);
×
37
    }
38

39
    protected function getRelationshipFromMethod($method)
40
    {
41
        if ($this->disableLazyLoading) {
×
42
            $modelName = static::class;
×
43

44
            throw new BadMethodCallException(
×
45
                "Attempting to lazy-load relation '{$method}' on model '{$modelName}'. "
×
46
                . 'See property $disableLazyLoading.'
×
47
            );
×
48
        }
49

50
        return parent::getRelationshipFromMethod($method);
×
51
    }
52

53
    /**
54
     * This method was added, because native Laravel's method addSelect
55
     * overwrites existed select clause
56
     * @param $query
57
     * @param array $fields
58
     *
59
     * @return mixed
60
     */
61
    public function scopeAddFieldsToSelect($query, array $fields = [])
62
    {
63
        if (is_null($query->getQuery()->columns)) {
1✔
64
            $query->addSelect("{$this->getTable()}.*");
1✔
65
        }
66

67
        if (empty($fields)) {
1✔
68
            return $query;
1✔
69
        }
70

71
        return $query->addSelect($fields);
×
72
    }
73

74
    /**
75
     * Add orderBy By related field,
76
     * $manyToManyStrategy is affect oneToMany and ManyToMany Relations make orderBy('id', ASC/DESC)
77
     *
78
     * @param $query
79
     * @param $relations
80
     * @param string $desc
81
     * @param string|null $asField
82
     * @param string $manyToManyStrategy
83
     *
84
     * @return mixed $query
85
     */
86
    public function scopeOrderByRelated(
87
        $query,
88
        $relations,
89
        string $desc = 'DESC',
90
        ?string $asField = null,
91
        string $manyToManyStrategy = 'max'
92
    ) {
93
        if (empty($asField)) {
1✔
94
            $asField = str_replace('.', '_', $relations);
1✔
95
        }
96

97
        $relations = $this->prepareRelations($relations);
1✔
98
        $orderField = $this->getOrderedField($relations);
1✔
99

100
        if (!empty($relations)) {
1✔
101
            $queries = $this->getQueriesList($query, $relations);
1✔
102
            $prevQuery = array_shift($queries);
1✔
103
            array_pop($queries);
1✔
104

105
            $this
1✔
106
                ->applyManyToManyStrategy($prevQuery, $manyToManyStrategy)
1✔
107
                ->select($orderField);
1✔
108

109
            foreach ($queries as $queryInCollection) {
1✔
110
                $prevQuery = $this
×
111
                    ->applyManyToManyStrategy($queryInCollection, $manyToManyStrategy)
×
112
                    ->selectSub($prevQuery, $asField);
×
113
            }
114

115
            $query->addFieldsToSelect();
1✔
116
            $query->selectSub($prevQuery, $asField);
1✔
117
        }
118

119
        return $query->orderBy($asField ?? $orderField, $desc);
1✔
120
    }
121

122
    protected function getRelationWithoutConstraints($query, $relation)
123
    {
124
        return Relation::noConstraints(function () use ($query, $relation) {
1✔
125
            return $query->getModel()->{$relation}();
1✔
126
        });
1✔
127
    }
128

129
    protected function prepareRelations(string $relations): array
130
    {
131
        if (Str::contains($relations, '.')) {
1✔
132
            return explode('.', $relations);
1✔
133
        } else {
134
            return [
×
NEW
135
                $relations,
×
136
            ];
×
137
        }
138
    }
139

140
    protected function getOrderedField(&$relations): string
141
    {
142
        if (is_array($relations)) {
1✔
143
            return array_pop($relations);
1✔
144
        }
145

146
        return $relations;
×
147
    }
148

149
    protected function getQueriesList($query, array $relations): array
150
    {
151
        $requiredColumns = [];
1✔
152
        $queryCollection = [$query];
1✔
153

154
        foreach ($relations as $relationString) {
1✔
155
            $query = Arr::last($queryCollection);
1✔
156

157
            $relation = $this->getRelationWithoutConstraints($query, $relationString);
1✔
158
            $subQuery = $relation->getRelationExistenceQuery(
1✔
159
                $relation->getQuery(),
1✔
160
                $query,
1✔
161
                $requiredColumns
1✔
162
            );
1✔
163

164
            $queryCollection[] = $subQuery;
1✔
165
        }
166

167
        return array_reverse($queryCollection);
1✔
168
    }
169

170
    protected function applyManyToManyStrategy($query, string $strategy)
171
    {
172
        if ($strategy === 'max') {
1✔
173
            $query->orderBy('id', 'ASC')->limit(1);
1✔
174
        } else {
175
            $query->orderBy('id', 'DESC')->limit(1);
×
176
        }
177

178
        return $query;
1✔
179
    }
180
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc