* @author Bertrand Chevrier */ trait TokenGenerator { /** * Generates a security token * @param int $length the expected token length * @return string the token * @throws \common_Exception */ protected function generate($length = 40) { try { return bin2hex(random_bytes($length / 2)); } catch (\TypeError $e) { // This is okay, so long as `Error` is caught before `Exception`. throw new \common_Exception("An unexpected error has occurred while trying to generate a security token", 0, $e); } catch (\Error $e) { // This is required, if you do not need to do anything just rethrow. throw new \common_Exception("An unexpected error has occurred while trying to generate a security token", 0, $e); } catch (\Exception $e) { throw new \common_Exception("Could not generate a security token. Is our OS secure?", 0, $e); } } }