Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ A powerful and flexible PHP library for formatting and transforming strings.
composer require respect/string-formatter
```

## Usage

You can use individual formatters directly or chain multiple formatters together using the `FormatterBuilder`:

```php
use Respect\StringFormatter\FormatterBuilder as f;

echo f::create()
->mask('7-12')
->pattern('#### #### #### ####')
->format('1234123412341234');
// Output: 1234 12** **** 1234
```

## Formatters

| Formatter | Description |
Expand Down
3 changes: 3 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
cacheDirectory=".phpunit.cache">
<testsuites>
<testsuite name="integration">
<directory>tests/Integration/</directory>
</testsuite>
<testsuite name="unit">
<directory>tests/Unit/</directory>
</testsuite>
Expand Down
63 changes: 63 additions & 0 deletions src/FormatterBuilder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

/*
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-License-Identifier: ISC
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
*/

declare(strict_types=1);

namespace Respect\StringFormatter;

use ReflectionClass;
use Respect\StringFormatter\Mixin\Builder;

use function array_reduce;
use function ucfirst;

/** @mixin Builder */
final readonly class FormatterBuilder implements Formatter
{
/** @var array<Formatter> */
private array $formatters;

public function __construct(Formatter ...$formatters)
{
$this->formatters = $formatters;
}

public static function create(Formatter ...$formatters): self
{
return new self(...$formatters);
}

public function format(string $input): string
{
if ($this->formatters === []) {
throw new InvalidFormatterException('No formatters have been added to the builder');
}

return array_reduce(
$this->formatters,
static fn(string $carry, Formatter $formatter) => $formatter->format($carry),
$input,
);
}

/** @param array<int, mixed> $arguments */
public function __call(string $name, array $arguments): self
{
/** @var class-string<Formatter> $class */
$class = __NAMESPACE__ . '\\' . ucfirst($name) . 'Formatter';
$reflection = new ReflectionClass($class);

return clone($this, ['formatters' => [...$this->formatters, $reflection->newInstanceArgs($arguments)]]);
}

/** @param array<int, mixed> $arguments */
public static function __callStatic(string $name, array $arguments): self
{
return self::create()->__call($name, $arguments);
}
}
24 changes: 24 additions & 0 deletions src/Mixin/Builder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/*
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-License-Identifier: ISC
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
*/

declare(strict_types=1);

namespace Respect\StringFormatter\Mixin;

use Respect\StringFormatter\FormatterBuilder;

/** @mixin FormatterBuilder */
interface Builder
{
public static function mask(string $range, string $replacement = '*'): Chain;

public static function pattern(string $pattern): Chain;

/** @param array<string, mixed> $parameters */
public static function placeholder(array $parameters): Chain;
}
24 changes: 24 additions & 0 deletions src/Mixin/Chain.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/*
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-License-Identifier: ISC
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
*/

declare(strict_types=1);

namespace Respect\StringFormatter\Mixin;

use Respect\StringFormatter\Formatter;
use Respect\StringFormatter\FormatterBuilder;

interface Chain extends Formatter
{
public function mask(string $range, string $replacement = '*'): FormatterBuilder;

public function pattern(string $pattern): FormatterBuilder;

/** @param array<string, mixed> $parameters */
public function placeholder(array $parameters): FormatterBuilder;
}
198 changes: 198 additions & 0 deletions tests/Integration/FormatterBuilderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
<?php

/*
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-License-Identifier: ISC
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
*/

declare(strict_types=1);

namespace Respect\StringFormatter\Test\Integration;

use ArgumentCountError;
use Error;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use ReflectionException;
use Respect\StringFormatter\FormatterBuilder;
use Respect\StringFormatter\InvalidFormatterException;
use Respect\StringFormatter\MaskFormatter;
use Respect\StringFormatter\PatternFormatter;
use Respect\StringFormatter\PlaceholderFormatter;

use function sprintf;

#[CoversClass(FormatterBuilder::class)]
final class FormatterBuilderTest extends TestCase
{
#[Test]
public function itShouldFormatWithSingleFormatter(): void
{
$input = '1234123412341234';
$range = '1-3,8-12';
$maskFormatter = new MaskFormatter($range);
$expected = $maskFormatter->format($input);

$builder = new FormatterBuilder();

$actual = $builder->mask($range)->format($input);

self::assertSame($expected, $actual);
}

#[Test]
public function itShouldFormatWithMultipleFormatters(): void
{
$input = '1234123412341234';
$range = '1-3,8-12';
$pattern = '#### #### #### ####';
$maskFormatter = new MaskFormatter($range);
$patternFormatter = new PatternFormatter($pattern);
$expected = $patternFormatter->format($maskFormatter->format($input));

$builder = new FormatterBuilder();

$actual = $builder->mask($range)->pattern($pattern)->format($input);

self::assertSame($expected, $actual);
}

#[Test]
public function itShouldThrowExceptionWhenFormattingWithoutFormatters(): void
{
$builder = new FormatterBuilder();

$this->expectException(InvalidFormatterException::class);
$this->expectExceptionMessage('No formatters have been added to the builder');

$builder->format('test');
}

#[Test]
public function itShouldAllowCallingSameFormatterMultipleTimes(): void
{
$input = '1234567890';
$firstRange = '1-3';
$secondRange = '5-7';
$firstMaskFormatter = new MaskFormatter($firstRange);
$secondMaskFormatter = new MaskFormatter($secondRange);
$expected = $secondMaskFormatter->format($firstMaskFormatter->format($input));

$builder = new FormatterBuilder();
$builder = $builder->mask($firstRange)->mask($secondRange);

$actual = $builder->format($input);

self::assertSame($expected, $actual);
}

#[Test]
public function itShouldCreateMaskFormatterUsingStaticFactory(): void
{
$input = '1234567890';
$range = '1-3';
$maskFormatter = new MaskFormatter($range);
$expected = $maskFormatter->format($input);

$actual = FormatterBuilder::mask($range)->format($input);

self::assertSame($expected, $actual);
}

#[Test]
public function itShouldCreatePatternFormatterUsingStaticFactory(): void
{
$input = '1234567890';
$pattern = '###-###-####';
$patternFormatter = new PatternFormatter($pattern);
$expected = $patternFormatter->format($input);

$actual = FormatterBuilder::pattern($pattern)->format($input);

self::assertSame($expected, $actual);
}

#[Test]
public function itShouldCreatePlaceholderFormatterUsingStaticFactory(): void
{
$input = 'Hello, {{name}}!';
$parameters = ['name' => 'World'];
$placeholderFormatter = new PlaceholderFormatter($parameters);
$expected = $placeholderFormatter->format($input);

$actual = FormatterBuilder::placeholder($parameters)->format($input);

self::assertSame($expected, $actual);
}

#[Test]
public function itShouldUsePlaceholderFormatter(): void
{
$input = 'Hello, {{name}}! Your balance is {{amount}}.';
$parameters = [
'name' => 'John',
'amount' => 100.5,
];
$expected = (new PlaceholderFormatter($parameters))->format($input);

$builder = new FormatterBuilder();
$actual = $builder->placeholder($parameters)->format($input);

self::assertSame($expected, $actual);
}

#[Test]
public function itShouldBuildFormatterWithMultipleArguments(): void
{
$input = '1234567890';
$range = '1-3,7-9';
$replacement = 'X';
$maskFormatter = new MaskFormatter($range, $replacement);
$expected = $maskFormatter->format($input);

$builder = new FormatterBuilder();
$actual = $builder->mask($range, $replacement)->format($input);

self::assertSame($expected, $actual);
}

#[Test]
public function itShouldThrowExceptionWhenFormatterIsNotInstantiable(): void
{
$builder = new FormatterBuilder();

$this->expectException(Error::class);
$this->expectExceptionMessage('Cannot instantiate interface Respect\StringFormatter\Formatter');

$builder->__call('', []);
}

#[Test]
public function itShouldThrowExceptionWhenFormatterArgumentIsMissing(): void
{
$builder = new FormatterBuilder();

$this->expectException(ArgumentCountError::class);
$this->expectExceptionMessage(sprintf(
'Too few arguments to function %s::__construct(), 0 passed and exactly 1 expected',
PatternFormatter::class,
));

/** @phpstan-ignore arguments.count */
$builder->pattern();
}

#[Test]
public function itShouldThrowExceptionWhenFormatterDoesNotExist(): void
{
$builder = new FormatterBuilder();

$this->expectException(ReflectionException::class);
$this->expectExceptionMessage('Class "Respect\StringFormatter\NonexistentFormatter" does not exist');

/** @phpstan-ignore method.notFound */
$builder->nonexistent();
}
}