Skip to content

Commit

Permalink
[TASK] Add documentation about FileProcessors (#121)
Browse files Browse the repository at this point in the history
* [TASK] Add documentation about FileProcessors

Resolves: rectorphp/rector#6374

* [TASK] Change some things
  • Loading branch information
sabbelasichon committed Jun 13, 2021
1 parent 651562d commit 25821f6
Show file tree
Hide file tree
Showing 3 changed files with 309 additions and 1 deletion.
3 changes: 2 additions & 1 deletion build/target-repository/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ By [buying a book](https://leanpub.com/rector-the-power-of-automated-refactoring
- [How to Ignore Rule or Paths](/docs/how_to_ignore_rule_or_paths.md)
- [Static Reflection and Autoload](/docs/static_reflection_and_autoload.md)
- [How to Configure Rule](/docs/how_to_configure_rules.md)
- [Beyond PHP - Entering the realm of FileProcessors](/docs/beyond_php_file_processors.md)

### For Rule Developers and Contributors

Expand All @@ -47,7 +48,7 @@ By [buying a book](https://leanpub.com/rector-the-power-of-automated-refactoring
- [How to Work with Doc Block and Comments](/docs/how_to_work_with_doc_block_and_comments.md)
- [How to Generate New Rector Rule](/docs/create_own_rule.md)
- [How to add Test for Rector Rule](/docs/how_to_add_test_for_rector_rule.md)

- [How to create a custom FileProcessor](/docs/create_custom_fileprocessor.md)
<br>

## Install
Expand Down
101 changes: 101 additions & 0 deletions build/target-repository/docs/beyond_php_file_processors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Beyond PHP - FileProcessors

You think Rector is all about PHP? You might be wrong.
Sure, the vast majority of the rules included in Rector is for PHP-Code. That´s true.

But since version 0.11.x Rector introduced the concept of so called FileProcessors.
When you are running Rector with the process command all collected files from your configured paths
are iterated through all registered FileProcessors.

Each FileProcessor must implement the [FileProcessorInterface](https://github.com/rectorphp/rector-src/blob/main/src/Contract/Processor/FileProcessorInterface.php) and must decide if it is able to handle a given file by
the [supports](https://github.com/rectorphp/rector-src/blob/main/src/Contract/Processor/FileProcessorInterface.php#L11) method or not.

Rector itself already ships with three FileProcessors. Whereas the most important one, you guessed it, is the PhpFileProcessor.

But another nice one is the ComposerFileProcessor. The ComposerFileProcessor lets you manipulate composer.json files in your project.
Let´s say you want to define a custom configuration where you want to update the version constraint of some packages.
All you have to do is using the ChangePackageVersionComposerRector:

```php
<?php
// rector.php
declare(strict_types=1);

use Rector\Composer\Rector\ChangePackageVersionComposerRector;
use Rector\Composer\ValueObject\PackageAndVersion;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;

return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ChangePackageVersionComposerRector::class)
->call('configure', [[
// we use constant for keys to save you from typos
ChangePackageVersionComposerRector::PACKAGES_AND_VERSIONS => ValueObjectInliner::inline([
new PackageAndVersion('symfony/yaml', '^5.0'),
]),
]]);
};
```

There are some more rules related to manipulate your composer.json files. Let´s see them in action:

```php
<?php
// rector.php
declare(strict_types=1);

use Rector\Composer\Rector\AddPackageToRequireComposerRector;
use Rector\Composer\Rector\AddPackageToRequireDevComposerRector;
use Rector\Composer\Rector\RemovePackageComposerRector;
use Rector\Composer\Rector\ReplacePackageAndVersionComposerRector;
use Rector\Composer\ValueObject\PackageAndVersion;
use Rector\Composer\ValueObject\ReplacePackageAndVersion;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;

return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();

// Add a package to the require section of your composer.json
$services->set(AddPackageToRequireComposerRector::class)
->call('configure', [[
// we use constant for keys to save you from typos
AddPackageToRequireComposerRector::PACKAGES_AND_VERSIONS => ValueObjectInliner::inline([
new PackageAndVersion('symfony/yaml', '^5.0'),
]),
]]);

// Add a package to the require dev section of your composer.json
$services->set(AddPackageToRequireDevComposerRector::class)
->call('configure', [[
// we use constant for keys to save you from typos
AddPackageToRequireDevComposerRector::PACKAGES_AND_VERSIONS => ValueObjectInliner::inline([
new PackageAndVersion('phpunit/phpunit', '^9.0'),
]),
]]);

// Remove a package from composer.json
$services->set(RemovePackageComposerRector::class)
->call('configure', [[
// we use constant for keys to save you from typos
RemovePackageComposerRector::PACKAGE_NAMES => ['symfony/console']
]]);

// Replace a package in the composer.json
$services->set(ReplacePackageAndVersionComposerRector::class)
->call('configure', [[
// we use constant for keys to save you from typos
ReplacePackageAndVersionComposerRector::REPLACE_PACKAGES_AND_VERSIONS => ValueObjectInliner::inline([
new ReplacePackageAndVersion('vendor1/package2', 'vendor2/package1', '^3.0'),
]),
]]);
};
```

Behind every FileProcessor are one or multiple rules which are in turn implementing a dedicated Interface extending the [RectorInterface](https://github.com/rectorphp/rector-src/blob/main/src/Contract/Rector/RectorInterface.php).
In the case of the ComposerFileProcessor all rules are implementing the [ComposerRectorInterface](https://github.com/rectorphp/rector-src/blob/main/rules/Composer/Contract/Rector/ComposerRectorInterface.php)

Are you eager to create your own one? Dive in and have a look at [How to create a custom FileProcessor](how_to_create_custom_fileprocessor.md)


206 changes: 206 additions & 0 deletions build/target-repository/docs/how_to_create_custom_fileprocessor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
# Create your own custom FileProcessor

This section is all about creating your custom specific FileProcessor.
If you don´t know the concept of FileProcessors in the context of Rector, have a look at [Beyond PHP - Entering the realm of FileProcessors](beyond_php_file_processors.md)

Most of the examples starting with a rather contrived example, let´s do it the same.

Imagine you would like to replace the sentence "Make america great again" to "Make the whole world a better place to be" in every file named bold_statement.txt.

In order to do so, we create the BoldStatementFileProcessor like that:

```php
<?php
namespace MyVendor\MyPackage\FileProcessor;

use Rector\Core\Contract\Processor\FileProcessorInterface;
use Rector\Core\ValueObject\Application\File;

final class BoldStatementFileProcessor implements FileProcessorInterface
{
/**
* @var string
*/
private const OLD_STATEMENT = 'Make america great again';

public function supports(File $file): bool
{
$smartFileInfo = $file->getSmartFileInfo();
return 'bold_statement.txt' === $smartFileInfo->getBasename();
}

/**
* @param File[] $files
*/
public function process(array $files): void
{
foreach ($files as $file) {
$this->processFile($file);
}
}

private function processFile(File $file): void
{
$oldContent = $file->getFileContent();

if(false === strpos($oldContent, self::OLD_STATEMENT)) {
return;
}

$newFileContent = str_replace(self::OLD_STATEMENT, 'Make the whole world a better place to be', $oldContent);
$file->changeFileContent($newFileContent);
}

public function getSupportedFileExtensions(): array
{
return ['txt'];
}
}

```

Now register your FileProcessor in your configuration (actually in the container):

```php
<?php
// rector.php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use MyVendor\MyPackage\FileProcessor\BoldStatementFileProcessor;

return static function (ContainerConfigurator $containerConfigurator): void {
// [...]
$services = $containerConfigurator->services();
$services->set(BoldStatementFileProcessor::class);
};
```

Run rector again and see what happens. Yes, we made the world better.

The astute reader has noticed, that the BoldStatementFileProcessor is not really reusable and easily extendable.
So it would be much better to separate the processing from the actual rule(s).
This is also the best practice in all Rector internal FileProcessors. So, let´s just do that.

Create a new dedicated Interface for our rules used by the BoldStatementFileProcessor. Just call it BoldStatementRectorInterface.

```php
<?php

namespace MyVendor\MyPackage\FileProcessor\Rector;

use Rector\Core\Contract\Rector\RectorInterface;

interface BoldStatementRectorInterface extends RectorInterface
{
public function transform(string $content): string;
}

```

Now, separate the modification from the processing:

```php
<?php

namespace MyVendor\MyPackage\FileProcessor\Rector;
use Rector\Core\ValueObject\Application\File;

final class BoldStatementMakeAmericaGreatAgainRector implements BoldStatementRectorInterface
{
/**
* @var string
*/
private const OLD_STATEMENT = 'Make america great again';

public function transform(string $content): string
{
if(false === strpos($content, self::OLD_STATEMENT)) {
return;
}

return str_replace(self::OLD_STATEMENT, 'Make the whole world a better place to be', $content);
}
}

```

And change our BoldStatementFileProcessor so it is using one or multiple classes implementing the BoldStatementRectorInterface:

```php
<?php

namespace MyVendor\MyPackage\FileProcessor;

use Rector\Core\Contract\Processor\FileProcessorInterface;
use Rector\Core\ValueObject\Application\File;
use MyVendor\MyPackage\FileProcessor\Rector\BoldStatementRectorInterface;

final class BoldStatementFileProcessor implements FileProcessorInterface
{
/**
* @var BoldStatementRectorInterface[]
*/
private $boldStatementRectors;

/**
* @param BoldStatementRectorInterface[] $boldStatementRectors
*/
public function __construct(array $boldStatementRectors)
{
$this->boldStatementRectors = $boldStatementRectors;
}

public function supports(File $file): bool
{
$smartFileInfo = $file->getSmartFileInfo();
return 'bold_statement.txt' === $smartFileInfo->getBasename();
}

/**
* @param File[] $files
*/
public function process(array $files): void
{
foreach ($files as $file) {
$this->processFile($file);
}
}

private function processFile(File $file): void
{
foreach ($this->boldStatementRectors as $boldStatementRector) {
$changeFileContent = $boldStatementRector->transform($file->getFileContent());
$file->changeFileContent($changeFileContent);
}
}

public function getSupportedFileExtensions(): array
{
return ['txt'];
}
}

```

Notice the annotation BoldStatementRectorInterface[]. This is important to inject all active classes implementing the BoldStatementRectorInterface into the BoldStatementFileProcessor.
Yes, we said active. So last but not least we must register our new rule in the container, so it is applied:

```php
<?php
// rector.php

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use MyVendor\MyPackage\FileProcessor\BoldStatementFileProcessor;
use MyVendor\MyPackage\FileProcessor\Rector\BoldStatementMakeAmericaGreatAgainRector;

return static function (ContainerConfigurator $containerConfigurator): void {
// [...]
$services = $containerConfigurator->services();
$services->set(BoldStatementFileProcessor::class);
$services->set(BoldStatementMakeAmericaGreatAgainRector::class);
};
```

Run rector again and yes, we made the world a better place again.

Puh. This was a long ride. But we are done and have our new shiny BoldStatementFileProcessor in place.
Now, it´s up to you, to create something useful. But always keep in mind: Try to make the world a better place to be.

0 comments on commit 25821f6

Please sign in to comment.