Completed
Pull Request — master (#12)
by Matthew
11:11
created

ManageableDataObjectExtension::doSaveObject()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 30
rs 9.3888
c 0
b 0
f 0
cc 5
nc 4
nop 2
1
<?php
2
3
namespace Dynamic\ManageableDataObject\Extensions;
4
5
use Dynamic\CoreTools\Form\CancelFormAction;
0 ignored issues
show
Bug introduced by
The type Dynamic\CoreTools\Form\CancelFormAction was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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 ManageableDataObjectExtension
16
 */
17
class ManageableDataObjectExtension 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
    public function add()
36
    {
37
        $model = $this->owner->config()->get('managed_object');
38
        $object = Injector::inst()->get($model);
39
        if ($object->canCreate(Security::getCurrentUser())) {
40
41
            $form = $this->ManageableDataObjectForm();
42
            if($object->config()->get('add_form_cancel_button')){
43
                $form->Actions()->push(new CancelFormAction($this->owner->Link(), 'Cancel'));
44
            }
45
46
            return $this->owner->customise([
47
                'Title' => ($this->owner->config()->get('add_item_title'))
48
                    ? $this->owner->config()->get('add_item_title')
49
                    : 'Add new ' . $object->singular_name(),
50
                '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
    public function edit()
66
    {
67
        if ($item = $this->getCurrentItem()) {
68
            if ($item->canEdit(Security::getCurrentUser())) {
69
70
                // get Form
71
                $form = $this->ManageableDataObjectForm($item);
72
73
                return $this->owner->customise([
74
                    'Title' => 'Edit ' . $item->singular_name(),
75
                    'ManageableDataObjectForm' => $form,
76
                    '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
    public function delete()
95
    {
96
        if ($item = $this->getCurrentItem()) {
97
            if ($item->canDelete(Security::getCurrentUser())) {
98
                if ($item->hasMethod('softDelete')) {
99
                    $item->softDelete();
100
                } else {
101
                    $item->delete();
102
                }
103
104
                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
        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
    public function ManageableDataObjectForm($object = null)
124
    {
125
        $model = $this->owner->config()->get('managed_object');
126
        $field = ($this->owner->config()->get('query_field'))
127
            ? $this->owner->config()->get('query_field')
128
            : 'ID';
129
        $object = ($object !== null && $object instanceof $model && $object->exists())
130
            ? $object
131
            : Injector::inst()->create($model);
132
133
        $form = ManageableDataObjectForm::create(
134
            $this->owner,
135
            'ManageableDataObjectForm',
136
            $object
137
        );
138
139
        if ($object->exists()) {
140
            $form->Fields()->push(HiddenField::create($field, $object->$field));
141
            $form->loadDataFrom($object);
142
        }
143
144
        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
    public function doSaveObject($data, Form $form)
157
    {
158
		/** @var \SilverStripe\ORM\DataObject $model */
159
        $model = $this->owner->config()->get('managed_object');
160
161
        /** @var \SilverStripe\ORM\DataObject|\Dynamic\ViewableDataObject\Extensions\ViewableDataObject $object */
162
        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
            $object = $model::create();
169
            if ($object->hasDatabaseField('URLSegment')) {
170
                $object->URLSegment = Injector::inst()->create(SiteTree::class)
171
					->generateURLSegment($data['Title']);
172
            }
173
            // write on create to relations are saved on final write (needs ID)
174
            $object->write();
175
        }
176
177
        $form->saveInto($object);
178
179
        $this->owner->extend('updateObjectPreSave', $data, $object, $form);
180
181
        $object->write();
182
183
        $this->owner->extend('updateObjectPostSave', $data, $object, $form);
184
185
        return $this->owner->redirect($object->Link());
186
    }
187
188
189
    /**
190
     * @return bool|\SilverStripe\ORM\DataObject
191
     */
192
    protected function getCurrentItem()
193
    {
194
        if (!$id = $this->owner->request->param('ID')) {
195
            return false;
196
        }
197
198
        /** @var string|\SilverStripe\ORM\DataObject $class */
199
        $class = $this->owner->config()->get('managed_object');
200
        $field = (Injector::inst()->get($class)->config()->get('query_field'))
201
            ? Injector::inst()->get($class)->config()->get('query_field')
202
            : 'ID';
203
204
        if (!$record = $class::get()->filter($field, $id)->first()) {
205
            return false;
206
        }
207
208
        return $record;
209
    }
210
211
}
212