Sergey Protko
Some stuff
class UserResource{
/**
* Transformer for user resource
* @return array<id: int, name: string, age: int, score: float>
*/
public function default(User $user, Scores $scores) {
return [
'id' => $user->id(), 'name' => $user->name(),
'age' => $user->age(), 'score' => $scores->forUser($user),
];
}
}
class UserResource
{
/**
* Transformer for user resource.
*
* @return array<id: int, name: string, age: int, score: float>
*/
public function default(User $user, Scores $scores)
{
return [
'id' => $user->id(),
'name' => $user->name(),
'age' => $user->age(),
'score' => $scores->forUser($user),
];
}
}
php-cs-fixer, php code sniffer, prettier-php
from Rasmus Lerdorf
Statically typed languages just too verbose
Don't turn PHP into Java!
I don't need type checking, I have tests!
ERROR: UndefinedMethod - 11:1 Method Bar::foo does not exist
Text
function tokenize(string $expression)
{
$groups = ['number', 'operation'];
$regex = '/(?<number>\d+)|(?<operation>[\+\-\*\/]?)|\s+$/';
preg_match_all($regex, $expression, $matches, PREG_SET_ORDER);
$tokens = [];
foreach ($matches as $match) {
/** @var string[] $lexem */
$lexem = array_intersect_key($match, array_flip($groups));
foreach ($groups as $group) {
if (
!isset($lexem[$group])
|| '' === $lexem[$group]
) {
continue;
}
$tokens[] = [
'type' => $group,
'value' => $lexem[$group],
];
}
}
return $tokens;
}
More complicated example...
/**
* @return string[][]
*
* @psalm-return array<int, array{type:string, value:string}>
*/
function tokenize(string $expression): array
{
// ...
/**
* @return string[][]
*
* @psalm-return array<int, array{type:string, value:string}>
*/
function tokenize(string $expression): array
{
// ...
<?php
declare(strict_types=1);
function sum(int $a, int $b): int {
return $a + $b;
}
$tokens = tokenize('2 + 3 * 2');
sum(
$tokens[0]['value'],
$tokens[0]['value']
);
If all types defined...
function processFile(string $content): array
{
// do something with it
}
processFile(
file_get_contents($filePath)
);
Fatal error: Uncaught TypeError: Argument 1 passed to processFile() must be of the type string, boolean given
By Sergey Protko