- assert: documentation ( source)
- implode: documentation ( source)
- sprintf: documentation ( source)
<?php
function getGreeting(MapInterface $user): string
{
$fullName = [];
$fullNameSegments = ['first_name', 'last_name'];
foreach ($fullNameSegments as $segment) {
if ($user->has($segment)) {
$fullName[] = $user->get($segment);
}
}
return implode(' ', $fullName);
}
interface MapInterface
{
public function get(string $key);
public function has(string $key): bool;
}
class Map implements MapInterface
{
protected $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function get(string $key)
{
if (!array_key_exists($key, $this->data)) {
throw new RangeException(sprintf('Key %1$s not found', $key));
}
return $this->data[$key];
}
public function has(string $key): bool
{
return array_key_exists($key, $this->data);
}
}
$user = new Map([
'first_name' => 'Xedin',
'last_name' => 'Unknown',
'id' => '12345',
]);
assert($user instanceof MapInterface);
echo getGreeting($user);