Completed
Push — master ( 2fdc96...4f1f24 )
by Damian
12:09
created

VersionedGridFieldItemRequest::getFormActions()   C

Complexity

Conditions 8
Paths 13

Size

Total Lines 62
Code Lines 36

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 62
rs 6.943
cc 8
eloc 36
nc 13
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Provides versioned dataobject support to {@see GridFieldDetailForm_ItemRequest}
5
 *
6
 * @property GridFieldDetailForm_ItemRequest $owner
7
 */
8
class VersionedGridFieldItemRequest extends GridFieldDetailForm_ItemRequest {
9
10
    protected function getFormActions() {
11
        $actions = parent::getFormActions();
12
13
		// Check if record is versionable
14
		$record = $this->getRecord();
15
        if(!$record || !$record->has_extension('Versioned')) {
16
            return $actions;
17
        }
18
19
        // Save & Publish action
20
		if($record->canPublish()) {
21
			// "publish", as with "save", it supports an alternate state to show when action is needed.
22
			$publish = FormAction::create(
23
                'doPublish',
24
                _t('VersionedGridFieldItemRequest.BUTTONPUBLISH', 'Publish')
25
            )
26
                ->setUseButtonTag(true)
27
                ->addExtraClass('ss-ui-action-constructive')
28
                ->setAttribute('data-icon', 'accept');
29
30
            // Insert after save
31
            if($actions->fieldByName('action_doSave')) {
32
                $actions->insertAfter('action_doSave', $publish);
33
            } else {
34
                $actions->push($publish);
35
            }
36
		}
37
38
        // Unpublish action
39
        $isPublished = $record->isPublished();
40
		if($isPublished && $record->canUnpublish()) {
41
			$actions->push(
42
				FormAction::create(
43
                    'doUnpublish',
44
                    _t('VersionedGridFieldItemRequest.BUTTONUNPUBLISH', 'Unpublish')
45
                )
46
                    ->setUseButtonTag(true)
47
					->setDescription(_t(
48
                        'VersionedGridFieldItemRequest.BUTTONUNPUBLISHDESC',
49
                        'Remove this record from the published site'
50
                    ))
51
					->addExtraClass('ss-ui-action-destructive')
52
			);
53
		}
54
55
        // Archive action
56
		if($record->canArchive()) {
57
            // Replace "delete" action
58
            $actions->removeByName('action_doDelete');
59
60
            // "archive"
61
            $actions->push(
62
                FormAction::create('doArchive', _t('VersionedGridFieldItemRequest.ARCHIVE','Archive'))
63
                    ->setDescription(_t(
64
                        'VersionedGridFieldItemRequest.BUTTONARCHIVEDESC',
65
                        'Unpublish and send to archive'
66
                    ))
67
                    ->addExtraClass('delete ss-ui-action-destructive')
68
            );
69
		}
70
		return $actions;
71
    }
72
73
    /**
74
     * Archive this versioned record
75
     *
76
     * @param array $data
77
     * @param Form $form
78
	 * @return SS_HTTPResponse
79
     */
80
	public function doArchive($data, $form) {
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
81
		$record = $this->getRecord();
82
		if (!$record->canArchive()) {
83
			return $this->httpError(403);
84
		}
85
86
		// Record name before it's deleted
87
		$title = $record->Title;
0 ignored issues
show
Documentation introduced by
The property Title does not exist on object<DataObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
88
89
		try {
90
			$record->doArchive();
91
		} catch(ValidationException $e) {
92
			return $this->generateValidationResponse($form, $e);
93
		}
94
95
		$message = sprintf(
96
			_t('VersionedGridFieldItemRequest.Archived', 'Archived %s %s'),
97
			$record->i18n_singular_name(),
98
			Convert::raw2xml($title)
99
		);
100
		$this->setFormMessage($form, $message);
101
102
		//when an item is deleted, redirect to the parent controller
103
		$controller = $this->getToplevelController();
104
		$controller->getRequest()->addHeader('X-Pjax', 'Content'); // Force a content refresh
105
106
		return $controller->redirect($this->getBacklink(), 302); //redirect back to admin section
107
    }
108
109
    /**
110
     * Publish this versioned record
111
     *
112
     * @param array $data
113
     * @param Form $form
114
	 * @return SS_HTTPResponse
115
     */
116
    public function doPublish($data, $form) {
117
        $record = $this->getRecord();
118
        $isNewRecord = $record->ID == 0;
119
120
		// Check permission
121
		if(!$record->canPublish()) {
122
			return $this->httpError(403);
123
		}
124
125
		// Save from form data
126
		try {
127
            // Initial save and reload
128
			$record = $this->saveFormIntoRecord($data, $form);
129
            $record->doPublish();
130
131
		} catch(ValidationException $e) {
132
			return $this->generateValidationResponse($form, $e);
133
		}
134
135
		$editURL = $this->Link('edit');
136
		$xmlTitle = Convert::raw2xml($record->Title);
137
		$link = "<a href=\"{$editURL}\">{$xmlTitle}</a>";
138
		$message = _t(
139
			'VersionedGridFieldItemRequest.Published',
140
			'Published {name} {link}',
141
			array(
142
				'name' => $record->i18n_singular_name(),
143
				'link' => $link
144
			)
145
		);
146
		$this->setFormMessage($form, $message);
147
148
		return $this->redirectAfterSave($isNewRecord);
149
    }
150
151
    /**
152
     * Delete this record from the live site
153
     *
154
     * @param array $data
155
     * @param Form $form
156
	 * @return SS_HTTPResponse
157
     */
158
    public function doUnpublish($data, $form) {
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
159
		$record = $this->getRecord();
160
		if (!$record->canUnpublish()) {
161
			return $this->httpError(403);
162
		}
163
164
		// Record name before it's deleted
165
		$title = $record->Title;
0 ignored issues
show
Documentation introduced by
The property Title does not exist on object<DataObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
166
167
		try {
168
			$record->doUnpublish();
169
		} catch(ValidationException $e) {
170
			return $this->generateValidationResponse($form, $e);
171
		}
172
173
		$message = sprintf(
174
			_t('VersionedGridFieldItemRequest.Unpublished', 'Unpublished %s %s'),
175
			$record->i18n_singular_name(),
176
			Convert::raw2xml($title)
177
		);
178
		$this->setFormMessage($form, $message);
179
180
		// Redirect back to edit
181
		return $this->redirectAfterSave(false);
182
    }
183
184
	/**
185
	 * @param Form $form
186
	 * @param string $message
187
	 */
188
	protected function setFormMessage($form, $message) {
189
		$form->sessionMessage($message, 'good', false);
190
		$controller = $this->getToplevelController();
191
		if($controller->hasMethod('getEditForm')) {
192
			$backForm = $controller->getEditForm();
193
			$backForm->sessionMessage($message, 'good', false);
194
		}
195
	}
196
}
197