Blog Detail

31

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

arrow_back Detect & manipulate indentation of files & strings with Php

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

Published at : 31-03-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project