minor #32006 Fix binary operation +, - or * on string by type casting to integer (steef)

This PR was submitted for the 4.3 branch but it was merged into the 3.4 branch instead (closes #32006).

Discussion
----------

Fix binary operation `+`, `-` or `*` on string by type casting to integer

| Q             | A
| ------------- | ---
| Branch?       | 4.3 for bug fixes <!-- see below -->
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| License       | MIT

# Description
After playing around with [PHPStan](https://github.com/phpstan/phpstan) I found potential improvements when we try to add, subtract or multiply on a string by type casting these values to integers. PHPStan has 8 different [levels](https://github.com/phpstan/phpstan#rule-levels) of strictness and these errors come up after level 2.

## Screenshot example
### Old ️
<img width="876" alt="Screenshot 2019-06-12 at 11 49 22" src="https://user-images.githubusercontent.com/34915382/59435551-2bea0280-8dee-11e9-8eb2-954d34973382.png">

### New 
<img width="876" alt="Screenshot 2019-06-12 at 11 48 54" src="https://user-images.githubusercontent.com/34915382/59435562-30aeb680-8dee-11e9-806d-d37985096363.png">

## How to test
1. Require PHPStan in [Composer](https://getcomposer.org/):
```
composer require --dev phpstan/phpstan
```
2. Create the following `phpstan.neon` [config](https://github.com/phpstan/phpstan#configuration) file:
```
parameters:
    excludes_analyse:
        - 'src/Symfony/Component/Form/Tests'
        - 'src/Symfony/Component/Cache/Tests'
        - 'src/Symfony/Component/DomCrawler/Tests'
        - 'src/Symfony/Component/HttpKernel/Tests'
        - 'src/Symfony/Component/PropertyAccess/Tests'
        - 'src/Symfony/Component/Routing/Tests'
        - 'src/Symfony/Component/Validator/Tests'
        - 'src/Symfony/Component/HttpKernel/Tests'
```
3. Comment out line 202-204 of the following file:
```
src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php
```
4. Analyse the project and search for binary operation errors by running:
```
vendor/bin/phpstan analyse src --level 2 -c phpstan.neon | grep --context=5 "Binary operation"
```
> Keep in mind that four errors will still popup. Three are for `+=` or `+` on arrays and the other one is  about `.` between an interface and empty array which in my opinion can't be improved.

Commits
-------

d445465ef4 Fix binary operation `+`, `-` or `*` on string
This commit is contained in:
Fabien Potencier 2019-06-13 17:39:38 +02:00
commit 27316a4206
9 changed files with 10 additions and 10 deletions

View File

@ -21,7 +21,7 @@ class BirthdayType extends AbstractType
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefault('years', range(date('Y') - 120, date('Y')));
$resolver->setDefault('years', range((int) date('Y') - 120, date('Y')));
$resolver->setAllowedTypes('years', 'array');
}

View File

@ -256,7 +256,7 @@ class DateType extends AbstractType
};
$resolver->setDefaults([
'years' => range(date('Y') - 5, date('Y') + 5),
'years' => range((int) date('Y') - 5, (int) date('Y') + 5),
'months' => range(1, 12),
'days' => range(1, 31),
'widget' => 'choice',

View File

@ -707,7 +707,7 @@ class Response
return (int) $age;
}
return max(time() - $this->getDate()->format('U'), 0);
return max(time() - (int) $this->getDate()->format('U'), 0);
}
/**
@ -788,7 +788,7 @@ class Response
}
if (null !== $this->getExpires()) {
return $this->getExpires()->format('U') - $this->getDate()->format('U');
return (int) $this->getExpires()->format('U') - (int) $this->getDate()->format('U');
}
}

View File

@ -85,7 +85,7 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
$this->storeRelativeAgeDirective('s-maxage', $response->headers->getCacheControlDirective('s-maxage') ?: $response->headers->getCacheControlDirective('max-age'), $age);
$expires = $response->getExpires();
$expires = null !== $expires ? $expires->format('U') - $response->getDate()->format('U') : null;
$expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
$this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0);
}

View File

@ -25,7 +25,7 @@ class DayOfYearTransformer extends Transformer
*/
public function format(\DateTime $dateTime, $length)
{
$dayOfYear = $dateTime->format('z') + 1;
$dayOfYear = (int) $dateTime->format('z') + 1;
return $this->padLeft($dayOfYear, $length);
}

View File

@ -315,7 +315,7 @@ class FullTransformer
preg_match_all($this->regExp, $this->pattern, $matches);
if (\in_array('yy', $matches[0])) {
$dateTime->setTimestamp(time());
$year = $year > $dateTime->format('y') + 20 ? 1900 + $year : 2000 + $year;
$year = $year > (int) $dateTime->format('y') + 20 ? 1900 + $year : 2000 + $year;
}
$dateTime->setDate($year, $month, $day);

View File

@ -120,7 +120,7 @@ class IssnValidator extends ConstraintValidator
for ($i = 0; $i < 7; ++$i) {
// Multiply the first digit by 8, the second by 7, etc.
$checkSum += (8 - $i) * $canonical[$i];
$checkSum += (8 - $i) * (int) $canonical[$i];
}
if (0 !== $checkSum % 11) {

View File

@ -83,7 +83,7 @@ class LuhnValidator extends ConstraintValidator
// ^ ^ ^ ^ ^
// = 1+8 + 4 + 6 + 1+6 + 2
for ($i = $length - 2; $i >= 0; $i -= 2) {
$checkSum += array_sum(str_split($value[$i] * 2));
$checkSum += array_sum(str_split((int) $value[$i] * 2));
}
if (0 === $checkSum || 0 !== $checkSum % 10) {

View File

@ -95,7 +95,7 @@ class DateCaster
if (3 === $i) {
$now = new \DateTimeImmutable();
$dates[] = sprintf('%s more', ($end = $p->getEndDate())
? ceil(($end->format('U.u') - $d->format('U.u')) / ($now->add($p->getDateInterval())->format('U.u') - $now->format('U.u')))
? ceil(($end->format('U.u') - $d->format('U.u')) / ((int) $now->add($p->getDateInterval())->format('U.u') - (int) $now->format('U.u')))
: $p->recurrences - $i
);
break;