/** * Remove some file * TODO: Refactor this method * @param $args * @return array * @throws InputError * @throws \Exception */ public function removeFiles($args) { $recordId = RootClass::extractId($args); if (empty($recordId)) { throw new InputError('No ID detected'); } $filesVarStructure = self::findImagesInDataStructure($this->workingClassInstance->getDataStructure()); $previousData = $this->workingClassInstance->get($recordId); $existingFiles = RootClass::selectDataFromStructure($filesVarStructure, $previousData); $getPreviousKey = function ($fieldName, $files) use($existingFiles) { if (isset($existingFiles[$fieldName]) && is_array($existingFiles[$fieldName])) { foreach ($existingFiles[$fieldName] as $key => $previousFiles) { if (isset($previousFiles['full']) && basename($files['full']) === $previousFiles['full']) { return $key; } } } return false; }; foreach ($filesVarStructure as $fieldName => $modelData) { if (isset($args[$fieldName])) { $filesToDelete = $args[$fieldName]; if (!empty($modelData['multiple']) && $modelData['multiple'] === 'true') { if (!is_array($filesToDelete)) { throw new InputError('To delete this files argument should be an array'); } foreach ($filesToDelete as $files) { $previousKey = $getPreviousKey($fieldName, $files); if ($previousKey !== false) { foreach ($files as $path) { $baseName = basename($path); $this->deleteFileFromDisk($baseName); } unset($existingFiles[$fieldName][$previousKey]); $existingFiles[$fieldName] = array_values($existingFiles[$fieldName]); } } } else { if (!is_string($filesToDelete)) { throw new InputError('To delete this file argument should be a string'); } if (!empty($previousData[$fieldName])) { $baseName = basename($existingFiles[$fieldName]); $this->deleteFileFromDisk($baseName); $existingFiles[$fieldName] = null; } } } } return $existingFiles; }
public function saveUploadedFile($recordId) { $filesVarStructure = self::findFilesInDataStructure($this->workingClassInstance->getDataStructure()); $previousData = $this->workingClassInstance->get($recordId); $existingFiles = RootClass::selectDataFromStructure($filesVarStructure, $previousData); return $this->saveUploadedFileOnDisk($existingFiles, $filesVarStructure); }