Skip to content

Commit

Permalink
make phpstan happy
Browse files Browse the repository at this point in the history
  • Loading branch information
lekoala committed Feb 2, 2024
1 parent 0e15985 commit 5733a85
Show file tree
Hide file tree
Showing 11 changed files with 174 additions and 85 deletions.
114 changes: 82 additions & 32 deletions src/ActionsGridFieldItemRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@
use SilverStripe\ORM\DataObject;
use SilverStripe\Core\Extensible;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\FormField;
use SilverStripe\Control\Director;
use SilverStripe\Forms\FormAction;
use SilverStripe\Admin\LeftAndMain;
use SilverStripe\Forms\HiddenField;
use SilverStripe\ORM\DataExtension;
use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTPRequest;
Expand All @@ -23,7 +25,6 @@
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Forms\GridField\GridFieldDetailForm_ItemRequest;
use SilverStripe\Forms\HiddenField;

/**
* Decorates GridDetailForm_ItemRequest to use new form actions and buttons.
Expand All @@ -36,7 +37,7 @@
*
* @link https://github.com/unclecheese/silverstripe-gridfield-betterbuttons
* @link https://github.com/unclecheese/silverstripe-gridfield-betterbuttons/blob/master/src/Extensions/GridFieldBetterButtonsItemRequest.php
* @property LeftAndMain|GridFieldDetailForm_ItemRequest|ActionsGridFieldItemRequest $owner
* @property LeftAndMain&GridFieldDetailForm_ItemRequest&ActionsGridFieldItemRequest $owner
*/
class ActionsGridFieldItemRequest extends DataExtension
{
Expand Down Expand Up @@ -68,7 +69,7 @@ class ActionsGridFieldItemRequest extends DataExtension
private static $enable_utils_prev_next = false;

/**
* @var array Allowed controller actions
* @var array<string> Allowed controller actions
*/
private static $allowed_actions = [
'doSaveAndClose',
Expand All @@ -79,7 +80,8 @@ class ActionsGridFieldItemRequest extends DataExtension
];

/**
* @return array
* @param FieldList $actions
* @return array<string>
*/
protected function getAvailableActions($actions)
{
Expand Down Expand Up @@ -116,6 +118,8 @@ public function updateEditForm(Form $form)
* GridField_ItemRequest defines its own set of actions so we need to add ours
* We add our custom save&close, save&next and other tweaks
* Actions can be made readonly after this extension point
* @param FieldList $actions
* @return void
*/
public function updateFormActions($actions)
{
Expand Down Expand Up @@ -201,8 +205,10 @@ public function updateFormActions($actions)
protected function processDropUpMenu($actions)
{
// The Drop-up container may already exist
/** @var ?Tab $dropUpContainer */
$dropUpContainer = $actions->fieldByName('ActionMenus.MoreOptions');
foreach ($actions as $action) {
//@phpstan-ignore-next-line
if ($action->hasMethod('getDropUp') && $action->getDropUp()) {
if (!$dropUpContainer) {
$dropUpContainer = $this->createDropUpContainer($actions);
Expand Down Expand Up @@ -271,6 +277,7 @@ public function moveCancelAndDelete(FieldList $actions, DataObject $record)
}
// Set custom title
if ($record->hasMethod('getDeleteButtonTitle')) {
//@phpstan-ignore-next-line
$deleteAction->setTitle($record->getDeleteButtonTitle());
}
}
Expand All @@ -286,6 +293,7 @@ public function moveCancelAndDelete(FieldList $actions, DataObject $record)
}
// Set custom titlte
if ($record->hasMethod('getCancelButtonTitle')) {
//@phpstan-ignore-next-line
$cancelButton->setTitle($record->getCancelButtonTitle());
}
}
Expand All @@ -299,6 +307,7 @@ public function getCustomPreviousRecordID(DataObject $record)
{
// This will overwrite state provided record
if (self::config()->enable_custom_prevnext && $record->hasMethod('PrevRecord')) {
//@phpstan-ignore-next-line
return $record->PrevRecord()->ID ?? 0;
}
return $this->owner->getPreviousRecordID();
Expand All @@ -313,11 +322,28 @@ public function getCustomNextRecordID(DataObject $record)

// This will overwrite state provided record
if (self::config()->enable_custom_prevnext && $record->hasMethod('NextRecord')) {
//@phpstan-ignore-next-line
return $record->NextRecord()->ID ?? 0;
}
return $this->owner->getNextRecordID();
}

/**
* @param FieldList $actions
* @return CompositeField|FieldList
*/
protected function getMajorActions(FieldList $actions)
{
/** @var ?CompositeField $MajorActions */
$MajorActions = $actions->fieldByName('MajorActions');

// If it doesn't exist, push to default group
if (!$MajorActions) {
$MajorActions = $actions;
}
return $MajorActions;
}

/**
* @param FieldList $actions
* @param DataObject $record
Expand All @@ -329,12 +355,7 @@ public function addSaveNextAndPrevious(FieldList $actions, DataObject $record)
return;
}

$MajorActions = $actions->fieldByName('MajorActions');

// If it doesn't exist, push to default group
if (!$MajorActions) {
$MajorActions = $actions;
}
$MajorActions = $this->getMajorActions($actions);

// TODO: state is having a hard time on post
// @link https://github.com/silverstripe/silverstripe-framework/issues/10742
Expand Down Expand Up @@ -384,12 +405,7 @@ public function addSaveAndClose(FieldList $actions, DataObject $record)
return;
}

$MajorActions = $actions->fieldByName('MajorActions');

// If it doesn't exist, push to default group
if (!$MajorActions) {
$MajorActions = $actions;
}
$MajorActions = $this->getMajorActions($actions);

if ($record->ID) {
$label = _t('ActionsGridFieldItemRequest.SAVEANDCLOSE', 'Save and Close');
Expand Down Expand Up @@ -419,13 +435,12 @@ protected function getBtnClassForRecord(DataObject $record)
if ($record->ID) {
return 'btn-outline-primary';
}

return 'btn-primary';
}

/**
* @param $action
* @param $definedActions
* @param string $action
* @param array<FormField>|FieldList $definedActions
* @return mixed|CompositeField|null
*/
protected static function findAction($action, $definedActions)
Expand All @@ -443,6 +458,7 @@ protected static function findAction($action, $definedActions)
$definedActionName = $definedAction->getName();

if ($definedAction->hasMethod('actionName')) {
//@phpstan-ignore-next-line
$definedActionName = $definedAction->actionName();
}
if ($definedActionName === $action) {
Expand All @@ -460,7 +476,7 @@ protected static function findAction($action, $definedActions)
* Action must be declared in getCMSActions to be called
*
* @param string $action
* @param array $data
* @param array<string,mixed> $data
* @param Form $form
* @return HTTPResponse|DBHTMLText|string
* @throws HTTPResponse_Exception
Expand All @@ -480,6 +496,7 @@ protected function forwardActionToRecord($action, $data = [], $form = null)
} elseif (!empty($data['ClassName']) && !empty($data['ID'])) {
$record = DataObject::get_by_id($data['ClassName'], $data['ID']);
} elseif ($controller->hasMethod("getRecord")) {
//@phpstan-ignore-next-line
$record = $controller->getRecord();
}

Expand Down Expand Up @@ -533,6 +550,7 @@ protected function forwardActionToRecord($action, $data = [], $form = null)
$message = $result;
}
} catch (Exception $ex) {
$result = null;
$error = true;
$message = $ex->getMessage();
}
Expand All @@ -551,11 +569,16 @@ protected function forwardActionToRecord($action, $data = [], $form = null)
}

// Progressive actions return array with json data
//@phpstan-ignore-next-line
if (method_exists($clickedAction, 'getProgressive') && $clickedAction->getProgressive()) {
$response = $controller->getResponse();
$response->addHeader('Content-Type', 'application/json');
if ($result) {
$response->setBody(json_encode($result));
$encodedResult = json_encode($result);
if (!$encodedResult) {
$encodedResult = json_last_error_msg();
}
$response->setBody($encodedResult);
}

return $response;
Expand All @@ -572,6 +595,7 @@ protected function forwardActionToRecord($action, $data = [], $form = null)

if (Director::is_ajax()) {
$controller->getResponse()->addHeader('X-Status', rawurlencode($message));
//@phpstan-ignore-next-line
if (method_exists($clickedAction, 'getShouldRefresh') && $clickedAction->getShouldRefresh()) {
$controller->getResponse()->addHeader('X-Reload', "true");
}
Expand All @@ -582,15 +606,18 @@ protected function forwardActionToRecord($action, $data = [], $form = null)
} else {
// If the controller support sessionMessage, use it instead of form
if ($controller->hasMethod('sessionMessage')) {
//@phpstan-ignore-next-line
$controller->sessionMessage($message, $status, ValidationResult::CAST_HTML);
} else {
$form->sessionMessage($message, $status, ValidationResult::CAST_HTML);
}
}

// Custom redirect
//@phpstan-ignore-next-line
if (method_exists($clickedAction, 'getRedirectURL') && $clickedAction->getRedirectURL()) {
$controller->getResponse()->addHeader('X-Reload', "true"); // we probably need a full ui refresh
//@phpstan-ignore-next-line
return $controller->redirect($clickedAction->getRedirectURL());
}

Expand Down Expand Up @@ -628,23 +655,23 @@ public function doCustomLink(HTTPRequest $request)
* [doTestAction] => 1
* )
*
* @param array $data The form data
* @param array<string,mixed> $data The form data
* @param Form $form The form object
* @return HTTPResponse|DBHTMLText|string
* @throws Exception
*/
public function doCustomAction($data, $form)
{
$action = key($data['action_doCustomAction']);

return $this->forwardActionToRecord($action, $data, $form);
}

/**
* Saves the form and goes back to list view
*
* @param array $data The form data
* @param array<string,mixed> $data The form data
* @param Form $form The form object
* @return HTTPResponse
*/
public function doSaveAndClose($data, $form)
{
Expand All @@ -666,8 +693,9 @@ public function doSaveAndClose($data, $form)
/**
* Saves the form and goes back to the next item
*
* @param array $data The form data
* @param array<string,mixed> $data The form data
* @param Form $form The form object
* @return HTTPResponse
*/
public function doSaveAndNext($data, $form)
{
Expand All @@ -680,6 +708,10 @@ public function doSaveAndNext($data, $form)
$class = get_class($record);
$getNextRecordID = $data['_cmsactions']['next'][$class] ?? $this->getCustomNextRecordID($record);
$class = get_class($record);
if (!$class) {
throw new Exception("Could not get class");
}
/** @var ?DataObject $next */
$next = $class::get()->byID($getNextRecordID);

$link = $this->owner->getEditLink($getNextRecordID);
Expand All @@ -699,8 +731,9 @@ public function doSaveAndNext($data, $form)
/**
* Saves the form and goes to the previous item
*
* @param array $data The form data
* @param array<string,mixed> $data The form data
* @param Form $form The form object
* @return HTTPResponse
*/
public function doSaveAndPrev($data, $form)
{
Expand All @@ -711,8 +744,13 @@ public function doSaveAndPrev($data, $form)
$controller->getResponse()->addHeader("X-Pjax", "Content");

$class = get_class($record);
$getPreviousRecordID = $data['_cmsactions']['prev'][$class] ?? $this->getPreviousRecordID($record);
$getPreviousRecordID = $data['_cmsactions']['prev'][$class] ?? $this->getCustomPreviousRecordID($record);
$class = get_class($record);
if (!$class) {
throw new Exception("Could not get class");
}

/** @var ?DataObject $prev */
$prev = $class::get()->byID($getPreviousRecordID);

$link = $this->owner->getEditLink($getPreviousRecordID);
Expand All @@ -729,6 +767,11 @@ public function doSaveAndPrev($data, $form)
return $controller->redirect($link);
}

/**
* @param string $url
* @param array<mixed> $data
* @return string
*/
protected function addGridState($url, $data)
{
// This should not be necessary at all if the state is correctly passed along
Expand Down Expand Up @@ -766,6 +809,10 @@ protected function getToplevelController()
return $controller;
}

/**
* @param Controller $controller
* @return boolean
*/
protected function isLeftAndMain($controller)
{
return is_subclass_of($controller, LeftAndMain::class);
Expand All @@ -775,15 +822,14 @@ protected function isLeftAndMain($controller)
* Gets the back link
*
* @return string
* @todo This had to be directly copied from {@link GridFieldDetailForm_ItemRequest}
* because it is a protected method and not visible to a decorator!
*/
public function getBackLink()
{
$backlink = '';
$toplevelController = $this->getToplevelController();
// Check for LeftAndMain and alike controllers with a Backlink or Breadcrumbs methods
if ($toplevelController->hasMethod('Backlink')) {
//@phpstan-ignore-next-line
$backlink = $toplevelController->Backlink();
} elseif ($this->owner->getController()->hasMethod('Breadcrumbs')) {
$parents = $this->owner->getController()->Breadcrumbs(false)->items;
Expand Down Expand Up @@ -827,6 +873,9 @@ protected function redirectAfterAction($isNewRecord, $record = null)
// Changes to the record properties might've excluded the record from
// a filtered list, so return back to the main view if it can't be found
$noActionURL = $url = $controller->getRequest()->getURL();
if (!$url) {
$url = '';
}

// The controller may not have these
if ($controller->hasMethod('getAction')) {
Expand All @@ -840,12 +889,13 @@ protected function redirectAfterAction($isNewRecord, $record = null)
}
} else {
// Simple fallback (last index of)
$pos = strrpos($url ?? '', 'ItemEditForm');
$noActionURL = substr($url ?? '', 0, $pos);
$pos = strrpos($url, 'ItemEditForm');
if (is_int($pos)) {
$noActionURL = substr($url, 0, $pos);
}
}

$controller->getRequest()->addHeader('X-Pjax', 'Content');

return $controller->redirect($noActionURL, 302);
}
}
Loading

0 comments on commit 5733a85

Please sign in to comment.