Detect & manipulate indentation of files & strings with Php

Detect & manipulate indentation of files & strings with Php cover image

Colin O’Dell introduced a PHP library called Indentation, that can be utilized to detect and manipulate the indentation of files and strings.

Installation

You can install this package via composer:

composer require --dev colinodell/indentation

Usage

Detecting the indentation of a string or file

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 === '    ');

Changing the indentation of a string or file

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);

Adding leading indentation to all lines

Need to add indent all lines by some amount?

use ColinODell\Indentation\Indentation;

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

Now you can embed the indented code into a Markdown document!

Removing leading indentation from all lines

Imagine you have a file where every line is indented by at least 4 spaces:

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

You can trim that leading indentation while preserving the nested indentation with the unindent() method:

use ColinODell\Indentation\Indentation;

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

Giving you:

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

Note how the leading 4 spaces are removed but all other indentation (like in the docblock and method body) is preserved.

For more details about this package, you can visit Github

Written by

Rizwan Aslam

Founder and CEO of CodeBrisk, with years of experience building web applications with Laravel and leading a team of expert developers.

More about Rizwan
Book a free call
Book a free call with CodeBrisk Open in new tab