Completed
Push — master ( 6fa307...fa7e27 )
by Corentin
04:31
created

CategoryRepository::getModelName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php namespace App\Repositories;
2
3
use App\Exceptions\RepositoryException;
4
use DB;
5
use Session;
6
7
class CategoryRepository extends Repository
8
{
9
    public function getModelName()
10
    {
11
        return 'App\Models\Categories';
12
    }
13
14
    public function get($id)
15
    {
16
        $this->validateID($id);
17
18
        try {
19
            $category = $this->model->find($id);
20
        } catch (\Exception $e) {
21
            throw new RepositoryException('Could not retrieve category', RepositoryException::DATABASE_ERROR);
22
        }
23
24
        if ($category == NULL) {
25
            throw new RepositoryException('Category not found', RepositoryException::RESOURCE_NOT_FOUND);
26
        }
27
28
        return $category;
29
    }
30
31
    public function store(array $data)
32
    {
33
        if ($this->contains($data['title'])) {
34
            throw new RepositoryException('Category name already exists', RepositoryException::DATABASE_ERROR);
35
        }
36
37
        try {
38
39
            $this->model->create([
40
                'group_id' => session('groupID'),
41
                'category_title' => $data['title'],
42
                'description' => $data['description'],
43
                'is_active' => true
44
            ]);
45
46
        } catch (\Exception $e) {
47
            throw new RepositoryException($e->getMessage(), RepositoryException:: DATABASE_ERROR);
48
        }
49
50
        return DB::getPdo()->lastInsertId();
51
    }
52
53
    public function contains($categoryTitle)
54
    {
55
        $category = $this->model->where('category_title', '=', $categoryTitle)->first();
56
57
        return $category != null;
58
    }
59
60
    public function allWithProducts()
61
    {
62
        $query = 'SELECT p.product_id as "id", p.product_name as "name", c.category_title as "group", p.price
63
					FROM categories c
64
					LEFT JOIN products p ON c.category_id = p.category_id
65
					WHERE p.deleted_at IS NULL
66
					AND c.deleted_at IS NULL
67
					AND c.group_id = ?';
68
69
        return DB::select($query, [Session::get('groupID')]);
70
    }
71
72
    public function allAPI()
73
    {
74
        $query = 'SELECT c.category_id as "id", c.category_title as "title",
75
    				c.description, c.is_active as "active", c.created_at as "created"
76
					FROM categories c
77
					WHERE c.group_id = ?
78
					AND c.deleted_at IS NULL';
79
80
        return DB::select($query, [ Session::get('groupID') ]);
81
    }
82
}