Completed
Push — master ( da6b7c...20aa8d )
by David
02:24
created

Field::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Taskforcedev\CrudApi\Helpers;
4
5
/**
6
 * Class Field.
7
 */
8
class Field
9
{
10
    public $crudApi;
11
12
    /**
13
     * Field constructor.
14
     *
15
     * @param CrudApi $crudApi
16
     */
17
    public function __construct(CrudApi $crudApi)
18
    {
19
        $this->crudApi = $crudApi;
20
    }
21
22
    /**
23
     * Determine if the field is an id field.
24
     *
25
     * @param $field
26
     *
27
     * @return bool
28
     */
29
    public function isIdField($field)
30
    {
31
        return strpos($field, '_id') === false ? false : true;
32
    }
33
34
    /**
35
     * Parse a relation field name into the relation name.
36
     *
37
     * @param string $field Field name
38
     *
39
     * @return string
40
     */
41
    public function getRelatedField($field)
42
    {
43
        $relation = str_replace('_id', '', $field);
44
        return $relation;
45
    }
46
47
    /**
48
     * Retrieve the models primary field for display purposes.
49
     *
50
     * @param            $item   Model to retrieve primary field of.
51
     * @param null|array $config CrudApi Configuration.
52
     *
53
     * @return string
54
     */
55
    public function getPrimaryField($item, $config = null)
56
    {
57
        /* If config is not overridden then load crudapi config */
58
        if ($config === null) {
59
            $config = config('crudapi');
60
        }
61
        if (!isset($config['models']['fields']['default'])) {
62
            $defaultField = 'name';
63
        } else {
64
            $defaultField = $config['models']['fields']['default'];
65
        }
66
67
        /* Get the items Class */
68
        $class = get_class($item);
69
70
        $stripped_class = str_replace($this->crudApi->namespace, '', $class);
71
        // if class starts with a \ remove it.
72
        if (substr($stripped_class, 0, 1) == '\\') {
73
            $stripped_class = substr($stripped_class, 1);
74
        }
75
76
        $primaryFields = $config['models']['fields']['primary'];
77
78
        if (array_key_exists($stripped_class, $primaryFields)) {
79
            return $primaryFields[$stripped_class];
80
        } else {
81
            //return the default
82
            return $defaultField;
83
        }
84
    }
85
}
86