Passed
Push — master ( 2c7a68...f72b76 )
by Dennis
07:59 queued 04:03
created

DynamicQuery::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 2
nc 2
nop 2
1
<?php
2
namespace SimpleCMS\DynamicUnit\Packages;
3
4
use Illuminate\Http\UploadedFile;
5
use Illuminate\Support\Collection;
6
use SimpleCMS\DynamicUnit\Models\DynamicAttribute;
7
use SimpleCMS\DynamicUnit\Models\DynamicUnit as DynamicUnitModel;
8
9
/**
10
 * 操作类
11
 *
12
 * @author Dennis Lui <[email protected]>
13
 */
14
class DynamicQuery
15
{
16
17
    /**
18
     * 删除动作
19
     *
20
     * @author Dennis Lui <[email protected]>
21
     * @param  int $id
22
     * @param  string $type
23
     * @return bool
24
     */
25
    public static function delete(int $id, string $type): bool
26
    {
27
        $model = self::convertModel($type);
28
        if (!$item = $model::find($id)) {
29
            return false;
30
        }
31
        return $item->delete();
32
    }
33
34
    /**
35
     * 添加动作
36
     *
37
     * @author Dennis Lui <[email protected]>
38
     * @param  array $data
39
     * @return bool
40
     */
41
    public static function create(array $data, string $type): bool
42
    {
43
        $model = self::convertModel($type);
44
        list($sql, $file) = self::getFileSql($data, $type);
45
        $item = $model::create($sql);
46
        if ($file) {
47
            $item->addMedia($file)->toMediaCollection($model::MEDIA_FILE);
48
        }
49
        self::addItems($data, $type, $item);
50
        return !empty($item);
51
    }
52
53
    private static function addItems(array $data, string $type = 'attribute', DynamicUnitModel $dynamicUnit): void
54
    {
55
        if ($type == 'unit' && array_key_exists('items', $data) && $data['items']) {
56
            foreach ($data['items'] as $rs) {
57
                self::create(array_merge(['dynamic_unit_id' => $dynamicUnit->id], $rs), 'attribute');
58
            }
59
        }
60
    }
61
62
    private static function getFileSql(array $data, string $type = 'attribute'): array
63
    {
64
        $file = null;
65
        if ($type == 'attribute') {
66
            $sql = self::convertAttributeSql($data);
67
            $file = self::pullFile($data);
68
        } else {
69
            $sql = self::convertUnitSql($data);
70
        }
71
        return [$sql, $file];
72
    }
73
74
    /**
75
     * 修改动作
76
     *
77
     * @author Dennis Lui <[email protected]>
78
     * @param  int $id
79
     * @param  array $data
80
     * @return bool
81
     */
82
    public static function update(int $id, array $data, string $type): bool
83
    {
84
        $model = self::convertModel($type);
85
        if (!$item = $model::find($id)) {
86
            return false;
87
        }
88
        $file = null;
89
        if ($type == 'attribute') {
90
            $sql = self::convertAttributeSql($data);
91
            $file = self::pullFile($data);
92
        } else {
93
            $sql = self::convertUnitSql($data);
94
        }
95
        $item->fill($sql);
96
        if ($result = $item->save()) {
97
            if ($file) {
98
                $item->media && $item->media->each(fn($media) => $media->delete());
99
                $item->addMedia($file)->toMediaCollection($model::MEDIA_FILE);
100
            }
101
        }
102
        if ($type == 'unit' && array_key_exists('items', $data) && $data['items']) {
103
            self::removeUnderId($item, $data['items']);
104
            foreach ($data['items'] as $rs) {
105
                if (array_key_exists('id', $rs) && $rs['id']) {
106
                    self::update((int) $rs['id'], array_merge(['dynamic_unit_id' => $item->id], $rs), 'attribute');
107
                } else {
108
                    self::create(array_merge(['dynamic_unit_id' => $item->id], $rs), 'attribute');
109
                }
110
            }
111
        }
112
        return $result;
113
    }
114
115
    private static function removeUnderId(DynamicUnitModel $item, array $array): void
116
    {
117
        $collection = new Collection($array);
1 ignored issue
show
Bug introduced by
$array of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $items of Illuminate\Support\Collection::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

117
        $collection = new Collection(/** @scrutinizer ignore-type */ $array);
Loading history...
118
        $idList = $collection->filter(fn($n) => isset ($n['id']) && !empty ($n['id']))->values()->pluck('id')->toArray();
119
        if ($idList) {
120
            $item->items()->whereNotIn('id', $idList)->delete();
121
        }
122
    }
123
124
    private static function convertModel(string $type)
125
    {
126
        return $type == 'attribute' ? DynamicAttribute::class : DynamicUnitModel::class;
127
    }
128
129
130
    private static function convertSql(array $data): array|bool
131
    {
132
        $sql = [];
133
        if (array_key_exists('name', $data) && trim($data['name'])) {
134
            $sql['name'] = trim($data['name']);
135
        }
136
        if (array_key_exists('code', $data) && trim($data['code'])) {
137
            $sql['code'] = trim($data['code']);
138
        }
139
        if (!$sql)
140
            return false;
141
        $file = array_key_exists("file", $data) ? $data['file'] : null;
142
        $id = array_key_exists("id", $data) ? $data['id'] : null;
143
        return [$sql, $file, $id];
144
    }
145
146
    private static function pullFile(array $data): null|UploadedFile
147
    {
148
        if (array_key_exists('file', $data) && $data['file']) {
149
            return $data['file'] instanceof UploadedFile ? $data['file'] : null;
150
        }
151
        return null;
152
    }
153
154
    private static function convertAttributeSql(array $data): array
155
    {
156
        $sql = array_merge([
157
            'dynamic_unit_id' => 0,
158
            'name' => null,
159
            'code' => null
160
        ], $data);
161
        $collection = new Collection($sql);
1 ignored issue
show
Bug introduced by
$sql of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $items of Illuminate\Support\Collection::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

161
        $collection = new Collection(/** @scrutinizer ignore-type */ $sql);
Loading history...
162
        return $collection->only(['dynamic_unit_id', 'name', 'code'])->toArray();
163
    }
164
165
    private static function convertUnitSql(array $data): array
166
    {
167
        $sql = array_merge([
168
            'name' => null,
169
            'code' => null
170
        ], $data);
171
        $collection = new Collection($sql);
1 ignored issue
show
Bug introduced by
$sql of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $items of Illuminate\Support\Collection::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

171
        $collection = new Collection(/** @scrutinizer ignore-type */ $sql);
Loading history...
172
        return $collection->only(['name', 'code'])->toArray();
173
    }
174
}