generated from yiisoft/package-template
-
-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add more specific psalm type for result of
Random::string()
method (#…
…53) * Add more specific psalm type for result of `Random::string()` method * fix typo
- Loading branch information
Showing
2 changed files
with
14 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,12 +4,14 @@ | |
|
||
namespace Yiisoft\Security; | ||
|
||
use Exception; | ||
use InvalidArgumentException; | ||
use Yiisoft\Strings\StringHelper; | ||
|
||
/** | ||
* Random allows generating random values. | ||
* | ||
* Currently it has a single method "string". | ||
* Currently, it has a single method "string". | ||
* The following extras are available via PHP directly: | ||
* | ||
* - `random_bytes()` for bytes. Note that output may not be ASCII. | ||
|
@@ -23,19 +25,25 @@ final class Random | |
* | ||
* @param int $length The length of the key in characters. | ||
* | ||
* @throws \Exception On failure. | ||
* @throws Exception On failure. | ||
* | ||
* @return string The generated random key. | ||
* | ||
* @psalm-return non-empty-string | ||
*/ | ||
public static function string(int $length = 32): string | ||
{ | ||
if ($length < 1) { | ||
throw new \InvalidArgumentException('First parameter ($length) must be greater than 0.'); | ||
throw new InvalidArgumentException('First parameter ($length) must be greater than 0.'); | ||
} | ||
|
||
// Optimization: we can generate a quarter fewer bits to completely cover the desired length in base64 | ||
/** @psalm-suppress ArgumentTypeCoercion */ | ||
/** | ||
* Optimization: we can generate a quarter fewer bits to completely cover the desired length in base64 | ||
* @psalm-suppress ArgumentTypeCoercion | ||
*/ | ||
$bytes = random_bytes((int) ceil($length * 0.75)); | ||
Check warning on line 44 in src/Random.php
|
||
|
||
/** @var non-empty-string */ | ||
return substr(StringHelper::base64UrlEncode($bytes), 0, $length); | ||
} | ||
} |