Skip to content

Commit

Permalink
Configurable precision for multiply / divide float-string
Browse files Browse the repository at this point in the history
  • Loading branch information
Wirone committed Feb 27, 2022
1 parent d497186 commit 3868f64
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"phpunit/phpunit": "^9.5",
"rector/rector": "^0.12",
"symfony/dependency-injection": "^5.4|^6.0",
"symplify/easy-coding-standard": "^10.0"
"symplify/easy-coding-standard": "^10.0",
"webmozart/assert": "^1.10"
},
"autoload": {
"psr-4": {
Expand Down
15 changes: 13 additions & 2 deletions src/Rule/MultiplyAndDivideByStringRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,19 @@
use PHPStan\Analyser\MutatingScope;
use PHPStan\Type\FloatType;
use PHPStan\Type\ObjectType;
use Rector\Core\Contract\Rector\AllowEmptyConfigurableRectorInterface;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Webmozart\Assert\Assert;

final class MultiplyAndDivideByStringRector extends AbstractRector
final class MultiplyAndDivideByStringRector extends AbstractRector implements AllowEmptyConfigurableRectorInterface
{
public const PRECISION = 'precision';

private int $precision;

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
Expand Down Expand Up @@ -79,7 +85,7 @@ public function refactor(Node $node): ?Node
$firstArg->value = $this->nodeFactory->createFuncCall(
'sprintf',
[
'%.5F',
sprintf('%%.%dF', $this->precision),
$firstArgValue,
]
);
Expand All @@ -91,6 +97,11 @@ public function refactor(Node $node): ?Node
return null;
}

public function configure(array $configuration): void
{
Assert::nullOrInteger($this->precision = $configuration[self::PRECISION] ?? 5);
}

private function shouldSkip(MethodCall $node): bool
{
/** @var ObjectType $executedOn */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@

$services = $containerConfigurator->services();

$services->set(MultiplyAndDivideByStringRector::class);
$services->set(MultiplyAndDivideByStringRector::class)
->configure([
MultiplyAndDivideByStringRector::PRECISION => 5,
]);
};

0 comments on commit 3868f64

Please sign in to comment.