<?php

namespace Inpsyde\EnvironmentChecker;

use Inpsyde\EnvironmentChecker\Constraints\AbstractVersionConstraint;
use Inpsyde\EnvironmentChecker\Constraints\ConstraintInterface;
use Inpsyde\EnvironmentChecker\Exception\ConstraintFailedException;
use Inpsyde\EnvironmentChecker\Exception\ConstraintFailedExceptionInterface;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class EnvironmentChecker implements ConstraintInterface {

    protected $constraintsArray;
    /**
     * @var array<string> List of the error messages if environment is not ok.
     */
    protected $errors;

    /**
     * __construct function.
     *
     * @access public
     *
     * @param AbstractVersionConstraint[] $constraintsArray
     */
	function __construct(array $constraintsArray) {
	   $this->constraintsArray = $constraintsArray;
	   $this->errors = [];
	}

	public function check()
	{
		foreach ($this->constraintsArray as $constraint) {

			assert($constraint instanceof ConstraintInterface);
			try {
				$constraint->check();
			} catch (ConstraintFailedExceptionInterface $e) {
				$this->errors[] = $e;

			}
		}

		$errCount = count($this->errors);
		if ($errCount) {
			throw new ConstraintFailedException(
				$this, // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Constraint instance is stored on the exception, not output.
				esc_html('General Checker'),
				esc_html($this->errors),
				esc_html($this->__('Validation failed with %1$d errors', [$errCount]))
			);
		}
	}

	/**
	 * Translates a string, interpolating params.
	 *
	 * @param string $string The string to translate. Can be a {@see sprintf()} style format.
	 * @param array $params The param values to interpolate into the string.
	 * @return string The translated string with params interpolated.
	 */
	protected function __($string, $params = [])
	{
		return vsprintf($string, $params);
	}
}
