Recursively compile an associative array to PHP code.
544219
protected function compile($config, $prefix = '') {
        $code = '';
        foreach ($config as $key => $value) {
            if (is_array($value)) {
                $code .= $this->compile($value, $prefix . $key . $this->sectionSeparator);
            } else {
                $fullName = $prefix . $key;
                if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $fullName)) {
                    throw new InvalidArgumentException(__CLASS__ . ": Cannot compile translation key " . $fullName . " because it is not a valid PHP identifier.");
                }
                $code .= 'const ' . $fullName . ' = \'' . str_replace('\'', '\\\'', $value) . "';\n";
            }
        }
        return $code;
    }
1042014
def _encode_data(data):
        """"""
        data = data if data is not None else {}
        data = to_nested_php_args(data)
        files = dict([
            (key, value) for key, value in
            data.items() if isinstance(value, file_type)])
        for fname in files:
            del data[fname]
        return data, files or None, None
1077845
private function _compile() {
		
		// remove spaces
		$this->_result = str_replace('{{ ', '{{', $this->_content);
		$this->_result = str_replace(' }}', '}}', $this->_result);
		
		// check if
		if ($this->ifs) {
			foreach ($this->ifs as $key => $val) {
				$this->_setBool($key, $val);
			}
			empty($this->ifs);
		}
		
		// check loop
		if ($this->loops) {
			foreach ($this->loops as $key => $val) {
				$this->_setArray($key, $val);
			}
			empty($this->loops);
		}
		
		// check static replaces
		if ($this->vars) {
			foreach ($this->vars as $key => $val) {
				$this->_setString($key, $val);
			}
			empty($this->vars);
		}
		
		// include global vars
		if (is_array($this->injects)) {
			foreach ($this->injects as $inject) {
				global $ {
					$inject
				};
			}
			extract($this->injects);
		}
		
		// remove if and loop traces
		$this->_result = preg_replace("/<if\..*?>(.*?)<\/if\..*?>/s", '', $this->_result);
		$this->_result = preg_replace("/<loop\..*?>(.*?)<\/loop\..*?>/s", '', $this->_result);
		
		// check dynamic variables
		$pattern = "\{\{(.*?)\}\}";
		preg_match_all("/" . $pattern . "/", $this->_result, $matches, PREG_SET_ORDER);
		foreach ($matches as $block) {
			$chunk = $block[0];
			$codes = '<?php ' . $this->config['echo'] . '(' . trim($block[1]) . ')' . '; ?>';
			$this->_result = str_replace($chunk, $codes, $this->_result);
		}
		
		// attempt to create cache file for this template in storage directory
		$cache_file = md5($this->_filename) . '.compiled';
		$cache = $this->config['dir_cache'] . '/' . $cache_file;
		$fd = @fopen($cache, 'w+');
		@fwrite($fd, $this->_result);
		@fclose($fd);
		
		// when failed, try to create in /tmp
		if (!file_exists($cache)) {
			$cache = '/tmp/' . $cache_file;
			$fd = @fopen($cache, 'w+');
			@fwrite($fd, $this->_result);
			@fclose($fd);
		}
		
		// if template cache file created then include it, else use eval() to compile
		if (file_exists($cache)) {
			ob_start();
			include $cache;
			$this->_compiled = ob_get_contents();
			ob_end_clean();
			@unlink($cache);
		} else {
			ob_start();
			eval('?>' . $this->_result . '<?php ');
			$this->_compiled = ob_get_contents();
			ob_end_clean();
		}
	}
273312
private static function encodeArray(array $array)
    {
        // If it is an associative array, treat it as an object.
        if (!empty($array) && array_keys($array) !== range(0, count($array) - 1)) {
            return self::encodeMap($array);
        }

        // Differentiate on the array length.
        if (count($array) < 16) {
            // fixarray
            $prefix = bindec(1001) * 16 + count($array);
        } elseif (count($array) < pow(2, 16)) {
            // array 16
            $prefix = 0xdc * 256 * 256;
            $prefix += count($array);
        } elseif (count($array) < pow(2, 32)) {
            // array 32
            $prefix = 0xdd * 256 * 256 * 256 * 256;
            $prefix += count($array);
        } else {
            throw new UnencodeableException('Array with more then 2^32 elements included cannot be encoded.', 1);
        }

        // Byte encode it.
        $result = pack('H*', dechex($prefix));

        // Loop every item of the array.
        foreach (array_values($array) as $item) {
            // Concatenate everything.
            $result .= self::encode($item);
        }

        // Return the result.
        return $result;
    }
1155653
function compile($indent) {
		$function_name = $this->function_name( $this->name ) ;
		
		// Build the typestack
		$typestack = array(); $class=$this;
		do {
			$typestack[] = $this->function_name($class->name);
		}
		while($class = $class->extends);

		$typestack = "array('" . implode("','", $typestack) . "')";
		
		// Build an array of additional arguments to add to result node (if any)
		if (empty($this->arguments)) {
			$arguments = 'null';
		}
		else {
			$arguments = "array(";
			foreach ($this->arguments as $k=>$v) { $arguments .= "'$k' => '$v'"; }
			$arguments .= ")";
		}
		
		$match = PHPBuilder::build() ;
		
		$match->l("protected \$match_{$function_name}_typestack = $typestack;");

		$match->b( "function match_{$function_name} (\$stack = array())",
			'$matchrule = "'.$function_name.'"; $result = $this->construct($matchrule, $matchrule, '.$arguments.');',
			$this->parsed->compile()->replace(array(
				'MATCH' => 'return $this->finalise($result);',
				'FAIL' => 'return FALSE;'
			))
		);

		$functions = array() ;
		foreach( $this->functions as $name => $function ) {
			$function_name = $this->function_name( preg_match( '/^_/', $name ) ? $this->name.$name : $this->name.'_'.$name ) ;
			$functions[] = implode( PHP_EOL, array(
				'function ' . $function_name . ' ' . $function
			));
		}

		// print_r( $match ) ; return '' ;
		return $match->render(NULL, $indent) . PHP_EOL . PHP_EOL . implode( PHP_EOL, $functions ) ;
	}
508600
private function compile()
    {
        $options = $replaces = [];
        $pattern = rtrim(ltrim($this->pattern, ':/'), '/');

        // correct [/ first occurrence]
        if (strpos($pattern, '[/') === 0) {
            $pattern = '[' . substr($pattern, 2);
        }

        if (preg_match_all('/<(\w+):?(.*?)?>/', $pattern, $matches)) {
            $variables = array_combine($matches[1], $matches[2]);

            foreach ($variables as $key => $segment) {
                $segment = $this->prepareSegment($key, $segment);
                $replaces["<$key>"] = "(?P<$key>$segment)";
                $options[] = $key;
            }
        }

        $template = preg_replace('/<(\w+):?.*?>/', '<\1>', $pattern);
        $options = array_fill_keys($options, null);

        foreach ($this->constrains as $key => $value) {
            if ($value instanceof Autofill) {
                // only forces value replacement, not required to be presented as parameter
                continue;
            }

            if (!array_key_exists($key, $options)) {
                throw new ConstrainException(sprintf(
                    "Route `%s` does not define routing parameter `<%s>`.",
                    $this->pattern,
                    $key
                ));
            }
        }

        $this->compiled = '/^' . strtr($template, $replaces + self::PATTERN_REPLACES) . '$/iu';
        $this->template = stripslashes(str_replace('?', '', $template));
        $this->options = $options;
    }
301037
public static function associativeArray(array $array) {
        $string = '[ ';
        foreach($array as $key => $item) {
            $string .= $key . ' => ' . $item;
            if($item !== last($array)) {
                $string .= ', ';
            }
        }
        $string .= ' ]';

        return $string;
    }
469818
static function postCompile(Smarty_Internal_TemplateCompilerBase $compiler, $initChildSequence = false)
    {
        $compiler->prefixCompiledCode .= "<?php \$_smarty_tpl->ext->_inheritance->init(\$_smarty_tpl, " .
            var_export($initChildSequence, true) . ");\n?>\n";
    }
723047
public function to_smarty_php()
    {
        $code = '';
        for ($key = 0, $cnt = count($this->subtrees); $key < $cnt; $key++) {
            if ($key + 2 < $cnt) {
                if ($this->subtrees[$key] instanceof _smarty_linebreak && $this->subtrees[$key + 1] instanceof _smarty_tag && $this->subtrees[$key + 1]->data == '' && $this->subtrees[$key + 2] instanceof _smarty_linebreak) {
                    $key = $key + 1;
                    continue;
                }
                if (substr($this->subtrees[$key]->data, -1) == '<' && $this->subtrees[$key + 1]->data == '' && substr($this->subtrees[$key + 2]->data, -1) == '?') {
                    $key = $key + 2;
                    continue;
                }
            }
            if (substr($code, -1) == '<') {
                $subtree = $this->subtrees[$key]->to_smarty_php();
                if (substr($subtree, 0, 1) == '?') {
                    $code = substr($code, 0, strlen($code) - 1) . '<<?php ?>?' . substr($subtree, 1);
                } elseif ($this->parser->asp_tags && substr($subtree, 0, 1) == '%') {
                    $code = substr($code, 0, strlen($code) - 1) . '<<?php ?>%' . substr($subtree, 1);
                } else {
                    $code .= $subtree;
                }
                continue;
            }
            if ($this->parser->asp_tags && substr($code, -1) == '%') {
                $subtree = $this->subtrees[$key]->to_smarty_php();
                if (substr($subtree, 0, 1) == '>') {
                    $code = substr($code, 0, strlen($code) - 1) . '%<?php ?>>' . substr($subtree, 1);
                } else {
                    $code .= $subtree;
                }
                continue;
            }
            if (substr($code, -1) == '?') {
                $subtree = $this->subtrees[$key]->to_smarty_php();
                if (substr($subtree, 0, 1) == '>') {
                    $code = substr($code, 0, strlen($code) - 1) . '?<?php ?>>' . substr($subtree, 1);
                } else {
                    $code .= $subtree;
                }
                continue;
            }
            $code .= $this->subtrees[$key]->to_smarty_php();
        }

        return $code;
    }
221560
function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$value, $namedParameters, $placement )
    {
        $phpname = $this->PHPNames[$operatorName];
        if ( $value !== null )
            $operand = $value;
        else
            $operand = $tpl->elementValue( $operatorParameters[0], $rootNamespace, $currentNamespace, $placement );
        $value = $phpname( $operand );
    }
9303
public static function buildFromArray($array)
    {
        $returnValue = null;

        
        if (!empty($array)){
        	if (!empty($array['type'])){
        		$acceptedTypes = array('PHPRuntime', 'PHPINIValue', 'PHPExtension', 'PHPDatabaseDriver', 'FileSystemComponent', 'Custom', 'Mock');
        		$cleanType = preg_replace('/^Check/i', '', $array['type']);
        		if (in_array($cleanType, $acceptedTypes)){
        			
        			if (!empty($array['value'])){
        				$values = $array['value'];
        				
        				// Optional parameter is always used.
        				$optional = false;
        				if (!empty($values['optional'])){
        					$optional = $values['optional'];
        				}
        				
	        			switch ($cleanType){
	        				case 'PHPRuntime':
	        					$max = null;
	        					if (!empty($values['max'])){
	        						$max = $values['max'];
	        					}
	        					
	        					if (empty($values['min'])){
	        						$msg = "Mandatory attribute 'min' is missing.";
	        						throw new common_configuration_ComponentFactoryException($msg);	
	        					}
	        					
	        					$returnValue = self::buildPHPRuntime($values['min'], $max, $optional);
	        				break;
	        				
	        				case 'PHPINIValue':
	        					if (empty($values['name'])){
	        						$msg = "Mandatory attribute 'name' is missing.";
	        						throw new common_configuration_ComponentFactoryException($msg);	
	        					}
	        					
	        					if (empty($values['value']) && $values['value'] !== '0'){
	        						$msg = "Mandatory attribute 'value' is missing.";
	        						throw new common_configuration_ComponentFactoryException($msg);	
	        					}
	        					
	        					$returnValue = self::buildPHPINIValue($values['name'], $values['value'], $optional);
	        				break;
	        				
	        				case 'PHPExtension':
	        					if (empty($values['name'])){
	        						$msg = "Mandatory attribute 'name' is missing.";
	        						throw new common_configuration_ComponentFactoryException($msg);	
	        					}
	        					
	        					$min = null;
	        					if (!empty($values['min'])){
	        						$min = $values['min'];	
	        					}
	        					
	        					$max = null;
	        					if (!empty($values['max'])){
	        						$max = $values['max'];	
	        					}
	        					
	        					$returnValue = self::buildPHPExtension($values['name'], $min, $max, $optional);
	        				break;
	        				
	        				case 'PHPDatabaseDriver':
	        					if (empty($values['name'])){
	        						$msg = "Mandatory attribute 'name' is missing.";
	        						throw new common_configuration_ComponentFactoryException($msg);	
	        					}
	        					
	        					$returnValue = self::buildPHPDatabaseDriver($values['name'], $optional);
	        				break;
	        				
	        				case 'FileSystemComponent':
	        					if (empty($values['location'])){
	        						$msg = "Mandatory attribute 'location' is missing.";
	        						throw new common_configuration_ComponentFactoryException($msg);	
	        					}
	        					
	        					if (empty($values['rights'])){
	        						$msg = "Mandatory attribute 'rights' is missing.";
	        						throw new common_configuration_ComponentFactoryException($msg);	
	        					}
	        					
	        					$returnValue = self::buildFileSystemComponent($values['location'], $values['rights'], $optional);
	        				break;
	        				
	        				case 'Custom':
	        					if (empty($values['name'])){
	        						$msg = "Mandatory attribute 'name' is missing.";
	        						throw new common_configuration_ComponentFactoryException($msg);	
	        					}

	        					$extension = 'generis';
	        					if (!empty($values['extension'])){
	        						$extension = $values['extension'];
	        					}
	        					
	        					$returnValue = self::buildCustom($values['name'], $extension, $optional);
	        				break;
	        				
	        				case 'Mock':
	        					$status = common_configuration_Report::VALID; 
	        					if (!empty($values['status'])){
	        						$status = $values['status'];
	        					}
	        					
	        					$returnValue = self::buildMock($status, $optional);
	        				break;
	        			}	
        			}
        			else{
        				$msg = "No 'value' array provided.";
        				throw new common_configuration_ComponentFactoryException($msg);
        			}
        		}
        		else{
        			$msg = "Unknown 'type' = '${cleanType}'.";
        			throw new common_configuration_ComponentFactoryException($msg);
        		}
        	}
        	else{
        		$msg = "Cannot build a Configuration Component without 'type'.";
        		throw new common_configuration_ComponentFactoryException($msg);
        	}
        }
        else{
        	$msg = 'Cannot build a Configuration Component with an empty array.';
        	throw new common_configuration_ComponentFactoryException($msg);
        }
        

        return $returnValue;
    }
544185
public function buildAutoloadArrays()
    {
        $phpFiles = $this->fetchFiles();

        $phpClasses = array();
        foreach ( $phpFiles as $mode => $fileList )
        {
            $phpClasses[$mode] = $this->getClassFileList( $fileList, $mode );
        }

        $maxClassNameLength = $this->checkMaxClassLength( $phpClasses );
        $this->autoloadArrays = $this->dumpArray( $phpClasses, $maxClassNameLength );

        if ( $this->options->writeFiles )
        {
            $this->writeAutoloadFiles();
        }
    }
763766
public function compileFrom()
    {
        $fromQuery = '';

        foreach ($this->query->getQueryFrom() as $key => $value) {
            if ($key == 0) {
                $fromQuery = "$value";
            } else {
                $fromQuery .= ",$value";
            }
        }

        $this->queryString = "{$this->queryString} FROM $fromQuery";
    }
802004
private static function array_recursive(&$array, $function, $apply_to_keys_also = false) {
		foreach ( $array as $key => $value ) {
			if (is_array ( $value )) {
				self::array_recursive ( $array [$key], $function, $apply_to_keys_also );
			} else {
				$array [$key] = $function ( $value );
			}

			if ($apply_to_keys_also && is_string ( $key )) {
				$new_key = $function ( $key );
				if ($new_key != $key) {
					$array [$new_key] = $array [$key];
					unset ( $array [$key] );
				}
			}
		}
	}
295971
private function compile_arrays( $view )
	{	
		$tokens = token_get_all( $view );

		$tags = array( 0 => '' );
		$tag_index = 0;
		$in_tag = false;

		// parse all php tags out of the view
		foreach ( $tokens as $token ) 
		{
			if ( is_array( $token ) ) 
			{
				if ( $token[0] === T_OPEN_TAG )
				{
					$in_tag = true;
				}

				if ( $in_tag && !in_array( $token[0], array( T_INLINE_HTML ) ) ) 
				{				
					$tags[$tag_index] .= $token[1];
				}

				if ( $token[0] === T_CLOSE_TAG )
				{
					$in_tag = false;
					$tag_index++;
				}
			}
			else 
			{
				if ( $in_tag )
				{
					$tags[$tag_index] .= $token;
				}
			}
		}

		// lets make the tags search keys
		$tags = array_flip( $tags );

		// now search and replace var in the php sections
		foreach( $tags as $search => &$replace )
		{
			$replace = preg_replace_callback('/(\$[a-zA-Z0-9\_\.\-\>\;]+)/s', function( $match )
			{ 
				$var = $match[1];

				if ( strpos( $var, '.' ) !== false )
				{
					$buffer = '';
					$length = strlen( $var );
					$inside_arr = false;

					for( $i=0;$i<$length;$i++ )
					{
						$char = $var[$i];

						if ( $char == '.' && !$inside_arr  )
						{
							$buffer .= "['";
							$inside_arr = true;
						}
						else
						{
							if ( $inside_arr && in_array( $char, array( ';', '-', ',' ) ) )
							{
								$buffer .= "']";
								$inside_arr = false;
							}

							if ( $char == '.' )
							{
								$buffer .= "']['";
								$inside_arr = true;
							}
							else
							{
								$buffer .= $char;
							}
						}
					}

					if ( $inside_arr )
					{
						$buffer .= "']";
					}

					$var = $buffer;
				}

				return $var;

			}, $search );
		}

		return CCStr::replace( $view, $tags );
	}
9280
private static function _toArray($data, $recursion = false)
    {
        $tmp  = array();
        $data = (array) $data;
        foreach ($data as $k => $v) {
            $v = (array) $v;
            if (isset($v[0]) && is_string($v[0])) {
                $tmp[$k] = $v[0];
            } else {
                $tmp[$k] = self::_toArray($v, true);
            }
        }
        return $tmp;
    }
61223
public function compile()
	{
		//reset arrays
		$this->params     = [];
		$this->paramNames = [];
		$this->conditions = [];

		$this->compiled = true;

		$uri = $this->normalizeUri($this->getUri());

		// match patterns like /{param?:regex}
		// tested in https://regex101.com/r/gP6yH7
		$regex = preg_replace_callback(
			'#(?:(\\/)?\\{(\\w+)(\\?)?(?::((?:\\\\\\{|\\\\\\}|[^{}]|\\{\\d(?:\\,(?:\\d)?)?\\})+))?\\})#',
			[$this, 'createRegex'],
			$uri
		);

		$regex .= "/?";

		$regex = '#^' . $regex . '$#';

		if ($this->caseSensitive === false)
		{
			$regex .= 'i';
		}

		$this->pattern = $regex;

		return $this;
	}