colinodell/indentation

一个用于检测和操作字符串和文件缩进的库

v1.0.0 2022-03-20 19:44 UTC

This package is auto-updated.

Last update: 2024-09-03 08:38:34 UTC


README

Latest Version Total Downloads Software License Build Status Coverage Status Quality Score Psalm Type Coverage Sponsor development of this project

PHP库,用于检测和操作文件和字符串的缩进

安装

composer require --dev colinodell/indentation

用法

检测字符串或文件的缩进

use ColinODell\Indentation\Indentation;

$indentation = Indentation::detect(file_get_contents('composer.json'));

assert($indentation->getAmount() === 4);
assert($indentation->getType() === Indentation::TYPE_SPACE);
assert((string)$indentation === '    ');

更改字符串或文件的缩进

use ColinODell\Indentation\Indentation;

$composerJson = file_get_contents('composer.json');
$composerJson = Indentation::change($composerJson, new Indentation(1, Indentation::TYPE_TAB));
file_put_contents('composer.json', $composerJson);

向所有行添加前导缩进

需要按某个量添加所有行的缩进吗?

use ColinODell\Indentation\Indentation;

$codeExample = file_get_contents('file.php');
$indented = Indentation::indent($codeExample, new Indentation(4, Indentation::TYPE_SPACE));

现在您可以将缩进代码嵌入到Markdown文档中!(提示:这与league/commonmark库配合得很好。)

从所有行中移除前导缩进

想象一下,您有一个文件,其中每一行都至少缩进了4个空格

    /**
     * Just a silly example
     */
    class Cat extends Animal
    {
        // ...
    }

您可以使用unindent()方法删除前导缩进,同时保留嵌套缩进

use ColinODell\Indentation\Indentation;

$contents = file_get_contents('Cat.php');
$trimmed = Indentation::unindent($contents);
file_put_contents('Cat.php', $trimmed);

这样您就得到了

/**
 * Just a silly example
 */
class Cat extends Animal
{
    // ...
}

注意,前导的4个空格被移除,但所有其他缩进(如docblock和方法体中的缩进)都被保留。

检测算法

当前算法寻找两个连续非空行之间的最常见差异。

在以下示例中,尽管4个空格缩进被使用了3次,而2个空格的缩进被使用了2次,但由于使用2个空格缩进时只有2次差异,而4个空格缩进有4次差异,所以它被检测为使用较少。

html {
  box-sizing: border-box;
}

body {
  background: gray;
}

p {
    line-height: 1.3em;
    margin-top: 1em;
    text-indent: 2em;
}

源。

此外,如果有多个最常用的差异,则选择具有最多行的缩进。

在以下示例中,缩进被检测为4个空格。

body {
  background: gray;
}

p {
    line-height: 1.3em;
    margin-top: 1em;
    text-indent: 2em;
}