sqrl-2.0.0-rc1/src/StringManipulation.php
src/StringManipulation.php
<?php
namespace Drupal\sqrl;
/**
* Trait to provide generic string manipulation methods.
*/
trait StringManipulation {
/**
* Gets some random bytes.
*
* @param int $length
* Length of the password to be generated.
*
* @return string
* The random bytes.
*/
protected function randomBytes(int $length): string {
$randomBytes = '';
try {
$randomBytes = random_bytes($length);
}
catch (\Exception) {
// @todo Error handling.
}
return $randomBytes;
}
/**
* Returns a URL safe base64 encoded version of the string.
*
* @param string $string
* The string to encode.
*
* @return string
* The encoded string.
*/
protected function base64Encode(string $string): string {
$data = base64_encode($string);
// Modify the output so it's safe to use in URLs.
return strtr($data, ['+' => '-', '/' => '_', '=' => '']);
}
/**
* Returns the base64 decoded version of the URL safe string.
*
* @param string $string
* The string to decode.
*
* @return string
* The decoded string.
*/
protected function base64Decode(string $string): string {
$data = strtr($string, ['-' => '+', '_' => '/']);
return base64_decode($data);
}
}
