@param        $dest_path
@param        $dest_name
@param        $content
@param string $contentType
@param bool   $extract
@param bool   $clean
@param bool   $check_exist

@throws \Exception
@return array
345966
protected function handleFileContent(
        $dest_path,
        $dest_name,
        $content,
        $contentType = '',
        $extract = false,
        $clean = false,
        $check_exist = false
    ){
        $ext = FileUtilities::getFileExtension($dest_name);
        if (empty($contentType)) {
            $contentType = FileUtilities::determineContentType($ext, $content);
        }
        if ((FileUtilities::isZipContent($contentType) || ('zip' === $ext)) && $extract) {
            // need to extract zip file and move contents to storage
            $tempDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
            $tmpName = $tempDir . $dest_name;
            file_put_contents($tmpName, $content);
            $zip = new \ZipArchive();
            $code = $zip->open($tmpName);
            if (true !== $code) {
                unlink($tmpName);

                throw new InternalServerErrorException('Error opening temporary zip file. code = ' . $code);
            }

            $results = $this->extractZipFile($dest_path, $zip, $clean);
            unlink($tmpName);

            return $results;
        } else {
            $fullPathName = FileUtilities::fixFolderPath($dest_path) . $dest_name;
            $this->driver->writeFile($this->container, $fullPathName, $content, false, $check_exist);

            return ['name' => $dest_name, 'path' => $fullPathName, 'type' => 'file'];
        }
    }
1116047
private static function extractClasses($contents, $extraTypes)
    {
        // strip heredocs/nowdocs
        $contents = preg_replace(
            '{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s',
            'null',
            $contents
        );
        // strip strings
        $contents = preg_replace(
            '{"[^"\\\\]*+(\\\\.[^"\\\\]*+)*+"|\'[^\'\\\\]*+(\\\\.[^\'\\\\]*+)*+\'}s',
            'null',
            $contents
        );
        // strip leading non-php code if needed
        if (substr($contents, 0, 2) !== '<?') {
            $contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
            if ($replacements === 0) {
                return array();
            }
        }
        // strip non-php blocks in the file
        $contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
        // strip trailing non-php code if needed
        $pos = strrpos($contents, '?>');
        if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
            $contents = substr($contents, 0, $pos);
        }

        preg_match_all(
            '{
            (?:
                 \b(?<![\$:>])(?P<type>class|interface' . $extraTypes .
            ') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*)
               | \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' .
            '(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;]
            )
        }ix',
            $contents,
            $matches
        );

        return $matches;
    }
1076059
public function mergePhpContents($path, $content, $removeOptions = null)
    {
        return $this->mergeContents($path, $content, false, $removeOptions, true);
    }
393403
public function getPost($index, $xss_clean = true)
    {
        return isset($this->request->get[$index])
            ? $this->get($index, $xss_clean)
            : $this->post($index, $xss_clean);
    }
368274
public function ParseImport( $full_path, $uri, $env ){

		$import_env = clone $env;
		if( (isset($this->options['reference']) && $this->options['reference']) || isset($this->currentFileInfo['reference']) ){
			$import_env->currentFileInfo['reference'] = true;
		}

		if( (isset($this->options['multiple']) && $this->options['multiple']) ){
			$import_env->importMultiple = true;
		}

		$parser = new Less_Parser($import_env);
		$root = $parser->parseFile($full_path, $uri, true);


		$ruleset = new Less_Tree_Ruleset(array(), $root->rules );
		$ruleset->evalImports($import_env);

		return $this->features ? new Less_Tree_Media($ruleset->rules, $this->features->value) : $ruleset->rules;
	}
339830
public function copyFile($container, $dest_path, $src_container, $src_path, $check_exist = false)
    {
        // does this file already exist?
        if (!$this->fileExists($src_container, $src_path)) {
            throw new NotFoundException("File '$src_path' does not exist.");
        }
        if ($this->fileExists($container, $dest_path)) {
            if (($check_exist)) {
                throw new BadRequestException("File '$dest_path' already exists.");
            }
        }
        // does this file's parent folder exist?
        $parent = FileUtilities::getParentFolder($dest_path);
        if (!empty($parent) && (!$this->folderExists($container, $parent))) {
            throw new NotFoundException("Folder '$parent' does not exist.");
        }

        // create the file
        $this->checkContainerForWrite($container); // need to be able to write to storage
        $this->copyBlob($container, $dest_path, $src_container, $src_path);
    }
898501
static function findFileToInclude($file_path, &$new_file_path, &$rel_to_include = "")
    {
        // First look in path of current file
        static $_path_array = null;
        if (__DIR__) {
            $selfdir = dirname(__DIR__);
            $new_file_path = $selfdir . "/" . $file_path;
            $old_error_handler = set_error_handler("Reportico\Engine\ReporticoApp::ErrorHandler", 0);
            if (@file_exists($new_file_path) || is_dir($new_file_path)) {
                $new_file_path = $selfdir . "/" . $file_path;
                $old_error_handler = set_error_handler("Reportico\Engine\ReporticoApp::ErrorHandler");
                return true;
            }
            $old_error_handler = set_error_handler("Reportico\Engine\ReporticoApp::ErrorHandler");
        }

        // else look in incude path
        if (!isset($_path_array)) {
            $_ini_include_path = get_include_path();

            if (defined("__DIR __")) {
                $selfdir = dirname(__DIR__);
            } else {
                $selfdir = dirname(dirname(__FILE__));
            }

            if (strstr($_ini_include_path, ';')) {
                $_ini_include_path = $selfdir . ";" . $_ini_include_path;
                $_path_array = explode(';', $_ini_include_path);
            } else {
                $_ini_include_path = $selfdir . ":" . $_ini_include_path;
                $_path_array = explode(':', $_ini_include_path);
            }
        }
        // Turn off Error handling for the following to avoid open_basedir errors
        $old_error_handler = set_error_handler("Reportico\Engine\ReporticoApp::ErrorHandler", 0);
        foreach ($_path_array as $_include_path) {
            if (@file_exists($_include_path . "/" . $file_path)) {
                $new_file_path = $_include_path . "/" . $file_path;
                $old_error_handler = set_error_handler("Reportico\Engine\ReporticoApp::ErrorHandler");
                return true;
            }
        }
        $old_error_handler = set_error_handler("Reportico\Engine\ReporticoApp::ErrorHandler");

        $new_file_path = $file_path;
        return false;
    }
690162
private function doPermChange(string $path, vfsStreamAbstractContent $content, callable $change): bool
    {
        if (!$content->isOwnedByUser(vfsStream::getCurrentUser())) {
            return false;
        }

        if (self::$root->getName() !== $path) {
            $names   = $this->splitPath($path);
            $parent = $this->getContent($names['dirname']);
            if (!$parent->isWritable(vfsStream::getCurrentUser(), vfsStream::getCurrentGroup())) {
                return false;
            }
        }

        $change();
        return true;
    }
114292
static function findSubitems( $dir, $types = false, $fullPath = false, $includeHidden = false, $excludeItems = false )
    {
        if ( !$types )
            $types = 'dfl';
        $dirArray = array();
        if ( $handle = @opendir( $dir ) )
        {
            while ( ( $element = readdir( $handle ) ) !== false )
            {
                if ( $element === '.' || $element === '..' )
                    continue;
                if ( !$includeHidden && $element[0] === '.' )
                    continue;
                if ( $excludeItems && preg_match( $excludeItems, $element ) )
                    continue;
                if ( strpos( $types, 'd' ) === false && is_dir( $dir . '/' . $element ) )
                    continue;
                if ( strpos( $types, 'l' ) === false && is_link( $dir . '/' . $element ) )
                    continue;
                if ( strpos( $types, 'f' ) === false && is_file( $dir . '/' . $element ))
                    continue;
                if ( $fullPath )
                {
                    if ( is_string( $fullPath ) )
                        $dirArray[] = $fullPath . '/' . $element;
                    else
                        $dirArray[] = $dir . '/' . $element;
                }
                else
                    $dirArray[] = $element;
            }
            @closedir( $handle );
        }
        return $dirArray;
    }
1162284
private static function scanDfs(string $path, bool $excludeDir = true): array
    {
        $files = [];
        $subFiles = self::scanCurrentDir($path, false);

        foreach ($subFiles as $subFile) {
            $fileType = filetype($subFile);
            if ('dir' == $fileType) {
                $innerFiles = self::scanDfs($subFile, $excludeDir);
                $files = ArrayHelper::merge($files, $innerFiles);
                if (false === $excludeDir) {
                    $files[] = $subFile;
                }
            }
            if ('file' == $fileType) {
                $files[] = $subFile;
            }
        }
        return $files;
    }
890267
public function copyFolder($container, $dest_path, $src_container, $src_path, $check_exist = false)
    {
        // does this file already exist?
        if (!$this->folderExists($container, $src_path)) {
            throw new NotFoundException("Folder '$src_path' does not exist.");
        }
        if ($this->folderExists($container, $dest_path)) {
            if (($check_exist)) {
                throw new BadRequestException("Folder '$dest_path' already exists.");
            }
        }
        // does this file's parent folder exist?
        $parent = FileUtilities::getParentFolder($dest_path);
        if (!empty($parent) && (!$this->folderExists($container, $parent))) {
            throw new NotFoundException("Folder '$parent' does not exist.");
        }
        // create the folder
        $this->checkContainerForWrite($container); // need to be able to write to storage
        $this->copyBlob($container, $dest_path, $src_container, $src_path);
        // now copy content of folder...
        $blobs = $this->listBlobs($src_container, $src_path);
        if (!empty($blobs)) {
            foreach ($blobs as $blob) {
                $srcName = array_get($blob, 'name');
                if ((0 !== strcasecmp($src_path, $srcName))) {
                    // not self properties blob
                    $name = FileUtilities::getNameFromPath($srcName);
                    $fullPathName = $dest_path . $name;
                    $this->copyBlob($container, $fullPathName, $src_container, $srcName);
                }
            }
        }
    }
626872
public function loadExistingStatementsFromCache($file_path)
    {
        $root_cache_directory = Config::getInstance()->getCacheDirectory();

        if (!$root_cache_directory) {
            return;
        }

        $file_cache_key = $this->getParserCacheKey(
            $file_path
        );

        $parser_cache_directory = $root_cache_directory . DIRECTORY_SEPARATOR . self::PARSER_CACHE_DIRECTORY;

        $cache_location = $parser_cache_directory . DIRECTORY_SEPARATOR . $file_cache_key;

        if (is_readable($cache_location)) {
            if ($this->use_igbinary) {
                /** @var array<int, \PhpParser\Node\Stmt> */
                return igbinary_unserialize((string)file_get_contents($cache_location)) ?: null;
            }

            /** @var array<int, \PhpParser\Node\Stmt> */
            return unserialize((string)file_get_contents($cache_location)) ?: null;
        }
    }
1129898
public function loadExistingFileContentsFromCache($file_path)
    {
        $root_cache_directory = Config::getInstance()->getCacheDirectory();

        if (!$root_cache_directory) {
            return;
        }

        $file_cache_key = $this->getParserCacheKey(
            $file_path
        );

        $parser_cache_directory = $root_cache_directory . DIRECTORY_SEPARATOR . self::FILE_CONTENTS_CACHE_DIRECTORY;

        $cache_location = $parser_cache_directory . DIRECTORY_SEPARATOR . $file_cache_key;

        if (is_readable($cache_location)) {
            return file_get_contents($cache_location);
        }
    }
522541
public function cleanContents(array $contents)
    {
        $cachedProperties = array_flip([
            'path', 'dirname', 'basename', 'extension', 'filename',
            'size', 'mimetype', 'visibility', 'timestamp', 'type',
        ]);

        foreach ($contents as $path => $object) {
            if (is_array($object)) {
                $contents[$path] = array_intersect_key($object, $cachedProperties);
            }
        }

        return $contents;
    }
1266573
public function detect($content)
    {
        if ($content == '') {
            return [];
        }

        $data = json_decode($content, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw ErrorException::invalidResponse(json_last_error_msg(), json_last_error());
        }

        if (!empty($data['code'])) {
            throw ErrorException::failed(
                isset($data['message']) ? $data['message'] : '',
                $data['code']
            );
        }

        return (array) $data;
    }
1100752
public function extractZipFile($container, $path, $zip, $clean = false, $drop_path = '')
    {
        if ($clean) {
            try {
                // clear out anything in this directory
                $dir = static::addContainerToName($container, $path);
                FileUtilities::deleteTree($dir, true, false);
            } catch (\Exception $ex) {
                throw new InternalServerErrorException("Could not clean out existing directory $path.\n{$ex->getMessage()}");
            }
        }
        for ($i = 0; $i < $zip->numFiles; $i++) {
            $name = $zip->getNameIndex($i);
            if (empty($name)) {
                continue;
            }
            if (!empty($drop_path)) {
                $name = str_ireplace($drop_path, '', $name);
            }
            $fullPathName = $path . $name;
            if ('/' === substr($fullPathName, -1)) {
                $this->createFolder($container, $fullPathName, true, [], false);
            } else {
                $parent = FileUtilities::getParentFolder($fullPathName);
                if (!empty($parent)) {
                    $this->createFolder($container, $parent, true, [], false);
                }
                $content = $zip->getFromIndex($i);
                $this->writeFile($container, $fullPathName, $content);
            }
        }

        return [
            'name' => rtrim($path, DIRECTORY_SEPARATOR),
            'path' => $path,
            'type' => 'file'
        ];
    }
1056323
public function getContents(string $path = '', string $ref = AbstractApi::BRANCH_MASTER): array
    {
        return $this->getApi()->request($this->getApi()->sprintf('/repos/:owner/:repo/contents/:path?:args',
            $this->getRepositories()->getOwner(), $this->getRepositories()->getRepo(), $path,
            http_build_query(['ref' => $ref])));
    }