config = $config; $this->fileManager = $fileManager; $this->helper = $helper; } /** * Set a parameter. */ public function set(string $name, $value) { if (in_array($name, $this->associativeArrayAttributeList) && is_object($value)) { $value = (array) $value; } $this->changedData[$name] = $value; } /** * Set multiple parameters. */ public function setMultiple(array $params) { foreach ($params as $name => $value) { $this->set($name, $value); } } /** * Remove a parameter. */ public function remove(string $name) { $this->removeParamList[] = $name; } /** * Save config changes to the file. */ public function save() { $changedData = $this->changedData; if (!isset($changedData[$this->cacheTimestampParam])) { $changedData[$this->cacheTimestampParam] = $this->generateCacheTimestamp(); } $configPath = $this->config->getConfigPath(); if (!$this->fileManager->isFile($configPath)) { throw new Error("Config file '{$configPath}' was not found."); } $data = $this->fileManager->getPhpContents($configPath); if (!is_array($data)) { $data = $this->fileManager->getPhpContents($configPath); } if (!is_array($data)) { throw new Error("Could not read config."); } foreach ($changedData as $key => $value) { $data[$key] = $value; } foreach ($this->removeParamList as $key) { unset($data[$key]); } if (!is_array($data)) { throw new Error("Invalid config data while saving."); } $data['microtime'] = $microtime = $this->helper->generateMicrotime(); try { $this->fileManager->putPhpContents($configPath, $data); } catch (Exception $e) { throw new Error("Could not save config."); } $reloadedData = $this->fileManager->getPhpContents($configPath); if ( !is_array($reloadedData) || $microtime !== ($reloadedData['microtime'] ?? null) ) { try { $this->fileManager->putPhpContentsNoRenaming($configPath, $data); } catch (Exception $e) { throw new Error("Could not save config."); } } $this->changedData = []; $this->removeParamList = []; $this->config->update(); } /** * Update the cache timestamp. * * @todo Remove? Saving re-writes the cache timestamp anyway. */ public function updateCacheTimestamp() { $this->set($this->cacheTimestampParam, $this->generateCacheTimestamp()); } protected function generateCacheTimestamp() : int { return $this->helper->generateCacheTimestamp(); } }