* @copyright Copyright (c) 2023 Samuel Marshall / JCH Optimize * @license GNU/GPLv3, or later. See LICENSE file * * If LICENSE file missing, see . */ namespace JchOptimize\WordPress\Model; use _JchOptimizeVendor\V91\Joomla\Filesystem\File; use _JchOptimizeVendor\V91\Psr\Http\Message\UploadedFileInterface; use Exception; use JchOptimize\Core\Mvc\Model; use JchOptimize\Core\Registry; use JchOptimize\Core\SystemUri\SystemUri; use function array_unique; use function in_array; use function pathinfo; use function strtolower; use function update_option; use const JCH_PLUGIN_DIR; use const PATHINFO_EXTENSION; class BulkSettings extends Model { public function setDefaultSettings(): bool { return update_option('jch-optimize_settings', []); } public function exportSettings(): string { $file = JCH_PLUGIN_DIR . 'tmp/' . SystemUri::currentUri()->getHost() . '_jchoptimize_settings.json'; $params = $this->state->toString(); File::write($file, $params); return $file; } public function importSettings(UploadedFileInterface $uploadedFile): void { $clientFilename = $uploadedFile->getClientFilename(); if ( $clientFilename === null || strtolower(pathinfo($clientFilename, PATHINFO_EXTENSION)) !== 'json' ) { throw new Exception('Only JSON settings files can be imported.'); } $clientMediaType = strtolower((string)$uploadedFile->getClientMediaType()); $allowedMediaTypes = ['application/json', 'application/octet-stream', 'text/json', 'text/plain']; if ($clientMediaType !== '' && !in_array($clientMediaType, $allowedMediaTypes, true)) { throw new Exception('Invalid settings file type.'); } $stream = $uploadedFile->getStream(); $stream->rewind(); $uploadedSettings = (new Registry())->loadString($stream->getContents()); if ($uploadedSettings->get('merge')) { $this->mergeSettings($uploadedSettings); } else { $this->setState($uploadedSettings); update_option('jch-optimize_settings', $uploadedSettings->toArray()); } } private function mergeSettings(Registry $uploadedSettings): void { $uploadedSettings->remove('merge'); foreach ($uploadedSettings as $setting => $value) { if (is_array($value)) { $mergedSetting = array_unique(array_merge($this->state->get($setting, []), $value)); } else { $mergedSetting = $value; } $this->state->set($setting, $mergedSetting); } update_option('jch-optimize_settings', $this->state->toArray()); } }