Skip to content

Instantly share code, notes, and snippets.

@KEINOS
Last active April 4, 2020 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KEINOS/b72391409f201777f8c4420a59a9c282 to your computer and use it in GitHub Desktop.
Save KEINOS/b72391409f201777f8c4420a59a9c282 to your computer and use it in GitHub Desktop.
<?php
/**
* Sample PHP script to check if a string is available to use in namespace.
*
* View this script in action online:
* https://paiza.io/projects/cjheAXgzbvk4uEq8civKAA
* View this script in Gist:
* https://gist.github.com/KEINOS/b72391409f201777f8c4420a59a9c282
*/
namespace SAMPLE;
echo 'PHP Version: ', phpversion(), PHP_EOL, PHP_EOL;
$list_sample = [
// Available
'FOO',
'FOO_',
'__FOO__',
'Vendor\Package\Valid',
'SAMPLE', // Already user defined namespace but not used
// Not available names
'KEINOS', // Already user defined and used namespace
'isavailablestring', // User defined function name
'stdClass', // Existing class name
'stdclass', // Existing class name
'sort', // Internaly defined function name
'FOO-',
'FOO-BAR',
'$this',
'\KEINOS',
];
foreach($list_sample as $string){
echo \KEINOS\isAvailableNamespace($string) ? 'OK' : 'NG', ': ', $string, PHP_EOL;
}
/*
* =============================================================================
* Functions
* =============================================================================
*/
namespace KEINOS;
function isAvailableNamespace(string $string): bool
{
// Eventhough, class names are case-sensitive, to avoid confusion do NOT allow
// use same class or function name.
$name = strtolower($string);
$defined_names = array_flip(getListNamesUsedInLowerCase());
if(isset($defined_names[$name])){
return false;
}
// Check available characters to use
// Ref:
// - https://stackoverflow.com/questions/41027816/what-are-the-valid-characters-in-php-namespace-names
// - https://www.php.net/manual/en/language.variables.basics.php
return preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff\\\\]*[a-zA-Z0-9_\x7f-\xff]$/', $string);
}
function getListNamesUsedInLowerCase(): array
{
static $result;
if(isset($result)){
return $result;
}
$defined_names = [];
$defined_names += array_flip(get_declared_classes());
$defined_names += array_flip(get_defined_functions()['internal']);
$defined_names += array_flip(get_defined_functions()['user']);
$result = [];
foreach($defined_names as $name => $value){
$name = strtolower($name);
if(strpos($name, '\\') === false){
$result[] = $name;
continue;
}
// Split names with namespace
$split = explode('\\', $name);
$result = array_merge($result, $split);
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment