AdminMethodsDestroy::destroyElement()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 4
eloc 12
c 2
b 1
f 1
nc 5
nop 2
dl 0
loc 17
rs 9.8666
1
<?php
2
3
namespace Larrock\Core\Traits;
4
5
use Lang;
6
use Session;
7
use Redirect;
8
use Larrock\Core\Component;
9
use Illuminate\Http\Request;
10
use Larrock\Core\Events\ComponentItemDestroyed;
11
12
trait AdminMethodsDestroy
13
{
14
    /** @var Component */
15
    protected $config;
16
17
    /**
18
     * Remove the specified resource from storage.
19
     *
20
     * @param Request $request
21
     * @param  int $id
22
     * @return \Illuminate\Http\RedirectResponse
23
     * @throws \Exception
24
     */
25
    public function destroy(Request $request, $id)
26
    {
27
        if ($request->has('ids') && \is_array($request->get('ids'))) {
28
            foreach ($request->get('ids') as $id_item) {
29
                $this->destroyElement($request, $id_item);
30
            }
31
            Session::push('message.success', 'Удалено '.\count($request->get('ids')).' элементов');
32
33
            return back();
34
        }
35
        $this->destroyElement($request, $id);
36
        if ($request->has('category_item')) {
37
            return Redirect::to('/admin/'.$this->config->name.'/'.$request->get('category_item'));
38
        }
39
        if ($request->get('place') === 'material') {
40
            return Redirect::to('/admin/'.$this->config->name);
41
        }
42
43
        return back();
44
    }
45
46
    /**
47
     * Remove id element.
48
     * @param Request $request
49
     * @param $id
50
     * @throws \Exception
51
     */
52
    protected function destroyElement(Request $request, $id)
53
    {
54
        if ($data = $this->config->getModel()::find($id)) {
55
            if (method_exists($data, 'clearMediaCollection')) {
56
                $data->clearMediaCollection();
57
            }
58
            $name = $data->title;
59
60
            if ($data->delete()) {
61
                event(new ComponentItemDestroyed($this->config, $data, $request));
62
                \Cache::flush();
63
                Session::push('message.success', Lang::get('larrock::apps.delete.success', ['name' => $name]));
64
            } else {
65
                Session::push('message.danger', Lang::get('larrock::apps.delete.error', ['name' => $name]));
66
            }
67
        } else {
68
            Session::push('message.danger', 'Такого материала уже не существует');
69
        }
70
    }
71
}
72