Skip to content

Allow for includes to contain parts to be replaced #170

@Idrinth

Description

@Idrinth

While using phpstan extensions(with phpstan using nette's di and loader(@ ^2.4.7||^3.0 )) I noticed that configuring the includes across different environments and relative paths was next to impossible without manually replacing the paths each time. A reference to a specific path not related to the config file's position would have helped out here by prefixing a relative path with a path to the tool used instead of the parent file's directory.

This would allow the loader to be less dependant on always having an identical file system structure, making it easier to use.

The resulting code in Nette\DI\Config\Loader::load() could look similar to the following:

	/**
	 * Reads configuration from file.
	 * @param  string   file name
	 * @param  string   optional section to load
     * @param  string[] replacements to be done in the paths to be included
	 * @return array
	 */
	public function load($file, $section = null, $replacements = [])
	{
		// removed unrelated checks and parsing

		// include child files
		$merged = [];
		if (isset($data[self::INCLUDES_KEY])) {
			Validators::assert($data[self::INCLUDES_KEY], 'list', "section 'includes' in file '$file'");
			foreach ($data[self::INCLUDES_KEY] as $include) {
				foreach ($replacements as $search => $replace) {
					$include = str_replace("%$search%", $replace, $include);
				}
				if (!preg_match('#([a-z]+:)?[/\\\\]#Ai', $include)) {
					$include = dirname($file) . '/' . $include;
				}
				$merged = Helpers::merge($this->load($include, null, $replacements), $merged);
			}
		}
		unset($data[self::INCLUDES_KEY], $this->loadedFiles[$file]);


		return Helpers::merge($data, $merged);
	}

With the initial call (optionally) passing along replacements, for example:

$config = (new Nette\DI\Config\Loader())->load('myconfig.neon', null, ['externals-dir' => '/a/directory/elsewhere']);

I'm willing to implement this feature properly if it's desired.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions