1. Go to this page and download the library: Download wplake/typed library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
wplake / typed example snippets
function getUserAge(array $userData): int
{
return isset($userData['meta']['age']) &&
is_numeric($userData['meta']['age'])
? (int) $userData['meta']['age']
: 0;
}
function upgradeUserById($mixedUserId): void
{
$userId = is_string($mixedUserId) ||
is_numeric($mixedUserId)
? (string) $mixedUserId
: '';
}
function setUserEducation(array $user, string $education): array
{
// such long chain is the only safe way passing PHPStan checks.
if(key_exists('data', $userData) &&
is_array($userData['data']) &&
key_exists('bio', $userData['data']) &&
is_array($userData['data']['bio'])) {
$userData['data']['bio']['education'] = $education;
}
return $userData;
}
use function WPLake\Typed\int;
use function WPLake\Typed\string;
function getUserAge(array $userData): int
{
return int($userData, 'meta.age');
}
function upgradeUserById($mixedUserId): void
{
$userId = string($mixedUserId);
}
function setUserEducation(array $userData, string $education): array
{
// will set only if 'data' and 'bio' keys are present.
$isSet = setItem($userData, 'data.bio.education', $education);
return $userData;
}
string($data, 'some.key', 'Default Value');
use WPLake\Typed\Typed;
Typed::int($data,'key');
use function WPLake\Typed\string;
use WPLake\Typed\Typed;
$string = string($array, 'first.second');
// alternatively, array of keys:
$string = string($array, ['first', 'second',]);
// alternatively, static method:
$string = Typed::string($array, 'first.second');
// custom fallback:
$string = string($array, 'first.second', 'custom default');
use function WPLake\Typed\setItem;
use WPLake\Typed\Typed;
function myFunction(array $unknownKeys): void {
// will set only if 'first' and 'second' keys exist.
$isSet = setItem($unknownKeys, 'first.second.third', 'value');
// alternatively, array of keys
$isSet = Typed::setItem($unknownKeys, ['first', 'second', 'third',], 'value');
// alternatively, static method
$isSet = Typed::setItem($unknownKeys, 'first.second.third', 'value');
return $array;
}
$array = [
'first' => [
// ...
'second' => [
],
],
];
myFunction($array);