ファイルの指定行と前後3行を取得する

行番号をキーとした連想配列を返す

@param   string  $file
@param   int $line

@return  string[]
972050
protected function getFileContents($file, $line){
        if(!is_string($file) || !is_int($line)
            || !is_file($file) || !is_readable($file)
        ){
            return null;
        }

        $file       = new \SplFileObject($file, "r");
        $current    = 1;
        $contents   = [];
        $min        = $line - 3;
        $max        = $line + 3;

        foreach($file as $row){
            if($min <= $current && $current <= $max){
                $contents[$current] = $row;
            }

            $current++;
        }

        if(empty($contents)){
            return null;
        }

        return $contents;
    }
549593
public function addValue($value, string $file, int $line){
        $this->values[] = [
            "value" => $value,
            "file"  => $file,
            "line"  => $line,
        ];

        return $this;
    }
1026276
def get_lines_from_file(filename, lineno, context_lines):
    

    def get_lines(start, end):
        return [linecache.getline(filename, l).rstrip() for l in range(start, end)]

    lower_bound = max(1, lineno - context_lines)
    upper_bound = lineno + context_lines
    linecache.checkcache(filename)
    pre_context = get_lines(lower_bound, lineno)
    context_line = linecache.getline(filename, lineno).rstrip()
    post_context = get_lines(lineno + 1, upper_bound)
    return lower_bound, pre_context, context_line, post_context
1238238
public function fileExcerpt($file, $line)
    {
        if (is_readable($file)) {
            if (\extension_loaded('fileinfo')) {
                $finfo = new \finfo();

                // Check if the file is an application/octet-stream (eg. Phar file) because highlight_file cannot parse these files
                if ('application/octet-stream' === $finfo->file($file, FILEINFO_MIME_TYPE)) {
                    return;
                }
            }

            // highlight_file could throw warnings
            // see https://bugs.php.net/bug.php?id=25725
            $code = @highlight_file($file, true);
            // remove main code/span tags
            $code = preg_replace('#^<code.*?>\s*<span.*?>(.*)</span>\s*</code>#s', '\\1', $code);
            $content = explode('<br />', $code);

            $lines = [];
            for ($i = max($line - 3, 1), $max = min($line + 3, \count($content)); $i <= $max; ++$i) {
                $lines[] = '<li'.($i == $line ? ' class="selected"' : '').'><code>'.self::fixCodeMarkup($content[$i - 1]).'</code></li>';
            }

            return '<ol start="'.max($line - 3, 1).'">'.implode("\n", $lines).'</ol>';
        }
    }
123040
protected function parseMultiLine($line, \SplFileObject $file, &$lineBreaks)
    {
        while ($this->isMultiLine($line) && $file->valid()) {
            $lineBreaks[] = strlen($line);

            $line2 = $file->getCurrentLine();

            // trim the ending slash
            $line = rtrim($line, '\\');
            // concatenate with next line
            $line = trim($line . $line2);

        }
        return $line;
    }
1193007
public function formatFile($file, $line, $text = null)
    {
        $flags = ENT_QUOTES | ENT_SUBSTITUTE;

        if (null === $text) {
            $file = trim($file);
            $fileStr = $file;
            if (0 === strpos($fileStr, $this->rootDir)) {
                $fileStr = str_replace(['\\', $this->rootDir], ['/', ''], $fileStr);
                $fileStr = htmlspecialchars($fileStr, $flags, $this->charset);
                $fileStr = sprintf('<abbr title="%s">kernel.project_dir</abbr>/%s', htmlspecialchars($this->rootDir, $flags, $this->charset), $fileStr);
            }

            $text = sprintf('%s at line %d', $fileStr, $line);
        }

        if (false !== $link = $this->getFileLink($file, $line)) {
            return sprintf('<a href="%s" title="Click to open this file" class="file_link">%s</a>', htmlspecialchars($link, $flags, $this->charset), $text);
        }

        return $text;
    }
226224
public function mergeEnvironments(array $lines, string $file): array
    {
        if ($this->files->exists($file)) {
            $lines = \array_replace_recursive($lines, $this->files->getRequire($file));
        }

        return $lines;
    }
1120490
private function findTableChars(string $line) : ?array
    {
        $lineChar  = $line[0];
        $spaceChar = null;

        for ($i = 0; $i < strlen($line); $i++) {
            if ($line[$i] === $lineChar) {
                continue;
            }

            if ($spaceChar === null) {
                $spaceChar = $line[$i];

                continue;
            }

            if ($line[$i] !== $spaceChar) {
                return null;
            }
        }

        if ($spaceChar === null) {
            return null;
        }

        return [$lineChar, $spaceChar];
    }
291207
protected function findUseStatements(File $file)
    {
        if (array_key_exists($file->getFilename(), static::$useCache)) {
            return static::$useCache[$file->getFilename()];
        }

        $tokens = $file->getTokens();
        $usePosition = $file->findNext(T_USE, 0);
        $useStatements = [];

        while ($usePosition !== false) {
            if ($this->shouldIgnoreUse($file, $usePosition)) {
                $usePosition = $file->findNext(T_USE, $usePosition + 1);
                continue;
            }

            $fullPath = '';
            $lastString = '';
            $alias = '';

            $useEnd = $file->findNext(
                [T_SEMICOLON, T_COMMA],
                $usePosition
            );
            $useFullPathEnd = $file->findNext(
                [T_SEMICOLON, T_COMMA, T_WHITESPACE],
                $usePosition + 2
            );

            $afterUse = $file->findNext(
                [T_STRING, T_NS_SEPARATOR],
                $usePosition
            );

            while ($afterUse !== false) {
                $fullPath .= $tokens[$afterUse]['content'];

                if ($tokens[$afterUse]['code'] == T_STRING) {
                    $lastString = $tokens[$afterUse]['content'];
                }

                $afterUse = $file->findNext(
                    [T_STRING, T_NS_SEPARATOR],
                    $afterUse + 1,
                    $useFullPathEnd
                );
            }

            if ($useFullPathEnd != $useEnd) {
                if ($tokens[$useFullPathEnd + 1]['code'] !== T_AS) {
                    continue;
                }

                if ($tokens[$useFullPathEnd + 3]['code'] === T_STRING) {
                    $alias = $tokens[$useFullPathEnd + 3]['content'];
                }
            } else {
                $alias = $lastString;
            }

            $useStatements[$fullPath] = $alias;

            $usePosition = $file->findNext(T_USE, $usePosition + 1);
        }

        static::$useCache[$file->getFilename()] = $useStatements;

        return $useStatements;
    }
451069
public static function getLineSlices(string $line)
    {
        preg_match('/^(\d+) (\w+) ([a-z0-9]+) +(\d+|-)\t(.*)$/', $line, $matches);
        $permissions = $matches[1];
        $type = null;
        switch ($matches[2]) {
            case NodeObject::TYPE_TREE:
                $type = NodeObject::TYPE_TREE;
                break;
            case NodeObject::TYPE_BLOB:
                $type = NodeObject::TYPE_BLOB;
                break;
            case NodeObject::TYPE_LINK:
                $type = NodeObject::TYPE_LINK;
                break;
        }
        $sha = $matches[3];
        $size = $matches[4];
        $fullPath = $matches[5];

        return [
            'permissions' => $permissions,
            'type'        => $type,
            'sha'         => $sha,
            'size'        => $size,
            'fullPath'    => $fullPath,
        ];
    }
105317
private function chunk($line)
    {
        $width = $this->getWidth();
        if (mb_strlen($line) <= $width) {
            return [$line];
        }
        $stripped = $this->terminal->filter($line, static::REPLACEMENT_CHAR);
        $offset = 0;
        $out = [];

        for ($i = 0, $j = 0; $i <= mb_strlen($stripped); $i++) {
            if (mb_substr($stripped, $i, 1) != static::REPLACEMENT_CHAR) {
                if ($j > 0 && $j % $width == 0) {
                    $out[] = mb_substr($line, $offset, $i - $offset);
                    $offset = $i;
                }
                $j++;
            }
        }

        // return any remaining entries
        if ($offset != $i - 1) {
            $out[] = mb_substr($line, $offset);
        }
        return $out;
    }
262383
protected function loadMappingFile($file)
    {
        $result     = [];
        $xmlElement = simplexml_load_file($file);

        if (isset($xmlElement->entity)) {
            foreach ($xmlElement->entity as $entityElement) {
                $entityName          = (string) $entityElement['name'];
                $result[$entityName] = $entityElement;
            }
        }

        return $result;
    }
936318
public function getFileFunctions($file) {
    $code = file_get_contents($file);
    //drush_print($code);

    $matches = array();
    $pattern = "/^function (\w+)/m";
    preg_match_all($pattern, $code, $matches);

    return $matches[1];
  }
828569
public function run(string $file, Node $node): array
    {
        if ($this->isFunctionCall($node, 'json_decode')) {
            $options = $node->children['args']->children[3] ?? null;
            if ($this->shouldCheckOption($options) && !$this->isIncludeJSONThrowOnErrorOption($options)) {
                return [new Hint(
                    self::HINT_TYPE,
                    self::HINT_MESSAGE,
                    $file,
                    $node->lineno,
                    self::HINT_LINK
                )];
            }
        }
        if ($this->isFunctionCall($node, 'json_encode')) {
            $options = $node->children['args']->children[1] ?? null;
            if ($this->shouldCheckOption($options) && !$this->isIncludeJSONThrowOnErrorOption($options)) {
                return [new Hint(
                    self::HINT_TYPE,
                    self::HINT_MESSAGE,
                    $file,
                    $node->lineno,
                    self::HINT_LINK
                )];
            }
        }

        return [];
    }
1105308
private function parseIniFile(string $file): array
    {
        $ini = parse_ini_file($file, true);

        if (!\is_array($ini)) {
            throw new \RuntimeException("File $file cannot be decoded");
        }

        if (!isset($ini['requires']) || !\is_array($ini['requires'])) {
            return [];
        }

        return $ini['requires'];
    }
847401
public static function parse($line)
    {
        $data = explode(':', $line);
        $filed = $data[0];
        if (isset($data[2])) {
            unset($data[0]);
            $value = implode(':', $data);
        } else {
            $value = $data[1];
        }
        return [rtrim($filed), ltrim($value)];
    }
528447
protected function splitLine($line)
    {
        $result = [];
        foreach($this->fields as $field) {
            $result[] = mb_substr($line, $field['from'], $field['to'] - $field['from']);
        }
        return $result;
    }