HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/boldt.komma.pro/app/Komma/Kms/QualityAssurance/BaseTestController.php
<?php


namespace App\Komma\Kms\QualityAssurance;

use Illuminate\Support\Facades\DB;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Output\ConsoleOutput;

/**
 * Class BaseTestController
 *
 * Used for building test controllers
 *
 * @package App\Komma|Kms\QualityAssurance
 */
abstract class BaseTestController
{
    /**
     * Folder where the Unit, Feature, test folders and Reports folder is stored
     * @var string $testsFolder
     */
    protected $testsFolder;

    /**
     * Folder where the browser screenshots are stored
     */
    protected $screenshotFolder;

    /**
     * @var string The directory this file resides in relative to the root of this project.
     */
    protected $baseDirectory;

    /** @var ConsoleOutput */
    protected $output;

    /**
     * returns true if the controller can run tests, false if not.
     *
     * @return bool
     */
    abstract protected function canTest();

    public function __construct()
    {
        $formatter = new OutputFormatter(true, self::createAdditionalStyles());
        $this->output = new ConsoleOutput(ConsoleOutput::VERBOSITY_VERY_VERBOSE, true, $formatter);
    }

    /**
     * Shows a console banner
     *
     * @param string $text
     */
    protected function showBanner($text = 'testing')
    {
        $horizontalBorderWidth = 55;
        $horizontalBorderSymbol = '#';
        $verticalBorderSymbol = '#';
        $borderThickness = 1;

        $horizontalBorder = str_repeat($horizontalBorderSymbol, $horizontalBorderWidth);
        $decoratedText = str_repeat($verticalBorderSymbol, $borderThickness).
            str_pad($text, $horizontalBorderWidth - ($borderThickness * 2), ' ', STR_PAD_BOTH).
            str_repeat($verticalBorderSymbol, $borderThickness);

        for($index = 0; $index < $borderThickness; $index++) $this->output->writeln($horizontalBorder);
        $this->output->writeln($decoratedText);
        for($index = 0; $index < $borderThickness; $index++) $this->output->writeln($horizontalBorder);
    }

    /**
     * Makes sure the application is in an predictable state (always the same).
     */
    public function prepareEnvironment() {
        $this->truncateDatabase();
    }

    /**
     * Runs php unit tests
     *
     * @param string $type
     * @return string The path to the php unit executable with filter or group parameters added an
     * optionally with debug parameters added
     */
    public function phpunit($type = 'kms') {
        $this->showBanner('Starting '.$type.' unit tests');

        $phpUnit = 'php -d display_errors=On -d memory_limit=768M '.base_path('vendor/bin/phpunit');

        $parameters = [];
        $parameters['-c'] = $this->baseDirectory.'phpunit.xml';
        $parameters['--bootstrap'] = 'vendor/autoload.php';

        $parameterstring = "";
        foreach($parameters as $key => $parameter) $parameterstring .= " ".$key." ".$parameter;

        $phpUnit = $phpUnit.' --debug '.$parameterstring;

        $this->output->writeln('Running command to test shop: '.$phpUnit);
        exec($phpUnit, $lines);
        $this->output->writeln($lines);
    }

    /**
     * Runs dusk (browser) tests
     * @param string $type
     */
    public function dusk($type = 'kms') {
        $this->showBanner('Starting '.$type.' dusk tests');

        //arguments are passed trough next commands. So remove the ones they certainly don't need to avoid conflicts
        $argumentsToRemove = ['artisan', $type.':test', 'dusk', '--noprep', 'kms', 'shop'];
        $_SERVER['argv'] = array_values(array_filter($_SERVER['argv'], function($argument) use($type, $argumentsToRemove) {
            return !in_array($argument, $argumentsToRemove, true);
        }));
        $_SERVER['argv'][] = '--debug';

        $command = 'php artisan dusk '.$type.' '.implode(' ', $_SERVER['argv']);
        $this->output->writeln('Running: '.$command);
        exec($command, $output); //Artisan::call does not register helpers and other weird stuff happens when you use that instead.
        $this->output->writeln($output);
        $this->output->writeln('Browser tests done.');
    }

    /**
     * Runs phpbench. For benchmarking performance.
     *
     * @param string|null $filterOrGroup
     * @param string|null $filterOrGroupValue
     * @param string $startBanner
     */
    public function phpbench(string $filterOrGroup = null, string $filterOrGroupValue = null, string $startBanner = 'Starting stress tests / benchmarks...')
    {
        $this->showBanner($startBanner);

        $phpbench = base_path('vendor/bin/phpbench');

        $parameters = [];
        $parameters['--config'] = $this->baseDirectory.'phpbench_config.json';
        $parameters['--report'] = 'standard';
        $parameters[$this->baseDirectory.'tests/Benchmark'] = '';

        if($filterOrGroupValue != "" && ($filterOrGroup == "--filter" || $filterOrGroup == "--group")) $parameters[$filterOrGroup] = $filterOrGroupValue;

        $command = $phpbench.' run '.self::parametersToString($parameters);

        $this->output->writeln('Running command to test kms: '.$command);
        exec($command, $lines);
        $this->output->writeln($lines);
    }

    /**
     * Truncates the database. E.g deletes everything in the database
     * @throws \Exception
     */
    protected function truncateDatabase()
    {
        echo 'Truncating database: '.env('DB_DATABASE').PHP_EOL;
        $colname = 'Tables_in_' . env('DB_DATABASE');

        $tables = DB::select('SHOW TABLES');

        $droplist = [];
        foreach($tables as $table) {

            $droplist[] = $table->$colname;

        }
        $droplist = implode(',', $droplist);
        if($droplist == '') return;
        DB::beginTransaction();
        //turn off referential integrity
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        DB::statement("DROP TABLE $droplist");
        //turn referential integrity back on
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
        DB::commit();
    }

    protected static function createAdditionalStyles()
    {
        return array(
            'highlight' => new OutputFormatterStyle('red'),
            'warning' => new OutputFormatterStyle('black', 'yellow'),
        );
    }

    /**
     * @param $parameters
     * @return string
     */
    protected static function parametersToString($parameters)
    {
        $parameterString = '';
        foreach($parameters as $parameter => $value) {
            if($value == '') {
                $parameterString .= ' '.$parameter;
                continue;
            };

            $parameterString .= sprintf(' %s=%s', $parameter, $value);
        }
        return trim($parameterString);
    }

}