<commit_before><?php
class Bridge {

    static protected $dirBridge;

    public function __construct(){
        throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.');
    }

    /**
    * Checks if a bridge is an instantiable bridge.
    * @param string $nameBridge name of the bridge that you want to use
    * @return true if it is an instantiable bridge, false otherwise.
    */
    static public function isInstantiable($nameBridge){
        $re = new ReflectionClass($nameBridge);
        return $re->IsInstantiable();
    }

    /**
    * Create a new bridge object
    * @param string $nameBridge Defined bridge name you want use
    * @return Bridge object dedicated
    */
    static public function create($nameBridge){
        if(!preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameBridge)){
            $message = <<<EOD
'nameBridge' must start with one uppercase character followed or not by
alphanumeric or dash characters!
EOD;
            throw new \InvalidArgumentException($message);
        }

        $nameBridge = $nameBridge . 'Bridge';
        $pathBridge = self::getDir() . $nameBridge . '.php';

        if(!file_exists($pathBridge)){
            throw new \Exception('The bridge you looking for does not exist. It should be at path ' . $pathBridge);
        }

        require_once $pathBridge;

        if(Bridge::isInstantiable($nameBridge)){
            return new $nameBridge();
        } else {
            return false;
        }
    }

    static public function setDir($dirBridge){
        if(!is_string($dirBridge)){
            throw new \InvalidArgumentException('Dir bridge must be a string.');
        }

        if(!file_exists($dirBridge)){
            throw new \Exception('Dir bridge does not exist.');
        }

        self::$dirBridge = $dirBridge;
    }

    static public function getDir(){
        $dirBridge = self::$dirBridge;

        if(is_null($dirBridge)){
            throw new \LogicException(__CLASS__ . ' class need to know bridge path !');
        }

        return $dirBridge;
    }

    /**
    * Lists the available bridges.
    * @return array List of the bridges
    */
    static public function listBridges(){
        $pathDirBridge = self::getDir();
        $listBridge = array();
        $dirFiles = scandir($pathDirBridge);

        if($dirFiles !== false){
            foreach($dirFiles as $fileName){
                if(preg_match('@^([^.]+)Bridge\.php$@U', $fileName, $out)){
                    $listBridge[] = $out[1];
                }
            }
        }

        return $listBridge;
    }

    static public function isWhitelisted($whitelist, $name){
        if(in_array($name, $whitelist)
          or in_array($name . '.php', $whitelist)
          or in_array($name . 'Bridge', $whitelist) // DEPRECATED
          or in_array($name . 'Bridge.php', $whitelist) // DEPRECATED
          or count($whitelist) === 1 and trim($whitelist[0]) === '*'){
            return true;
        } else {
            return false;
        }
    }
}

interface BridgeInterface {
    public function collectData();
    public function getCacheDuration();
    public function getName();
    public function getURI();
}

abstract class BridgeAbstract implements BridgeInterface {

    const NAME = 'Unnamed bridge';
    const URI = '';
    const DESCRIPTION = 'No description provided';
    const MAINTAINER = 'No maintainer';
    const PARAMETERS = array();

    public $useProxy = true;

    protected $cache;
    protected $items = array();
    protected $inputs = array();
    protected $queriedContext = '';

    protected function returnError($message, $code){
        throw new \HttpException($message, $code);
    }

    protected function returnClientError($message){
        $this->returnError($message, 400);
    }

    protected function returnServerError($message){
        $this->returnError($message, 500);
    }

    /**
    * Return items stored in the bridge
    * @return mixed
    */
    public function getItems(){
        return $this->items;
    }

    protected function validateTextValue($value, $pattern = null){
        if(!is_null($pattern)){
            $filteredValue = filter_var($value, FILTER_VALIDATE_REGEXP,
                array('options' => array(
                    'regexp' => '/^' . $pattern . '$/'
                ))
            );
        } else {
            $filteredValue = filter_var($value);
        }

        if($filteredValue === false)
            return null;

        return $filteredValue;
    }

    protected function validateNumberValue($value){
        $filteredValue = filter_var($value, FILTER_VALIDATE_INT);

        if($filteredValue === false && !empty($value))
            return null;

        return $filteredValue;
    }

    protected function validateCheckboxValue($value){
        $filteredValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

        if(is_null($filteredValue))
            return null;

        return $filteredValue;
    }

    protected function validateListValue($value, $expectedValues){
        $filteredValue = filter_var($value);

        if($filteredValue === false)
            return null;

        if(!in_array($filteredValue, $expectedValues)){ // Check sub-values?
            foreach($expectedValues as $subName => $subValue){
                if(is_array($subValue) && in_array($filteredValue, $subValue))
                    return $filteredValue;
            }
            return null;
        }

        return $filteredValue;
    }

    protected function validateData(&$data){
        if(!is_array($data))
            return false;

        foreach($data as $name=>$value){
            $registered = false;
            foreach(static::PARAMETERS as $context=>$set){
                if(array_key_exists($name,$set)){
                    $registered = true;
                    if(!isset($set[$name]['type'])){
                        $set[$name]['type']='text';
                    }

                    switch($set[$name]['type']){
                    case 'number':
                        $data[$name] = $this->validateNumberValue($value);
                        break;
                    case 'checkbox':
                        $data[$name] = $this->validateCheckboxValue($value);
                        break;
                    case 'list':
                        $data[$name] = $this->validateListValue($value, $set[$name]['values']);
                        break;
                    default:
                    case 'text':
                        if(isset($set[$name]['pattern'])){
                            $data[$name] = $this->validateTextValue($value, $set[$name]['pattern']);
                        } else {
                            $data[$name] = $this->validateTextValue($value);
                        }
                        break;
                    }

                    if(is_null($data[$name])){
                        echo 'Parameter \'' . $name . '\' is invalid!' . PHP_EOL;
                        return false;
                    }
                }
            }

            if(!$registered)
                return false;
        }

        return true;
    }

    protected function setInputs(array $inputs){
        foreach($inputs as $name => $value){
            foreach(static::PARAMETERS as $context => $set){
                if(array_key_exists($name, static::PARAMETERS[$context])){
                    $this->inputs[$context][$name]['value'] = $value;
                }
            }
        }
    }

    protected function getQueriedContext(array $inputs){
        $queriedContexts=array();
        foreach(static::PARAMETERS as $context=>$set){
            $queriedContexts[$context]=null;
            foreach($set as $id=>$properties){
                if(isset($inputs[$id]) && !empty($inputs[$id])){
                    $queriedContexts[$context]=true;
                }elseif(isset($properties['required']) &&
                    $properties['required']===true){
                    $queriedContexts[$context]=false;
                    break;
                }
            }
        }

        if(array_key_exists('global',static::PARAMETERS) &&
            $queriedContexts['global']===false){
            return null;
        }
        unset($queriedContexts['global']);

        switch(array_sum($queriedContexts)){
        case 0:
            foreach($queriedContexts as $context=>$queried){
                if (is_null($queried)){
                    return $context;
                }
            }
            return null;
        case 1: return array_search(true,$queriedContexts);
        default: return false;
        }
    }

    /**
    * Defined datas with parameters depending choose bridge
    * Note : you can define a cache with "setCache"
    * @param array array with expected bridge paramters
    */
    public function setDatas(array $inputs){
        if(!is_null($this->cache)){
            $this->cache->prepare($inputs);
            $time = $this->cache->getTime();
            if($time !== false && (time() - $this->getCacheDuration() < $time)){
                $this->items = $this->cache->loadData();
                return;
            }
        }

        if(empty(static::PARAMETERS)){
            if(!empty($inputs)){
                $this->returnClientError('Invalid parameters value(s)');
            }

            $this->collectData();
            if(!is_null($this->cache)){
                $this->cache->saveData($this->getItems());
            }
            return;
        }

        if(!$this->validateData($inputs)){
            $this->returnClientError('Invalid parameters value(s)');
        }

        $this->setInputs($inputs);

        // Guess the paramter context from input data
        $this->queriedContext = $this->getQueriedContext($inputs);
        if(is_null($this->queriedContext)){
            $this->returnClientError('Required parameter(s) missing');
        } elseif($this->queriedContext === false){
            $this->returnClientError('Mixed context parameters');
        }

        // Apply default values to missing data
        $contexts=array($this->queriedContext);
        if(array_key_exists('global',static::PARAMETERS)){
            $contexts[]='global';
        }
        foreach($contexts as $context){
            foreach(static::PARAMETERS[$context] as $name=>$properties){
                if(!isset($properties['type'])){
                  $type='text';
                }else{
                  $type=$properties['type'];
                }
                if(isset($this->inputs[$context][$name]['value'])){
                  continue;
                }
                switch($properties['type']){
                case 'checkbox':
                    if(!isset($properties['defaultValue'])){
                        $this->inputs[$context][$name]['value']=false;
                    }else{
                        $this->inputs[$context][$name]['value']=$properties['defaultValue'];
                    }
                    break;
                case 'list':
                    if(!isset($properties['defaultValue'])){
                        $firstItem=reset($properties['values']);
                        if(is_array($firstItem)){
                            $firstItem=reset($firstItem);
                        }
                        $this->inputs[$context][$name]['value']=$firstItem;
                    }else{
                        $this->inputs[$context][$name]['value']=$properties['defaultValue'];
                    }
                    break;
                default:
                    if(isset($properties['defaultValue'])){
                        $this->inputs[$context][$name]['value']=$properties['defaultValue'];
                    }
                    break;
                }
            }
        }

        // Copy global parameter values to the guessed context
        if(array_key_exists('global',static::PARAMETERS)){
            foreach(static::PARAMETERS['global'] as $name=>$properties){
                if(isset($inputs[$name])){
                    $value=$inputs[$name];
                }else if(isset($properties['value'])){
                    $value=$properties['value'];
                }else{
                    continue;
                }
                $this->inputs[$this->queriedContext][$name]['value']=$value;
            }
        }

        // Only keep guessed context parameters values
        if(!isset($this->inputs[$this->queriedContext])){
          $this->inputs[$this->queriedContext]=array();
        }
        $this->inputs=array($this->queriedContext=>$this->inputs[$this->queriedContext]);

        $this->collectData();

        if(!is_null($this->cache)){
            $this->cache->saveData($this->getItems());
        }
    }<commit_msg>[Bridge] Apply default value while setting inputs<commit_after><?php
class Bridge {

    static protected $dirBridge;

    public function __construct(){
        throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.');
    }

    /**
    * Checks if a bridge is an instantiable bridge.
    * @param string $nameBridge name of the bridge that you want to use
    * @return true if it is an instantiable bridge, false otherwise.
    */
    static public function isInstantiable($nameBridge){
        $re = new ReflectionClass($nameBridge);
        return $re->IsInstantiable();
    }

    /**
    * Create a new bridge object
    * @param string $nameBridge Defined bridge name you want use
    * @return Bridge object dedicated
    */
    static public function create($nameBridge){
        if(!preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameBridge)){
            $message = <<<EOD
'nameBridge' must start with one uppercase character followed or not by
alphanumeric or dash characters!
EOD;
            throw new \InvalidArgumentException($message);
        }

        $nameBridge = $nameBridge . 'Bridge';
        $pathBridge = self::getDir() . $nameBridge . '.php';

        if(!file_exists($pathBridge)){
            throw new \Exception('The bridge you looking for does not exist. It should be at path ' . $pathBridge);
        }

        require_once $pathBridge;

        if(Bridge::isInstantiable($nameBridge)){
            return new $nameBridge();
        } else {
            return false;
        }
    }

    static public function setDir($dirBridge){
        if(!is_string($dirBridge)){
            throw new \InvalidArgumentException('Dir bridge must be a string.');
        }

        if(!file_exists($dirBridge)){
            throw new \Exception('Dir bridge does not exist.');
        }

        self::$dirBridge = $dirBridge;
    }

    static public function getDir(){
        $dirBridge = self::$dirBridge;

        if(is_null($dirBridge)){
            throw new \LogicException(__CLASS__ . ' class need to know bridge path !');
        }

        return $dirBridge;
    }

    /**
    * Lists the available bridges.
    * @return array List of the bridges
    */
    static public function listBridges(){
        $pathDirBridge = self::getDir();
        $listBridge = array();
        $dirFiles = scandir($pathDirBridge);

        if($dirFiles !== false){
            foreach($dirFiles as $fileName){
                if(preg_match('@^([^.]+)Bridge\.php$@U', $fileName, $out)){
                    $listBridge[] = $out[1];
                }
            }
        }

        return $listBridge;
    }

    static public function isWhitelisted($whitelist, $name){
        if(in_array($name, $whitelist)
          or in_array($name . '.php', $whitelist)
          or in_array($name . 'Bridge', $whitelist) // DEPRECATED
          or in_array($name . 'Bridge.php', $whitelist) // DEPRECATED
          or count($whitelist) === 1 and trim($whitelist[0]) === '*'){
            return true;
        } else {
            return false;
        }
    }
}

interface BridgeInterface {
    public function collectData();
    public function getCacheDuration();
    public function getName();
    public function getURI();
}

abstract class BridgeAbstract implements BridgeInterface {

    const NAME = 'Unnamed bridge';
    const URI = '';
    const DESCRIPTION = 'No description provided';
    const MAINTAINER = 'No maintainer';
    const PARAMETERS = array();

    public $useProxy = true;

    protected $cache;
    protected $items = array();
    protected $inputs = array();
    protected $queriedContext = '';

    protected function returnError($message, $code){
        throw new \HttpException($message, $code);
    }

    protected function returnClientError($message){
        $this->returnError($message, 400);
    }

    protected function returnServerError($message){
        $this->returnError($message, 500);
    }

    /**
    * Return items stored in the bridge
    * @return mixed
    */
    public function getItems(){
        return $this->items;
    }

    protected function validateTextValue($value, $pattern = null){
        if(!is_null($pattern)){
            $filteredValue = filter_var($value, FILTER_VALIDATE_REGEXP,
                array('options' => array(
                    'regexp' => '/^' . $pattern . '$/'
                ))
            );
        } else {
            $filteredValue = filter_var($value);
        }

        if($filteredValue === false)
            return null;

        return $filteredValue;
    }

    protected function validateNumberValue($value){
        $filteredValue = filter_var($value, FILTER_VALIDATE_INT);

        if($filteredValue === false && !empty($value))
            return null;

        return $filteredValue;
    }

    protected function validateCheckboxValue($value){
        $filteredValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

        if(is_null($filteredValue))
            return null;

        return $filteredValue;
    }

    protected function validateListValue($value, $expectedValues){
        $filteredValue = filter_var($value);

        if($filteredValue === false)
            return null;

        if(!in_array($filteredValue, $expectedValues)){ // Check sub-values?
            foreach($expectedValues as $subName => $subValue){
                if(is_array($subValue) && in_array($filteredValue, $subValue))
                    return $filteredValue;
            }
            return null;
        }

        return $filteredValue;
    }

    protected function validateData(&$data){
        if(!is_array($data))
            return false;

        foreach($data as $name=>$value){
            $registered = false;
            foreach(static::PARAMETERS as $context=>$set){
                if(array_key_exists($name,$set)){
                    $registered = true;
                    if(!isset($set[$name]['type'])){
                        $set[$name]['type']='text';
                    }

                    switch($set[$name]['type']){
                    case 'number':
                        $data[$name] = $this->validateNumberValue($value);
                        break;
                    case 'checkbox':
                        $data[$name] = $this->validateCheckboxValue($value);
                        break;
                    case 'list':
                        $data[$name] = $this->validateListValue($value, $set[$name]['values']);
                        break;
                    default:
                    case 'text':
                        if(isset($set[$name]['pattern'])){
                            $data[$name] = $this->validateTextValue($value, $set[$name]['pattern']);
                        } else {
                            $data[$name] = $this->validateTextValue($value);
                        }
                        break;
                    }

                    if(is_null($data[$name])){
                        echo 'Parameter \'' . $name . '\' is invalid!' . PHP_EOL;
                        return false;
                    }
                }
            }

            if(!$registered)
                return false;
        }

        return true;
    }

    protected function setInputs(array $inputs){
        foreach($inputs as $name => $value){
            foreach(static::PARAMETERS as $context => $set){
                if(array_key_exists($name, static::PARAMETERS[$context])){
                    $this->inputs[$context][$name]['value'] = $value;
                }
            }
        }

        // Apply default values to missing data
        $contexts = array($this->queriedContext);
        if(array_key_exists('global', static::PARAMETERS)){
            $contexts[] = 'global';
        }

        foreach($contexts as $context){
            foreach(static::PARAMETERS[$context] as $name => $properties){
                if(!isset($properties['type'])){
                  $type = 'text';
                } else {
                  $type = $properties['type'];
                }
                if(isset($this->inputs[$context][$name]['value'])){
                  continue;
                }
                switch($properties['type']){
                case 'checkbox':
                    if(!isset($properties['defaultValue'])){
                        $this->inputs[$context][$name]['value'] = false;
                    } else {
                        $this->inputs[$context][$name]['value'] = $properties['defaultValue'];
                    }
                    break;
                case 'list':
                    if(!isset($properties['defaultValue'])){
                        $firstItem = reset($properties['values']);
                        if(is_array($firstItem)){
                            $firstItem = reset($firstItem);
                        }
                        $this->inputs[$context][$name]['value'] = $firstItem;
                    } else {
                        $this->inputs[$context][$name]['value'] = $properties['defaultValue'];
                    }
                    break;
                default:
                    if(isset($properties['defaultValue'])){
                        $this->inputs[$context][$name]['value'] = $properties['defaultValue'];
                    }
                    break;
                }
            }
        }

        // Copy global parameter values to the guessed context
        if(array_key_exists('global', static::PARAMETERS)){
            foreach(static::PARAMETERS['global'] as $name => $properties){
                if(isset($inputs[$name])){
                    $value = $inputs[$name];
                }else if(isset($properties['value'])){
                    $value = $properties['value'];
                }else{
                    continue;
                }
                $this->inputs[$this->queriedContext][$name]['value'] = $value;
            }
        }

        // Only keep guessed context parameters values
        if(!isset($this->inputs[$this->queriedContext])){
          $this->inputs[$this->queriedContext] = array();
        }
        $this->inputs = array($this->queriedContext=>$this->inputs[$this->queriedContext]);
    }

    protected function getQueriedContext(array $inputs){
        $queriedContexts=array();
        foreach(static::PARAMETERS as $context=>$set){
            $queriedContexts[$context]=null;
            foreach($set as $id=>$properties){
                if(isset($inputs[$id]) && !empty($inputs[$id])){
                    $queriedContexts[$context]=true;
                }elseif(isset($properties['required']) &&
                    $properties['required']===true){
                    $queriedContexts[$context]=false;
                    break;
                }
            }
        }

        if(array_key_exists('global',static::PARAMETERS) &&
            $queriedContexts['global']===false){
            return null;
        }
        unset($queriedContexts['global']);

        switch(array_sum($queriedContexts)){
        case 0:
            foreach($queriedContexts as $context=>$queried){
                if (is_null($queried)){
                    return $context;
                }
            }
            return null;
        case 1: return array_search(true,$queriedContexts);
        default: return false;
        }
    }

    /**
    * Defined datas with parameters depending choose bridge
    * Note : you can define a cache with "setCache"
    * @param array array with expected bridge paramters
    */
    public function setDatas(array $inputs){
        if(!is_null($this->cache)){
            $this->cache->prepare($inputs);
            $time = $this->cache->getTime();
            if($time !== false && (time() - $this->getCacheDuration() < $time)){
                $this->items = $this->cache->loadData();
                return;
            }
        }

        if(empty(static::PARAMETERS)){
            if(!empty($inputs)){
                $this->returnClientError('Invalid parameters value(s)');
            }

            $this->collectData();
            if(!is_null($this->cache)){
                $this->cache->saveData($this->getItems());
            }
            return;
        }

        if(!$this->validateData($inputs)){
            $this->returnClientError('Invalid parameters value(s)');
        }

        // Guess the paramter context from input data
        $this->queriedContext = $this->getQueriedContext($inputs);
        if(is_null($this->queriedContext)){
            $this->returnClientError('Required parameter(s) missing');
        } elseif($this->queriedContext === false){
            $this->returnClientError('Mixed context parameters');
        }

        $this->setInputs($inputs);

        $this->collectData();

        if(!is_null($this->cache)){
            $this->cache->saveData($this->getItems());
        }
    }
{'fraction_non_alphanumeric': 0.1349645747028534, 'fraction_numerical': 0.0010066204653683844, 'mean_word_length': 1.7178030303030303, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 141, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3165193', 'n_tokens_mistral': 6812, 'n_tokens_neox': 6393, 'n_words': 1344}