Completed
Push — dev ( 917cb5...992eab )
by Marc
10:46
created

hasMany::addItem()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 28
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 3 Features 0
Metric Value
c 6
b 3
f 0
dl 0
loc 28
rs 8.8571
cc 1
eloc 12
nc 1
nop 1
1
<?php namespace Mascame\Artificer\Fields\Types\Relations;
2
3
use Request;
4
use Route;
5
use Session;
6
7
// Todo: attach somehow the new created items to the a new item (which have not yet been created)
8
9
class hasMany extends Relation
10
{
11
12
    public function boot()
13
    {
14
        parent::boot();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Mascame\Artificer\Fields\Types\Relations\Relation as the method boot() does only exist in the following sub-classes of Mascame\Artificer\Fields\Types\Relations\Relation: Mascame\Artificer\Fields\Types\Relations\hasMany. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
15
        //$this->addWidget(new Chosen());
16
        $this->attributes->add(array('class' => 'chosen'));
0 ignored issues
show
Bug introduced by
The method add cannot be called on $this->attributes (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
17
    }
18
19
    public function input()
20
    {
21
        if (!$this->relation->getRelatedModel()) {
0 ignored issues
show
Bug introduced by
The method getRelatedModel cannot be called on $this->relation (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
22
            throw new \Exception('missing relation in config for the current model.');
23
        }
24
25
        $this->fields = array_get(\View::getShared(), 'fields');
26
        $id = $this->fields['id']->value;
27
28
        $modelName = $this->relation->getRelatedModel();
0 ignored issues
show
Bug introduced by
The method getRelatedModel cannot be called on $this->relation (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
29
        $model = $this->modelObject->schema->models[$modelName];
30
        $model['class'] = $this->modelObject->schema->getClass($modelName);
31
        $this->model = $model;
32
33
        if ((Route::currentRouteName() == 'admin.model.create' || Route::currentRouteName() == 'admin.model.field')
34
            && Session::has('_set_relation_on_create_' . $this->modelObject->name)
35
        ) {
36
            $relateds = Session::get('_set_relation_on_create_' . $this->modelObject->name);
37
38
            $related_ids = array();
39
            foreach ($relateds as $related) {
40
                $related_ids[] = $related['id'];
41
            }
42
43
            $data = $relateds[0]['modelClass']::whereIn('id', $related_ids)->get()->toArray();
44
        } else {
45
            $data = $model['class']::where($this->relation->getForeignKey(), '=', $id)->get(array(
0 ignored issues
show
Bug introduced by
The method getForeignKey cannot be called on $this->relation (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
46
                'id',
47
                $this->relation->getShow()
0 ignored issues
show
Bug introduced by
The method getShow cannot be called on $this->relation (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
48
            ))->toArray();
49
        }
50
51
        $this->showItems($data);
52
53
        $this->createURL = $this->createURL($this->model['route']) . "?" . http_build_query(array(
54
                $this->relation->getForeignKey() => $id,
0 ignored issues
show
Bug introduced by
The method getForeignKey cannot be called on $this->relation (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
55
                '_standalone' => 'true'
56
            ));
57
58
        if (!Request::ajax() || $this->showFullField) {
0 ignored issues
show
Bug introduced by
The property showFullField does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
59
            $this->relationModal($this->model['route'], $id);
60
61
            ?>
62
            <div class="text-right">
63
                <div class="btn-group">
64
                    <button class="btn btn-default" data-toggle="modal"
65
                            data-url="<?= $this->createURL ?>"
66
                            data-target="#form-modal-<?= $this->model['route'] ?>">
67
                        <i class="fa fa-plus"></i>
68
                    </button>
69
                </div>
70
            </div>
71
        <?php
72
        }
73
    }
74
75
    public function showItems($data)
76
    {
77
        if (!Request::ajax()) {
78
79
//			<div data-refresh-field="
80
//			<?= \URL::route('admin.model.field',
81
//				array('slug'  => $this->model['route'],
82
//					  'id'    => ($this->fields['id']->value) ? $this->fields['id']->value : 0,
83
//					  'field' => $this->name))
84
//					  ">
85
86
        }
87
        ?>
88
        <div name="<?= $this->name ?>"><?php
89
        if (!empty($data)) { ?>
90
            <ul class="list-group">
91
                <?php foreach ($data as $item) {
92
                    $this->addItem($item);
93
                } ?>
94
            </ul>
95
        <?php } else { ?>
96
            <div class="well well-sm">No items yet</div>
97
        <?php
98
        }
99
        ?></div><?php
100
101
        if (!Request::ajax()) {
102
            ?>
103
            <!--			</div>-->
104
        <?php
105
        }
106
    }
107
108
    public function addItem($item)
109
    {
110
        $edit_url = $this->editURL($this->model['route'],
111
                $item['id']) . '?' . http_build_query(array('_standalone' => 'true'));
112
        ?>
113
        <li class="list-group-item">
114
            <?= $item[$this->relation->getShow()] ?> &nbsp;
0 ignored issues
show
Bug introduced by
The method getShow cannot be called on $this->relation (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
115
116
			<span class="right">
117
				<span class="btn-group">
118
					<button class="btn btn-default" data-toggle="modal"
119
                            data-url="<?= $edit_url ?>"
120
                            data-target="#form-modal-<?= $this->model['route'] ?>">
121
                        <i class="fa fa-edit"></i>
122
                    </button>
123
124
					<a data-method="delete" data-token="<?= csrf_token() ?>"
125
                       href="<?= route('admin.model.destroy',
126
                           array('slug' => $this->model['route'], 'id' => $item['id']), $absolute = true) ?>"
127
                       type="button" class="btn btn-default">
128
                        <i class="fa fa-remove"></i>
129
                    </a>
130
				</span>
131
			</span>
132
133
        </li>
134
    <?php
135
    }
136
137
    public function show($values = null)
138
    {
139
        $values = ($values) ?: $this->value;
140
141
        if (isset($values) && !$values->isEmpty()) {
142
            $modelName = $this->relation->getRelatedModel();
0 ignored issues
show
Bug introduced by
The method getRelatedModel cannot be called on $this->relation (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
143
            $model = $this->modelObject->schema->models[$modelName];
144
            $show = $this->relation->getShow();
0 ignored issues
show
Bug introduced by
The method getShow cannot be called on $this->relation (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
145
146
            foreach ($values as $value) {
147
                print '<a href="' . $this->editURL($model['route'],
148
                        $value->id) . '" target="_blank">' . $value->$show . "</a><br>";
149
            }
150
        } else {
151
            print "<em>(none)</em>";
152
        }
153
    }
154
155
}