<?php
namespace install\library;
/**
 * RequirementsChecker class
 * @author Jérôme Brilland
 * @version 1.0
 * @copyright (c) 2022, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class RequirementsChecker {

    private $requirements = [];
    private $errors = false;
    
    public function getRequirements() {
        if ( empty( $this->requirements ) ) {
            $this->checkRequirements();
        }
        return $this->requirements;
    }
    
    private function checkRequirements() {
        $this->checkPHPVersion();
        $this->checkPDO();
        $this->checkMySQL();
        $this->checkPostgreSQL();
        $this->checkMail();
        $this->checkGD();
        $this->checkImageMagick();
        $this->checkMultibyteString();
        $this->checkConfigFileWritable();
    }

    private function checkPHPVersion() {
        $this->requirements['php_version'] = version_compare( PHP_VERSION, '7.3.0', '>' );
        $this->errors = $this->errors || !$this->requirements['php_version'];
    }

    private function checkPDO() {
        $this->requirements['pdo'] = extension_loaded( 'pdo' );
        $this->errors = $this->errors || !$this->requirements['pdo'];
    }

    private function checkMySQL() {
        $this->requirements['mysql'] = in_array( 'mysql', \PDO::getAvailableDrivers() );
    }

    private function checkPostgreSQL() {
        $this->requirements['pgsql'] = in_array( 'pgsql', \PDO::getAvailableDrivers() );
    }

    private function checkMail() {
        $this->requirements['mail'] = function_exists( 'mail' );
    }

    private function checkGD() {
        $this->requirements['gd'] = extension_loaded( 'gd' );
    }

    private function checkImageMagick() {
        $this->requirements['imagick'] = extension_loaded( 'imagick' );
    }

    private function checkMultibyteString() {
        $this->requirements['mbstring'] = extension_loaded( 'mbstring' );
        $this->errors = $this->errors || !$this->requirements['mbstring'];
    }

    private function checkConfigFileWritable() {
        $this->requirements['config_file_writable'] = is_writable( CONFIG_DIR . 'config.php' );
        $this->errors = $this->errors || !$this->requirements['config_file_writable'];
    }

    public function hasErrors() {
        if ( empty( $this->requirements ) ) {
            $this->checkRequirements();
        }
        return $this->errors || !( $this->requirements['mysql'] || $this->requirements['pgsql'] );
    }
}
