<?php
/**
 * Config provider for the repository config for "transmutation_handler.shortcode_references".
 *
 * @package Ealab\Deployer
 */

namespace EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\Config\TransmutationHandlerShortcodeReferences;

use EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\Config\ConfigProviderBase;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\Config\RepositoryConfigProviderInterface;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\DeployerConfigRepository\DeployerConfig;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\DeployerConfigRepository\InstalledPluginKeyConfigFilter;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\DeployerConfigRepository\InstalledPluginsConfigFilter;

/**
 * Config provider for the repository config for "transmutation_handler.shortcode_references".
 */
class TransmutationHandlerShortcodeReferencesRepositoryConfigProvider extends ConfigProviderBase implements
	RepositoryConfigProviderInterface {

	/**
	 * {@inheritDoc}
	 */
	public function collect(): ?array {
		// Load the repository configuration.
		$repo_config = DeployerConfig::getConfig(
			'transmutation_handler.shortcode_references',
			array(
				// Filter out using the quick filter first.
				InstalledPluginKeyConfigFilter::class,
				// Filter out using the version filter.
				InstalledPluginsConfigFilter::class,
			),
		);

		$this->config = array();

		// Build the final configuration.
		foreach ( $repo_config as $plugin_slug => $items ) {
			// In theory, there should be only a single item per plugin.
			// We simply take the last one.
			$plugin_level_config = end( $items );

			// The real config is nested under the 'value' key.
			$real_config = json_decode( $plugin_level_config['value'], true );

			if ( json_last_error() !== JSON_ERROR_NONE ) {
				// The JSON is invalid. Skip this plugin.
				continue;
			}

			$this->config[ $plugin_slug ] = $real_config;
		}

		return $this->config;
	}
}
