@param string $filePath
@param int $cutOffDepth The number of levels of curly braces to go before ignoring the content

@return string
15859
public static function remove_class_content($filePath, $cutOffDepth = 1)
    {

        // Use PHP's built in method to strip comments and whitespace
        $contents = php_strip_whitespace($filePath);

        if (!trim($contents)) {
            return $contents;
        }

        if (!preg_match('/\b(?:class|interface|trait)/i', $contents)) {
            return '';
        }

        // tokenize the file contents
        $tokens = token_get_all($contents);
        $cleanContents = '';
        $depth = 0;
        $startCounting = false;
        // iterate over all the tokens and only store the tokens that are outside $cutOffDepth
        foreach ($tokens as $token) {
            // only store the string literal of the token, that's all we need
            if (!is_array($token)) {
                $token = [
                    T_STRING,
                    $token,
                    null
                ];
            }

            // only count if we see a class/interface/trait keyword
            if (!$startCounting && in_array($token[0], [T_CLASS, T_INTERFACE, T_TRAIT])) {
                $startCounting = true;
            }

            // use curly braces as a sign of depth
            if ($token[1] === '{') {
                if ($depth < $cutOffDepth) {
                    $cleanContents .= $token[1];
                }
                if ($startCounting) {
                    ++$depth;
                }
            } elseif ($token[1] === '}') {
                if ($startCounting) {
                    --$depth;

                    // stop counting if we've just come out of the
                    // class/interface/trait declaration
                    if ($depth <= 0) {
                        $startCounting = false;
                    }
                }
                if ($depth < $cutOffDepth) {
                    $cleanContents .= $token[1];
                }
            } elseif ($depth < $cutOffDepth) {
                $cleanContents .= $token[1];
            }
        }

        // return cleaned class
        return trim($cleanContents);
    }
370792
protected function logFilename($filename, $filePath)
    {
        $filePath = trim(rtrim($filePath, "\/"));
        $filename = trim(trim($filename, "\/"));

        $path = $filePath . DIRECTORY_SEPARATOR . $filename;

        if (!realpath($path) || !file_exists($path)) {
            touch($path);
        }

        return realpath($path);
    }
674560
public function withFileToSend($filePath, $attachmentName = null, $attachment = false)
    {
        if (!is_string($attachmentName)) {
            $basePath = basename($filePath);
        } else {
            $basePath = $attachmentName;
        }

        $this->file = $filePath;

        if ($attachment) {
            return $this->withHeader('Content-Description', 'File Transfer')
                ->withHeader('Content-Disposition', 'attachment; filename="' . $basePath . '"')
                ->withHeader('Content-Transfer-Encoding', 'binary');
        }

        return $this;
    }
697582
protected function getFileFunctions($filePath)
    {
        $source = file_get_contents($filePath);
        $tokens = token_get_all($source);

        $functions = [];
        $nextStringIsFunc = false;
        foreach($tokens as $token) {
            switch($token[0]) {
                case T_FUNCTION:
                    $nextStringIsFunc = true;
                    break;

                case T_STRING:
                    if ($nextStringIsFunc) {
                        $nextStringIsFunc = false;
                        $functions[] = $token[1];
                    }
                    break;
            }
        }

        return $functions;
    }
417466
protected function getFileRelativePath($filePath)
    {
        $commonParts = array();

        // replace window \ to work with /
        $rootDir = (false !== strpos($this->rootDir, '\\')) ? str_replace('\\', '/', $this->rootDir) : $this->rootDir;

        $antiSlash = false;
        if (false !== strpos($filePath, '\\')) {
            $filePath = str_replace('\\', '/', $filePath);
            $antiSlash = true;
        }

        $rootDirParts = explode('/', $rootDir);
        $filePathParts = explode('/', $filePath);

        $i = 0;
        while ($i < count($rootDirParts)) {
            if (isset($rootDirParts[$i], $filePathParts[$i]) && $rootDirParts[$i] == $filePathParts[$i]) {
                $commonParts[] = $rootDirParts[$i];
            }
            $i++;
        }

        $filePath = str_replace(implode('/', $commonParts).'/', '', $filePath);

        $nbCommonParts = count($commonParts);
        $nbRootParts = count($rootDirParts);

        for ($i = $nbCommonParts; $i < $nbRootParts; $i++) {
            $filePath = '../'.$filePath;
        }

        return $antiSlash ? str_replace('/', '\\', $filePath) : $filePath;
    }
1244327
private function generateGenericFileDebugInfo (Asset $asset, string $filePath, string $openingComment, string $closingComment) : string
    {
        // keep the blank line at the end, as php strips blank lines at the end of HEREDOC
        return <<<HEADER
{$openingComment}
    Embed asset
        {$asset->getAssetPath()}
    from file 
        {$filePath}
{$closingComment}

HEADER;
    }
445875
public function getExtensionByFileName($filepath)
    {
        $path = pathinfo($filepath);

        // check if the file has the extenison and we need
        // to lower down the extension (caused unknown extension for uppercased extension)
        if (isset($path['extension'])) {
            return strtolower($path['extension']);
        } else if (is_string($this->getMime())) {
            return str_replace("image/", "", $this->getMime());
        } else if ($this->format != "") {
            return $this->format;
        } else {
            // fallback to enable save image on empty extension. ImageMagick has no problem with this.
            return "jpg";
        }
    }
176073
public function getFileContent( string$filePath ):string
	{
		return isset($this->fileGetter) ? $this->fileGetter($filePath) : file_get_contents($filePath);
	}
619165
public static function parse(string $filePath): FilePathInterface
    {
        if (!self::myFilePathParse(
            DIRECTORY_SEPARATOR,
            $filePath,
            function ($p, $d, &$e) {
                return self::myPartValidator($p, $d, $e);
            },
            null,
            $isAbsolute,
            $aboveBaseLevel,
            $drive,
            $directoryParts,
            $filename,
            $error)
        ) {
            throw new FilePathInvalidArgumentException('File path "' . $filePath . '" is invalid: ' . $error);
        }

        return new self($isAbsolute, $aboveBaseLevel, $drive, $directoryParts, $filename);
    }
39622
public function getPreviousPage($filepath, $entityPath)
    {
        $previousUrl = $previousPage = null;

        foreach ($this->getPages() as $url => $page) {
            if ($filepath == $page['filepath']) {
                if ($previousUrl) {
                    return new ArrayData(
                        array(
                        'Link' => $this->buildUrl($previousUrl),
                        'Title' => $previousPage['title']
                        )
                    );
                }
            }

            if (strpos($page['filepath'], $entityPath) !== false) {
                $previousUrl = $url;
                $previousPage = $page;
            }
        }

        return null;
    }
765133
public function tail($filepath, $lines = 1) {

        $f = @fopen($filepath, "rb");
        if ($f === false) return false;

        else $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));

        fseek($f, -1, SEEK_END);
        if (fread($f, 1) != "\n") $lines -= 1;

        // Start reading
        $output = '';
        $chunk = '';
        // While we would like more
        while (ftell($f) > 0 && $lines >= 0) {
            // Figure out how far back we should jump
            $seek = min(ftell($f), $buffer);
            // Do the jump (backwards, relative to where we are)
            fseek($f, -$seek, SEEK_CUR);
            // Read a chunk and prepend it to our output
            $output = ($chunk = fread($f, $seek)) . $output;
            // Jump back to where we started reading
            fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
            // Decrease our line counter
            $lines -= substr_count($chunk, "\n");
        }
        // While we have too many lines
        // (Because of buffer size we might have read too many)
        while ($lines++ < 0) {
            // Find first newline and remove all text before that
            $output = substr($output, strpos($output, "\n") + 1);
        }
        // Close file and return
        fclose($f);

        return trim($output);
    }
945924
private function editFile($filePath, $shouldRemoveFile)
    {
        $escapedFilePath = \escapeshellarg($filePath);

        $pipes = [];
        $proc = \proc_open((\getenv('EDITOR') ?: 'nano') . " {$escapedFilePath}", [STDIN, STDOUT, STDERR], $pipes);
        \proc_close($proc);

        $editedContent = @\file_get_contents($filePath);

        if ($shouldRemoveFile) {
            @\unlink($filePath);
        }

        if ($editedContent === false) {
            throw new \UnexpectedValueException("Reading {$filePath} returned false");
        }

        return $editedContent;
    }
533342
public static function getRelative($filePath, $rootPath = null, $forceDS = DIRECTORY_SEPARATOR, $toRealpath = true)
    {
        // Cleanup file path
        if ($toRealpath && !self::isReal($filePath)) {
            $filePath = self::real($filePath);
        }
        $filePath = self::clean($filePath, $forceDS);


        // Cleanup root path
        $rootPath = $rootPath ?: Sys::getDocRoot();
        if ($toRealpath && !self::isReal($rootPath)) {
            $rootPath = self::real($rootPath);
        }
        $rootPath = self::clean($rootPath, $forceDS);


        // Remove root part
        $relPath = preg_replace('#^' . preg_quote($rootPath, null) . '#i', '', $filePath);
        $relPath = ltrim($relPath, $forceDS);

        return $relPath;
    }
22324
function getCamelCase(filePath) {
    if (!filePath) {
        return '';
    }

    // clip off everything by after the last slash and the .js
    filePath = filePath.substring(filePath.lastIndexOf(delim) + 1);

    if (filePath.substring(filePath.length - 3) === '.js') {
        filePath = filePath.substring(0, filePath.length - 3);
    }

    // replace dots with caps
    var parts = filePath.split('.');
    var i;
    for (i = 1; i < parts.length; i++) {
        parts[i] = parts[i].substring(0, 1).toUpperCase() +
            parts[i].substring(1);
    }

    // replace dashs with caps
    filePath = parts.join('');
    parts = filePath.split('-');
    for (i = 1; i < parts.length; i++) {
        parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1);
    }

    return parts.join('');
}
959288
function(filepath) {
    var pieces = _.last(filepath.split('/')).split('.');
    var name   = _(pieces).without(_.last(pieces)).join('.'); // strips file extension
    if (name.charAt(0) === '_') {
      name = name.substr(1, name.length); // strips leading _ character
    }
    return name;
  }
377105
public function processFile($filePath, $functions) {
		$result = array(
			'problems' => array(),
			'fixes' => array(),
		);
		$phpTokens = new PhpFileParser($filePath);
		$changes = 0;
		foreach ($phpTokens as $key => $row) {
			// get non trivial tokens
			if (is_array($row)) {
				list($token, $functionName, $lineNumber) = $row;
				$originalFunctionName = $functionName;

				// prepare normalized version of function name for matching
				$functionName = strtolower($functionName);

				// check for function call
				if ($token == T_STRING
					&& !$phpTokens->isEqualToToken(T_OBJECT_OPERATOR, $key-1) //not method
					&& !$phpTokens->isEqualToToken(T_DOUBLE_COLON, $key-1) //not static method
					&& !$phpTokens->isEqualToToken(T_FUNCTION, $key-2) //not definition
				) {
					// mark function as called
					if (function_exists($functionName) && !in_array($functionName, $this->calledFunctions)) {
						$this->calledFunctions[] = $functionName;
					}
					// is it function we're looking for
					if (isset($functions[$functionName])) {
						$definingFunctionName = $phpTokens->getDefiningFunctionName($key);

						//we're skipping deprecated calls that are in deprecated function itself
						if (!$definingFunctionName || !isset($functions[strtolower($definingFunctionName)])) {
							$result['problems'][] = array($functions[$functionName], $originalFunctionName, $lineNumber);
						}

						//do instant replacement
						if ($this->fixProblems && isset($this->instantReplacements[$functionName])) {
							$phpTokens[$key] = array(T_STRING, $this->instantReplacements[$functionName]);
							$result['fixes'][] = array($originalFunctionName, $this->instantReplacements[$functionName], $lineNumber);
							$changes++;
						}
					}
				}
			}
		}
		if ($changes) {
			try {
				$phpTokens->exportPhp($filePath);
			} catch (\CodeReview\IOException $e) {
				echo '*** Error: ' . $e->getMessage() . " ***\n";
			}
		}
		unset($phpTokens);
		return $result;
	}
1327887
public static function file_lines($filepath, $line_num, $highlight = true, $padding = 5)
	{
		// deal with eval'd code
		if (strpos($filepath, 'eval()\'d code') !== false)
		{
			return '';
		}

		// We cache the entire file to reduce disk IO for multiple errors
		if ( ! isset(static::$files[$filepath]))
		{
			static::$files[$filepath] = file($filepath, FILE_IGNORE_NEW_LINES);
			array_unshift(static::$files[$filepath], '');
		}

		$start = $line_num - $padding;
		if ($start < 0)
		{
			$start = 0;
		}

		$length = ($line_num - $start) + $padding + 1;
		if (($start + $length) > count(static::$files[$filepath]) - 1)
		{
			$length = NULL;
		}

		$debug_lines = array_slice(static::$files[$filepath], $start, $length, TRUE);

		if ($highlight)
		{
			$to_replace = array('<code>', '</code>', '<span style="color: #0000BB">&lt;?php&nbsp;', "\n");
			$replace_with = array('', '', '<span style="color: #0000BB">', '');

			foreach ($debug_lines as & $line)
			{
				$line = str_replace($to_replace, $replace_with, highlight_string('<?php ' . $line, TRUE));
			}
		}

		return $debug_lines;
	}