Completed
Push — master ( 6d2ae7...b8f7ff )
by Matthew
02:15
created

ManageableControllerExtension::edit()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.3332

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 3
nop 0
dl 0
loc 22
ccs 8
cts 12
cp 0.6667
crap 3.3332
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
namespace Dynamic\ManageableDataObject\Extensions;
4
5
use Dynamic\AdditionalFormFields\Form\CancelFormAction;
6
use Dynamic\ManageableDataObject\Form\ManageableDataObjectForm;
7
use SilverStripe\CMS\Model\SiteTree;
8
use SilverStripe\Core\Extension;
9
use SilverStripe\Core\Injector\Injector;
10
use SilverStripe\Forms\Form;
11
use SilverStripe\Forms\HiddenField;
12
use SilverStripe\Security\Security;
13
14
/**
15
 * Class ManageableControllerExtension
16
 */
17
class ManageableControllerExtension extends Extension
18
{
19
20
    /**
21
     * @var array
22
     */
23
    private static $allowed_actions = [
24
        'add',
25
        'edit',
26
        'delete',
27
        'ManageableDataObjectForm',
28
    ];
29
30
    /**
31
     * Add object
32
     *
33
     * @return \SilverStripe\Control\HTTPResponse|\SilverStripe\View\ViewableData_Customised
34
     */
35 2
    public function add()
36
    {
37 2
        $model = $this->owner->config()->get('managed_object');
38 2
        $object = Injector::inst()->get($model);
39 2
        if ($object->canCreate(Security::getCurrentUser())) {
40
41 2
            $form = $this->ManageableDataObjectForm();
42 2
            if($object->config()->get('add_form_cancel_button')){
43
                $form->Actions()->push(new CancelFormAction($this->owner->Link(), 'Cancel'));
44
            }
45
46 2
            return $this->owner->customise([
47 2
                'Title' => ($this->owner->config()->get('add_item_title'))
48
                    ? $this->owner->config()->get('add_item_title')
49 2
                    : 'Add new ' . $object->singular_name(),
50 2
                'ManageableDataObjectForm' => $form,
51
            ]);
52
        }
53
54
        return Security::permissionFailure(
55
        	$this->owner,
56
			"You don't have permission to add records."
57
		);
58
    }
59
60
    /**
61
     * Edit object
62
     *
63
     * @return \SilverStripe\Control\HTTPResponse|\SilverStripe\View\ViewableData_Customised
64
     */
65 1
    public function edit()
66
    {
67 1
        if ($item = $this->getCurrentItem()) {
68 1
            if ($item->canEdit(Security::getCurrentUser())) {
69
70
                // get Form
71 1
                $form = $this->ManageableDataObjectForm($item);
72
73 1
                return $this->owner->customise([
74 1
                    'Title' => 'Edit ' . $item->singular_name(),
75 1
                    'ManageableDataObjectForm' => $form,
76 1
                    'Item' => $item,
77
                ]);
78
            }
79
80
            return Security::permissionFailure(
81
            	$this->owner,
82
				"You don't have permission to edit this record."
83
			);
84
        }
85
86
        return $this->owner->httpError(404);
87
    }
88
89
    /**
90
     * Delete Object
91
     *
92
     * @return \SilverStripe\Control\HTTPResponse
93
     */
94 1
    public function delete()
95
    {
96 1
        if ($item = $this->getCurrentItem()) {
97 1
            if ($item->canDelete(Security::getCurrentUser())) {
98 1
                if ($item->hasMethod('softDelete')) {
99
                    $item->softDelete();
100
                } else {
101 1
                    $item->delete();
102
                }
103
104 1
                return $this->owner->redirect($this->owner->Link());
105
            }
106
107
            return Security::permissionFailure(
108
            	$this->owner,
109
				"You don't have permission to delete this record."
110
			);
111
        }
112
113 1
        return $this->owner->httpError(404);
114
    }
115
116
    /**
117
     * Main GridObject Form. Fields loaded via getFrontEndFields method on each Object
118
     *
119
     * @param \SilverStripe\ORM\DataObject $object
120
     *
121
     * @return ManageableDataObjectForm
122
     */
123 3
    public function ManageableDataObjectForm($object = null)
124
    {
125 3
        $model = $this->owner->config()->get('managed_object');
126 3
        $field = ($this->owner->config()->get('query_field'))
127
            ? $this->owner->config()->get('query_field')
128 3
            : 'ID';
129 3
        $object = ($object !== null && $object instanceof $model && $object->exists())
130 1
            ? $object
131 3
            : Injector::inst()->create($model);
132
133 3
        $form = ManageableDataObjectForm::create(
134 3
            $this->owner,
135 3
            'ManageableDataObjectForm',
136 3
            $object
137
        );
138
139 3
        if ($object->exists()) {
140 1
            $form->Fields()->push(HiddenField::create($field, $object->$field));
141 1
            $form->loadDataFrom($object);
142
        }
143
144 3
        return $form;
145
    }
146
147
	/**
148
	 * Save object
149
	 *
150
	 * @param $data
151
	 * @param Form $form
152
	 *
153
	 * @return \SilverStripe\Control\HTTPResponse
154
	 * @throws \SilverStripe\ORM\ValidationException
155
	 */
156 1
    public function doSaveObject($data, Form $form)
157
    {
158
		/** @var \SilverStripe\ORM\DataObject $model */
159 1
        $model = $this->owner->config()->get('managed_object');
160
161
        /** @var \SilverStripe\ORM\DataObject|\Dynamic\ViewableDataObject\Extensions\ViewableDataObject $object */
162 1
        if (isset($data['ID']) && $data['ID']) {
163
            $field = ($this->owner->config()->get('query_field'))
164
                ? $this->owner->config()->get('query_field')
165
                : 'ID';
166
            $object = $model::get()->filter($field, $data['ID'])->first();
167
        } else {
168 1
            $object = $model::create();
169 1
            if ($object->hasDatabaseField('URLSegment')) {
0 ignored issues
show
Bug introduced by
The method hasDatabaseField() does not exist on Dynamic\ViewableDataObje...ions\ViewableDataObject. ( Ignorable by Annotation )

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

169
            if ($object->/** @scrutinizer ignore-call */ hasDatabaseField('URLSegment')) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
170 1
                $object->URLSegment = Injector::inst()->create(SiteTree::class)
171 1
					->generateURLSegment($data['Title']);
172
            }
173
            // write on create to relations are saved on final write (needs ID)
174 1
            $object->write();
0 ignored issues
show
Bug introduced by
The method write() does not exist on Dynamic\ViewableDataObje...ions\ViewableDataObject. ( Ignorable by Annotation )

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

174
            $object->/** @scrutinizer ignore-call */ 
175
                     write();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
175
        }
176
177 1
        $form->saveInto($object);
0 ignored issues
show
Bug introduced by
It seems like $object can also be of type Dynamic\ViewableDataObje...ions\ViewableDataObject; however, parameter $dataObject of SilverStripe\Forms\Form::saveInto() does only seem to accept SilverStripe\ORM\DataObjectInterface, maybe add an additional type check? ( Ignorable by Annotation )

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

177
        $form->saveInto(/** @scrutinizer ignore-type */ $object);
Loading history...
178
179 1
        $this->owner->extend('updateObjectPreSave', $data, $object, $form);
180
181 1
        $object->write();
182
183 1
        $this->owner->extend('updateObjectPostSave', $data, $object, $form);
184
185 1
        return $this->owner->redirect($object->Link());
186
    }
187
188
189
    /**
190
     * @return bool|\SilverStripe\ORM\DataObject
191
     */
192 2
    protected function getCurrentItem()
193
    {
194 2
        if (!$id = $this->owner->request->param('ID')) {
195 1
            return false;
196
        }
197
198
        /** @var string|\SilverStripe\ORM\DataObject $class */
199 2
        $class = $this->owner->config()->get('managed_object');
200 2
        $field = (Injector::inst()->get($class)->config()->get('query_field'))
201
            ? Injector::inst()->get($class)->config()->get('query_field')
202 2
            : 'ID';
203
204 2
        if (!$record = $class::get()->filter($field, $id)->first()) {
205
            return false;
206
        }
207
208 2
        return $record;
209
    }
210
}
211