diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..66e6675 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,8 @@ +{ + "image":"mcr.microsoft.com/vscode/devcontainers/base:ubuntu", + "features": { + "ghcr.io/shyim/devcontainers-features/php:0": { + "extensionsExtra": "intl mysqli mbstring" + } + } +} diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..0d5d7c8 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,32 @@ + + + CodeSniffer ruleset for SilverStripe coding conventions. + + src + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/DropzoneFile.php b/src/DropzoneFile.php index 8eb98fd..3086c94 100644 --- a/src/DropzoneFile.php +++ b/src/DropzoneFile.php @@ -41,32 +41,33 @@ public function IsImage() */ public function getPreviewThumbnail($w = null, $h = null) { - if(!$w) { $w = $this->owner->config()->grid_thumbnail_width; + if (!$w) { + $w = $this->owner->config()->grid_thumbnail_width; } - if(!$h) { $h = $this->owner->config()->grid_thumbnail_height; + if (!$h) { + $h = $this->owner->config()->grid_thumbnail_height; } - if($this->IsImage() && Director::fileExists($this->owner->Filename)) { + if ($this->IsImage() && Director::fileExists($this->owner->Filename)) { return $this->owner->CroppedImage($w, $h); } - $sizes = Config::inst()->forClass(FileAttachmentField::class)->icon_sizes; + $sizes = Config::forClass(FileAttachmentField::class)->icon_sizes; sort($sizes); - foreach($sizes as $size) { - if($w <= $size) { - if($this->owner instanceof Folder) { + foreach ($sizes as $size) { + if ($w <= $size) { + if ($this->owner instanceof Folder) { $file = $this->getFilenameForType('_folder', $size); - } - else { + } else { $file = $this->getFilenameForType($this->owner->getExtension(), $size); } - if(!file_exists(BASE_PATH.'/'.$file)) { + if (!file_exists(BASE_PATH . '/' . $file)) { $file = $this->getFilenameForType('_blank', $size); } $image = Image::create(); - $image->setFromLocalFile(Director::getAbsFile($file), basename($file)); + $image->setFromLocalFile(Director::getAbsFile($file), basename($file ?? '')); return $image; } @@ -86,7 +87,7 @@ protected function getFilenameForType($ext, $size) return ModuleResourceLoader::singleton()->resolveURL(sprintf( 'unclecheese/dropzone:images/file-icons/%spx/%s.png', $size, - strtolower($ext) + strtolower($ext ?? '') )); } -} \ No newline at end of file +} diff --git a/src/FileAttachmentField.php b/src/FileAttachmentField.php index ddea293..cd73edc 100644 --- a/src/FileAttachmentField.php +++ b/src/FileAttachmentField.php @@ -2,6 +2,7 @@ namespace UncleCheese\Dropzone; +use Exception; use SilverStripe\Core\Manifest\ModuleLoader; use SilverStripe\Core\Manifest\ModuleManifest; use SilverStripe\Core\Manifest\ModuleResourceLoader; @@ -39,15 +40,15 @@ class FileAttachmentField extends FileField * * @var array */ - private static $allowed_actions = array ( + private static $allowed_actions = [ 'upload', 'handleSelect', - ); + ]; - private static $url_handlers = array ( + private static $url_handlers = [ 'select' => 'handleSelect', - ); + ]; /** * Track files that are uploaded and remove the tracked files when @@ -130,9 +131,11 @@ class FileAttachmentField extends FileField public static function camelise($str) { return preg_replace_callback( - '/_([a-z])/', function ($c) { + '/_([a-z])/', + function ($c) { return strtoupper($c[1]); - }, $str + }, + $str ?? '' ); } @@ -144,12 +147,17 @@ public static function camelise($str) */ public static function underscorise($str) { + if (!is_string($str)) { + return ''; + } $str[0] = strtolower($str[0]); return preg_replace_callback( - '/([A-Z])/', function ($c) { + '/([A-Z])/', + function ($c) { return "_" . strtolower($c[1]); - }, $str + }, + $str ); } @@ -162,10 +170,10 @@ public static function underscorise($str) public static function get_filesize_from_ini() { $bytes = min( - array( - File::ini2bytes(ini_get('post_max_size') ?: '8M'), - File::ini2bytes(ini_get('upload_max_filesize') ?: '2M') - ) + [ + Convert::memstring2bytes(ini_get('post_max_size') ?: '8M'), + Convert::memstring2bytes(ini_get('upload_max_filesize') ?: '2M') + ] ); return floor($bytes/(1024*1024)); @@ -205,7 +213,7 @@ public function __construct($name, $title = null, $value = null, $form = null) * @param array $attributes * @return SSViewer */ - public function FieldHolder($attributes = array ()) + public function FieldHolder($attributes = []) { $this->defineFieldHolderRequirements(); return parent::FieldHolder($attributes); @@ -218,7 +226,7 @@ public function FieldHolder($attributes = array ()) * @param array $attributes * @return SSViewer */ - public function SmallFieldHolder($attributes = array ()) + public function SmallFieldHolder($attributes = []) { $this->defineFieldHolderRequirements(); return parent::SmallFieldHolder($attributes); @@ -231,16 +239,16 @@ protected function defineFieldHolderRequirements() { Requirements::javascript('unclecheese/dropzone:javascript/dropzone.js'); Requirements::javascript('unclecheese/dropzone:javascript/file_attachment_field.js'); - if($this->isCMS()) { + if ($this->isCMS()) { Requirements::javascript('unclecheese/dropzone:javascript/file_attachment_field_backend.js'); } Requirements::css('unclecheese/dropzone:css/file_attachment_field.css'); - if(!$this->getSetting('url')) { + if (!$this->getSetting('url')) { $this->settings['url'] = $this->Link('upload'); } - if(!$this->getSetting('maxFilesize')) { + if (!$this->getSetting('maxFilesize')) { $this->settings['maxFilesize'] = static::get_filesize_from_ini(); } // The user may not have opted into a multiple upload. If the form field @@ -248,8 +256,8 @@ protected function defineFieldHolderRequirements() $this->settings['uploadMultiple'] = $this->IsMultiple(); // Auto filter images if assigned to an Image relation - if($class = $this->getFileClass()) { - if(Injector::inst()->get($class) instanceof Image) { + if ($class = $this->getFileClass()) { + if (Injector::inst()->get($class) instanceof Image) { $this->imagesOnly(); } } @@ -264,26 +272,28 @@ protected function defineFieldHolderRequirements() public function saveInto(DataObjectInterface $record) { $fieldname = $this->getName(); - if(!$fieldname) { return $this; + if (!$fieldname) { + return $this; } // Handle deletions. This is a bit of a hack. A workaround for having a single form field // post two params. - $deletions = Controller::curr()->getRequest()->postVar('__deletion__'.$this->getName()); + $deletions = Controller::curr()->getRequest()->postVar('__deletion__' . $this->getName()); if ($deletions && is_array($deletions)) { - foreach($deletions as $id) { + foreach ($deletions as $id) { $this->deleteFileByID($id); } } + /** @var DataObject $record */ $ones = $record->hasOne(); - if(($relation = $this->getRelation($record))) { + if (($relation = $this->getRelation($record))) { $relation->setByIDList($this->Value()); - } else if(isset($ones[$fieldname])) { + } elseif (isset($ones[$fieldname])) { $record->{"{$fieldname}ID"} = $this->Value() ?: 0; - } elseif($record->hasField($fieldname)) { + } elseif ($record->hasField($fieldname)) { $record->$fieldname = is_array($this->Value()) ? implode(',', $this->Value()) : $this->Value(); } @@ -371,7 +381,7 @@ public function setMaxFilesize($num) $this->settings['maxFilesize'] = $num; $validator = $this->getValidator(); if ($validator) { - $validator->setAllowedMaxFileSize($num.'m'); + $validator->setAllowedMaxFileSize($num . 'm'); } return $this; } @@ -452,7 +462,7 @@ public function addValidFileIDs(array $ids) $validIDs = $session->get('FileAttachmentField.validFileIDs'); if (!$validIDs) { - $validIDs = array(); + $validIDs = []; } foreach ($ids as $id) { $validIDs[$id] = $id; @@ -511,7 +521,7 @@ public function validate($validator) "validation" ); $result = false; - } else if ($value && is_array($value)) { + } elseif ($value && is_array($value)) { // Prevent a malicious user from inspecting element and changing // one of the fields to use an invalid File ID. $validIDs = $this->getValidFileIDs(); @@ -524,7 +534,7 @@ public function validate($validator) _t( 'FileAttachmentField.VALIDATION', 'Invalid file ID sent %s.', - array('id' => $id) + ['id' => $id] ), "validation" ); @@ -542,26 +552,26 @@ public function validate($validator) * @param array|DataObject $data * @return $this */ - public function setValue($val, $data = array()) + public function setValue($val, $data = []) { if (!$val && $data && $data instanceof DataObject && $data->exists()) { // NOTE: This stops validation errors from occuring when editing // an already saved DataObject. $fieldName = $this->getName(); - $ids = array(); + $ids = []; if ($data->getSchema()->hasOneComponent(get_class($data), $fieldName)) { - $id = $data->{$fieldName.'ID'}; + $id = $data->{$fieldName . 'ID'}; if ($id) { - $ids[] = $id; + $ids[] = $id; } - } else if ($data->getSchema()->hasManyComponent(get_class($data), $fieldName) || $data->getSchema()->manyManyComponent(get_class($data), $fieldName)) { + } elseif ($data->getSchema()->hasManyComponent(get_class($data), $fieldName) || $data->getSchema()->manyManyComponent(get_class($data), $fieldName)) { $files = $data->{$fieldName}(); if ($files) { foreach ($files as $file) { if (!$file->exists()) { continue; } - $ids[] = $file->ID; + $ids[] = $file->ID; } } } @@ -630,7 +640,7 @@ public function setThumbnailHeight($num) */ public function setView($view) { - if(!in_array($view, array ('grid','list'))) { + if (!in_array($view, ['grid','list'])) { throw new Exception("FileAttachmentField::setView - View must be one of 'grid' or 'list'"); } @@ -669,12 +679,12 @@ public function setClickable($val) * @param array $files * @return FileAttachmentField */ - public function setAcceptedFiles($files = array ()) + public function setAcceptedFiles($files = []) { - if(is_array($files)) { + if (is_array($files)) { $files = implode(',', $files); } - $files = str_replace(' ', '', $files); + $files = str_replace(' ', '', $files ?? ''); $this->settings['acceptedFiles'] = $files; // Update validator @@ -682,7 +692,7 @@ public function setAcceptedFiles($files = array ()) if ($validator) { $fileExts = explode(',', $files); - $validatorExts = array(); + $validatorExts = []; foreach ($fileExts as $fileExt) { if ($fileExt && isset($fileExt[0]) && $fileExt[0] === '.') { $fileExt = substr($fileExt, 1); @@ -702,7 +712,7 @@ public function setAcceptedFiles($files = array ()) */ public function imagesOnly() { - $this->setAcceptedFiles(array('.png','.gif','.jpeg','.jpg')); + $this->setAcceptedFiles(['.png','.gif','.jpeg','.jpg']); return $this; } @@ -713,9 +723,9 @@ public function imagesOnly() * @param array $types * @return FileAttachmentField */ - public function setAcceptedMimeTypes($types = array ()) + public function setAcceptedMimeTypes($types = []) { - if(is_array($types)) { + if (is_array($types)) { $types = implode(',', $types); } $this->settings['acceptedMimeTypes'] = $types; @@ -809,8 +819,8 @@ public function addParam($key, $val) */ public function setPermissions($perms) { - foreach($perms as $perm => $val) { - if(!isset($this->permissions[$perm])) { + foreach ($perms as $perm => $val) { + if (!isset($this->permissions[$perm])) { throw new Exception("FileAttachmentField::setPermissions - Permission $perm is not allowed"); } $this->permissions[$perm] = $val; @@ -830,9 +840,9 @@ public function setPermissions($perms) public function setPermission($perm, $val) { return $this->setPermissions( - array( + [ $perm => $val - ) + ] ); } @@ -862,7 +872,7 @@ public function isCMS() { return Controller::curr() instanceof LeftAndMain; } - + /** * @note these are user-friendlier versions of internal PHP errors reported back in the ['error'] value of an upload * @return string @@ -870,29 +880,29 @@ public function isCMS() private function getUploadUserError($code) { $error_message = ""; - switch($code) { - case UPLOAD_ERR_OK: - // no error - 0 + switch ($code) { + case UPLOAD_ERR_OK: + // no error - 0 return ""; - break; - case UPLOAD_ERR_INI_SIZE: - case UPLOAD_ERR_FORM_SIZE: - $error_message = _t('FileAttachmentField.ERRFILESIZE', 'The file is too large, please try again with a smaller version of the file.'); break; - case UPLOAD_ERR_PARTIAL: - $error_message = _t('FileAttachmentField.ERRPARTIALUPLOAD', 'The file was only partially uploaded, did you cancel the upload? Please try again.'); + case UPLOAD_ERR_INI_SIZE: + case UPLOAD_ERR_FORM_SIZE: + $error_message = _t('FileAttachmentField.ERRFILESIZE', 'The file is too large, please try again with a smaller version of the file.'); break; - case UPLOAD_ERR_NO_FILE: - $error_message = _t('FileAttachmentField.ERRNOFILE', 'No file upload was detected.'); + case UPLOAD_ERR_PARTIAL: + $error_message = _t('FileAttachmentField.ERRPARTIALUPLOAD', 'The file was only partially uploaded, did you cancel the upload? Please try again.'); break; - case UPLOAD_ERR_NO_TMP_DIR: - case UPLOAD_ERR_CANT_WRITE: - case UPLOAD_ERR_EXTENSION: - $error_message = _t('FileAttachmentField.ERRSYSTEMFAIL', 'Sorry, the system is not allowing file uploads at this time.'); + case UPLOAD_ERR_NO_FILE: + $error_message = _t('FileAttachmentField.ERRNOFILE', 'No file upload was detected.'); break; - default: - // handles if an extra error value is added at some point as a general error - $error_message = _t('FileAttachmentField.ERRUNKNOWNCODE', 'Sorry, an unknown error has occured. Please try again later.'); + case UPLOAD_ERR_NO_TMP_DIR: + case UPLOAD_ERR_CANT_WRITE: + case UPLOAD_ERR_EXTENSION: + $error_message = _t('FileAttachmentField.ERRSYSTEMFAIL', 'Sorry, the system is not allowing file uploads at this time.'); + break; + default: + // handles if an extra error value is added at some point as a general error + $error_message = _t('FileAttachmentField.ERRUNKNOWNCODE', 'Sorry, an unknown error has occured. Please try again later.'); break; } return $error_message; @@ -914,29 +924,29 @@ private function getUploadUserError($code) */ public function upload(HTTPRequest $request) { - + $name = $this->getSetting('paramName'); - $files = (!empty($_FILES[$name]) ? $_FILES[$name] : array()); - $tmpFiles = array(); + $files = (!empty($_FILES[$name]) ? $_FILES[$name] : []); + $tmpFiles = []; // Checking if field is not supporting uploads - if($this->isDisabled() || $this->isReadonly() || !$this->CanUpload()) { + if ($this->isDisabled() || $this->isReadonly() || !$this->CanUpload()) { $error_message = _t('FileAttachmentField.UPLOADFORBIDDEN', 'Files cannot be uploaded via this form at the current time.'); return $this->httpError(403, $error_message); } - + // No files detected in the upload, this can occur if post_max_size is < the upload size $value = $request->postVar($name); - if(empty($files) || empty($value)) { + if (empty($files) || empty($value)) { $error_message = _t('FileAttachmentField.NOFILESUPLOADED', 'No files were detected in your upload. Please try again later.'); return $this->httpError(400, $error_message); } - + // Security token check, must go after above check as a low post_max_size can scrub the Security Token name from the request $form = $this->getForm(); - if($form) { + if ($form) { $token = $form->getSecurityToken(); - if(!$token->checkRequest($request)) { + if (!$token->checkRequest($request)) { $error_message = _t('FileAttachmentField.BADSECURITYTOKEN', 'Your form session has expired, please reload the form and try again.'); return $this->httpError(400, $error_message); } @@ -944,27 +954,26 @@ public function upload(HTTPRequest $request) // Sort the files out into a list of arrays containing each property // http://php.net/manual/en/features.file-upload.post-method.php - if(!empty($files['tmp_name']) && is_array($files['tmp_name'])) { - for($i = 0; $i < count($files['tmp_name']); $i++) { - $tmpFile = array(); - foreach(array('name', 'type', 'tmp_name', 'error', 'size') as $field) { + if (!empty($files['tmp_name']) && is_array($files['tmp_name'])) { + for ($i = 0; $i < count($files['tmp_name']); $i++) { + $tmpFile = []; + foreach (['name', 'type', 'tmp_name', 'error', 'size'] as $field) { $tmpFile[$field] = $files[$field][$i]; } $tmpFiles[] = $tmpFile; } - } - elseif(!empty($files['tmp_name'])) { + } elseif (!empty($files['tmp_name'])) { $tmpFiles[] = $files; } - $ids = array (); - foreach($tmpFiles as $tmpFile) { - if($tmpFile['error']) { + $ids = []; + foreach ($tmpFiles as $tmpFile) { + if ($tmpFile['error']) { // http://php.net/manual/en/features.file-upload.errors.php $user_message = $this->getUploadUserError($tmpFile['error']); return $this->httpError(400, $user_message); } - if($relationClass = $this->getFileClass($tmpFile['name'])) { + if ($relationClass = $this->getFileClass($tmpFile['name'])) { $fileObject = Injector::inst()->create($relationClass); } @@ -992,7 +1001,7 @@ public function upload(HTTPRequest $request) if (!$formController instanceof LeftAndMain) { $trackFile->setRecord($formController->getRecord()); } - } else if ($formClass !== 'Form') { + } elseif ($formClass !== 'Form') { $trackFile->ControllerClass = $formClass; } else { // If using generic 'Form' instance, get controller @@ -1014,7 +1023,7 @@ public function upload(HTTPRequest $request) */ public function handleSelect(HTTPRequest $request) { - if($this->isDisabled() || $this->isReadonly() || !$this->CanAttach()) { + if ($this->isDisabled() || $this->isReadonly() || !$this->CanAttach()) { return $this->httpError(403); } @@ -1031,17 +1040,16 @@ public function handleSelect(HTTPRequest $request) */ protected function deleteFileByID($id) { - if($this->CanDelete() && $record = $this->getRecord()) { + if ($this->CanDelete() && $record = $this->getRecord()) { $ones = $record->hasOne(); - if($relation = $this->getRelation()) { + if ($relation = $this->getRelation()) { $file = $relation->byID($id); - } - else if(isset($ones[$this->getName()])) { + } elseif (isset($ones[$this->getName()])) { $file = $record->{$this->getName()}(); } - if($file && $file->canDelete()) { + if ($file && $file->canDelete()) { $file->delete(); return true; @@ -1058,20 +1066,20 @@ protected function deleteFileByID($id) */ public function IsMultiple() { - if($this->getSetting('uploadMultiple')) { + if ($this->getSetting('uploadMultiple')) { return true; } - if($record = $this->getRecord()) { + if ($record = $this->getRecord()) { $manyMany = $record->manyMany(); - if(isset($manyMany[$this->getName()])) { + if (isset($manyMany[$this->getName()])) { return true; } $hasMany = $record->hasMany(); - if(isset($hasMany[$this->getName()])) { + if (isset($hasMany[$this->getName()])) { return true; } } @@ -1086,7 +1094,7 @@ public function IsMultiple() */ public function InputName() { - return $this->IsMultiple() ? $this->getName()."[]" : $this->getName(); + return $this->IsMultiple() ? $this->getName() . "[]" : $this->getName(); } /** @@ -1096,26 +1104,25 @@ public function InputName() */ public function AttachedFiles() { - if($record = $this->getRecord()) { - if($record->hasMethod($this->getName())) { + if ($record = $this->getRecord()) { + if ($record->hasMethod($this->getName())) { $result = $record->{$this->getName()}(); - if($result instanceof SS_List) { + if ($result instanceof SS_List) { return $result; - } - else if($result->exists()) { - return ArrayList::create(array($result)); + } elseif ($result->exists()) { + return ArrayList::create([$result]); } } } if ($ids = $this->dataValue()) { - if($ids instanceof ManyManyList) { + if ($ids instanceof ManyManyList) { $ids = array_keys($ids->map()->toArray()); } if (!is_array($ids)) { - $ids = explode(',', $ids); + $ids = explode(',', $ids ?? ''); } $attachments = ArrayList::create(); @@ -1149,16 +1156,18 @@ public function RootThumbnailsDir() */ public function ThumbnailsDir() { - return $this->RootThumbnailsDir().'/'.$this->TemplateThumbnailSize()."px"; + return $this->RootThumbnailsDir() . '/' . $this->TemplateThumbnailSize() . "px"; } public function CSSSize() { $w = $this->getSelectedThumbnailWidth(); - if($w < 150) { return "small"; + if ($w < 150) { + return "small"; } - if($w < 250) { return "medium"; + if ($w < 250) { + return "medium"; } return "large"; @@ -1234,7 +1243,6 @@ public function CanAttach() public function PreviewTemplate($fileID = null) { return $this->renderWith($this->previewTemplate); - } /** @@ -1247,8 +1255,9 @@ public function TemplateThumbnailSize() { $w = $this->getSelectedThumbnailWidth(); - foreach($this->config()->icon_sizes as $size) { - if($w <= $size) { return $size; + foreach ($this->config()->icon_sizes as $size) { + if ($w <= $size) { + return $size; } } } @@ -1273,10 +1282,11 @@ public function AutoProcess() */ protected function checkPerm($perm) { - if(!isset($this->permissions[$perm])) { return false; + if (!isset($this->permissions[$perm])) { + return false; } - if(is_callable($this->permissions[$perm])) { + if (is_callable($this->permissions[$perm])) { return $this->permissions[$perm](); } @@ -1298,22 +1308,23 @@ public function getFileClass($filename = null) $name = $this->getName(); $record = $this->getRecord(); - $ext = pathinfo($filename, PATHINFO_EXTENSION); + $ext = pathinfo($filename ?? '', PATHINFO_EXTENSION); $defaultClass = File::get_class_for_file_extension($ext); - if(empty($name) || empty($record)) { + if (empty($name) || empty($record)) { return $defaultClass; } - if($record) { + if ($record) { $class = $record->getRelationClass($name); - if(!$class) { $class = File::class; + if (!$class) { + $class = File::class; } } - if($filename) { - if($defaultClass == "Image" - && $this->config()->upgrade_images + if ($filename) { + if ($defaultClass == "Image" + && $this->config()->upgrade_images && !Injector::inst()->get($class) instanceof Image ) { $class = Image::class; @@ -1334,16 +1345,15 @@ public function getRecord() $record = $this->form->getRecord(); if ($record && $record instanceof DataObject) { $this->record = $record; - } - else if ($controller = $this->form->getController()) { - if($controller->hasMethod('data') + } elseif ($controller = $this->form->getController()) { + if ($controller->hasMethod('data') && ($record = $controller->data()) && ($record instanceof DataObject) ) { $this->record = $record; - } else if($controller->hasMethod('getRecord')) { - if($controller->hasMethod('currentPageID')) { - if($record = $controller->getRecord($controller->currentPageID())) { + } elseif ($controller->hasMethod('getRecord')) { + if ($controller->hasMethod('currentPageID')) { + if ($record = $controller->getRecord($controller->currentPageID())) { $this->record = $record; } } else { @@ -1359,14 +1369,15 @@ public function getRecord() /** * Gets the name of the relation, if attached to a record * - * @return string + * @return RelationList|UnsavedRelationList|bool */ protected function getRelation($record = null) { - if(!$record) { $record = $this->getRecord(); + if (!$record) { + $record = $this->getRecord(); } - if($record) { + if ($record) { $fieldname = $this->getName(); $relation = $record->hasMethod($fieldname) ? $record->$fieldname() : null; @@ -1386,7 +1397,7 @@ protected function getRelation($record = null) */ protected function getSetting($setting) { - if(isset($this->settings[$setting])) { + if (isset($this->settings[$setting])) { return $this->settings[$setting]; } @@ -1407,11 +1418,11 @@ protected function getDefaults() $file_path = ModuleLoader::inst()->getManifest()->getModule('unclecheese/dropzone') ->getResource($this->config()->default_config_path) ->getPath(); - if(!file_exists($file_path)) { + if (!file_exists($file_path)) { throw new Exception("FileAttachmentField::getDefaults() - There is no config json file at $file_path"); } - return Convert::json2array(file_get_contents($file_path)); + return json_decode(file_get_contents($file_path) ?? '', true); } /** @@ -1421,7 +1432,7 @@ protected function getDefaults() */ public function getSelectedThumbnailWidth() { - if($w = $this->getSetting('thumbnailWidth')) { + if ($w = $this->getSetting('thumbnailWidth')) { return $w; } @@ -1437,7 +1448,7 @@ public function getSelectedThumbnailWidth() */ public function getSelectedThumbnailHeight() { - if($h = $this->getSetting('thumbnailHeight')) { + if ($h = $this->getSetting('thumbnailHeight')) { return $h; } @@ -1456,16 +1467,16 @@ public function getConfigJSON() { $data = $this->settings; $defaults = $this->getDefaults(); - foreach($this->config()->defaults as $setting => $value) { + foreach ($this->config()->defaults as $setting => $value) { $js_name = static::camelise($setting); // If the setting has been set on the instance, use that value - if(isset($data[$js_name])) { + if (isset($data[$js_name])) { continue; } // Only include the setting in the JSON if it differs from the core default value - if(!isset($defaults[$js_name]) || ($defaults[$js_name] !== $value)) { + if (!isset($defaults[$js_name]) || ($defaults[$js_name] !== $value)) { $data[$js_name] = $value; } } @@ -1475,18 +1486,18 @@ public function getConfigJSON() $data['thumbnailWidth'] = $this->getSelectedThumbnailWidth(); $data['thumbnailHeight'] = $this->getSelectedThumbnailHeight(); - if(!$this->IsMultiple()) { + if (!$this->IsMultiple()) { $data['maxFiles'] = 1; } - if($this->isCMS()) { + if ($this->isCMS()) { $data['urlSelectDialog'] = $this->Link('select'); - if($this->getFolderName()) { + if ($this->getFolderName()) { $data['folderID'] = Folder::find_or_make($this->getFolderName())->ID; } } - return Convert::array2json($data); + return json_encode($data); } public function performReadonlyTransformation() diff --git a/src/FileAttachmentFieldCleanTask.php b/src/FileAttachmentFieldCleanTask.php index 801e450..b21e88b 100644 --- a/src/FileAttachmentFieldCleanTask.php +++ b/src/FileAttachmentFieldCleanTask.php @@ -4,6 +4,7 @@ use SilverStripe\Dev\BuildTask; use SilverStripe\ORM\DB; + /** * Delete all files being tracked that weren't saved against anything. * @@ -17,7 +18,7 @@ class FileAttachmentFieldCleanTask extends BuildTask private static $segment = 'dropzone-clean'; protected $title = "File Attachment Field - Clear all tracked files that are older than 1 hour"; - + protected $description = 'Delete files uploaded via FileAttachmentField that aren\'t attached to anything.'; public function run($request) @@ -28,10 +29,10 @@ public function run($request) foreach ($files as $trackRecord) { $file = $trackRecord->File(); if ($file->exists()) { - DB::alteration_message('Remove File #'.$file->ID.' from "'.$trackRecord->ControllerClass.'" on '.$trackRecord->RecordClass.' #'.$trackRecord->RecordID, 'error'); + DB::alteration_message('Remove File #' . $file->ID . ' from "' . $trackRecord->ControllerClass . '" on ' . $trackRecord->RecordClass . ' #' . $trackRecord->RecordID, 'error'); $file->delete(); } else { - DB::alteration_message('Untrack missing File #'.$file->ID.' from "'.$trackRecord->ControllerClass.'" on '.$trackRecord->RecordClass.' #'.$trackRecord->RecordID, 'error'); + DB::alteration_message('Untrack missing File #' . $file->ID . ' from "' . $trackRecord->ControllerClass . '" on ' . $trackRecord->RecordClass . ' #' . $trackRecord->RecordID, 'error'); } $trackRecord->delete(); } diff --git a/src/FileAttachmentFieldTrack.php b/src/FileAttachmentFieldTrack.php index c032e9e..d80168b 100644 --- a/src/FileAttachmentFieldTrack.php +++ b/src/FileAttachmentFieldTrack.php @@ -49,11 +49,11 @@ public function onBeforeWrite() if ($controller->hasMethod('data')) { // Store page visiting on frontend (ContentController) $pageRecord = $controller->data(); - } else if ($controller->hasMethod('currentPageID')) { + } elseif ($controller->hasMethod('currentPageID')) { // Store editing page in CMS (LeftAndMain) $id = $controller->currentPageID(); $pageRecord = $controller->getRecord($id); - } else if ($controller->hasMethod('getRecord')) { + } elseif ($controller->hasMethod('getRecord')) { $pageRecord = $controller->getRecord(); } @@ -74,7 +74,7 @@ public function setRecord($record) public function Record() { if ($this->RecordClass && $this->RecordID) { - return DataObject::get_one($this->RecordClass, "ID = ".(int)$this->RecordID); + return DataObject::get_one($this->RecordClass, "ID = " . (int)$this->RecordID); } } }