本文整理汇总了PHP中Zend\Math\Rand类的典型用法代码示例。如果您正苦于以下问题:PHP Rand类的具体用法?PHP Rand怎么用?PHP Rand使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Rand类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: generateRandomSlug
/**
* Generate a random slug
*
* @param integer $slugLength
* @param string $slugChars
* @return string
*/
public static function generateRandomSlug($slugLength = 10, $slugChars = null)
{
if (!$slugChars) {
$slugChars = 'abcdefghijklmnopqrstuvwxyz';
}
return Rand::getString($slugLength, $slugChars, true);
}
示例2: indexAction
public function indexAction()
{
$this->requireLogin();
$keyRepo = $this->getEntityManager()->getRepository('Frontend\\Api\\Entity\\Key');
$userKey = $keyRepo->findOneBy(array('user' => $this->identity()));
if ($this->getRequest()->getQuery('getKey') == 1 && !$userKey) {
// add to api
$keyChars = array_merge(range(0, 9), range('A', 'Z'), range('a', 'z'));
$apiKey = Rand::getString(50, implode('', $keyChars));
$userKey = new Key();
$userKey->setKey($apiKey);
$userKey->setLimit($userKey->getDefaultRateLimit());
$userKey->setUser($this->getEntityManager()->getReference('Auth\\Entity\\Benutzer', $this->identity()->getId()));
$userKey->setRequests(0);
$userKey->setStatus(1);
try {
$this->getEntityManager()->persist($userKey);
$this->getEntityManager()->flush();
$this->flashMessenger()->addSuccessMessage('Nice! Subscribe to API successfully. Can\'t wait to hear about your application');
} catch (\Exception $e) {
$this->flashMessenger()->addErrorMessage('Balls...something went wrong :/');
}
}
$viewModel = new ViewModel();
$viewModel->setTemplate('/api/index.phtml');
$viewModel->setVariable('userKey', $userKey);
return $viewModel;
}
示例3: addAclResources
/**
* Add acl resources
*
* @param array $resources
* @param boolean $createConnections
* @param integer $userRole
*/
protected function addAclResources($resources, $createConnections = true, $userRole = AclModelBase::DEFAULT_ROLE_MEMBER)
{
// create a test user
$userData = ['nick_name' => Rand::getString(32), 'email' => Rand::getString(32), 'role' => $userRole];
// add member
$query = $this->aclModelBase->insert()->into('user_list')->values($userData);
$statement = $this->aclModelBase->prepareStatementForSqlObject($query);
$statement->execute();
$this->userId = $this->aclModelBase->getAdapter()->getDriver()->getLastGeneratedValue();
// create new resources
foreach ($resources as $resource) {
// add new test resource
$query = $this->aclModelBase->insert()->into('acl_resource')->values(['resource' => $resource, 'module' => 1, 'description' => '']);
$statement = $this->aclModelBase->prepareStatementForSqlObject($query);
$statement->execute();
$resourceId = $this->aclModelBase->getAdapter()->getDriver()->getLastGeneratedValue();
$this->aclResourcesIds[] = $resourceId;
if ($createConnections) {
$query = $this->aclModelBase->insert()->into('acl_resource_connection')->values(['role' => $userRole, 'resource' => $resourceId]);
$statement = $this->aclModelBase->prepareStatementForSqlObject($query);
$statement->execute();
$this->aclResourcesConnections[] = $this->aclModelBase->getAdapter()->getDriver()->getLastGeneratedValue();
}
}
}
示例4: provider
/**
* @return array
*/
public function provider()
{
$dateTime = new \DateTime();
$dateStart = $dateTime->sub(new \DateInterval('P1Y'));
$dateEnd = $dateTime->add(new \DateInterval('P4Y'));
$dateTime = new \DateTime();
$dateStartActual = $dateTime->sub(new \DateInterval('P6M'));
$dateEndActual = $dateTime->add(new \DateInterval('P3Y'));
$contactTest = new ContactTest();
$callTest = new CallTest();
$project = new Project();
$project->setCall($callTest->provider()[0][0]);
$project->setDateStart($dateStart);
$project->setDateEnd($dateEnd);
$project->setDateStartActual($dateStartActual);
$project->setDateEndActual($dateEndActual);
$project->setNumber(Rand::getString(4));
$project->setContact($contactTest->provider()[0][0]);
$project->setSummary('This is the summary');
$project->setDescription('This is the description');
$versionType = new Type();
$versionType->setType('Type');
$versionType->setId(1);
return [[$project, $versionType]];
}
示例5: createAction
/**
*
*/
public function createAction()
{
$isPublic = (bool) ($this->params('public') ?: $this->showPrompt('public'));
$description = $this->params('description') ?: $this->showPrompt('description');
$grantTypes = $this->params('grant-types') ?: $this->showPrompt('grant-types');
$redirectUri = $this->params('redirect-uri') ?: $this->showPrompt('redirect-uri');
$secret = null;
$encryptedSecret = null;
if (!$isPublic) {
$secret = Rand::getString(32);
$encryptedSecret = $this->password->create($secret);
}
if ($grantTypes) {
$grantTypes = explode(',', $grantTypes);
array_walk($grantTypes, function (&$grant) {
$grant = trim($grant);
});
}
$client = new Client(null, $encryptedSecret, null, $grantTypes, $redirectUri, $description);
$this->clientMapper->save($client);
$this->getConsole()->writeLine();
$this->getConsole()->writeLine('* Client created *', Color::GREEN);
if (!$isPublic) {
$this->getConsole()->writeLine('The client secret was auto-generated and encrypted. Please store it safely.');
$this->getConsole()->writeLine("Don't ever disclose the client secret publicly", Color::YELLOW);
$this->getConsole()->writeLine();
}
$this->getConsole()->writeLine("UUID: \t\t" . $client->getUuid());
if (!$isPublic) {
$this->getConsole()->writeLine("Secret: \t" . $secret);
}
$this->getConsole()->writeLine("Grant types: \t" . implode(', ', $client->getGrantTypes()));
$this->getConsole()->writeLine("Description: \t" . $client->getDescription());
$this->getConsole()->writeLine("Redirect URI: \t" . $client->getRedirectUri());
}
示例6: passwordAction
public function passwordAction()
{
$request = $this->getRequest();
// Make sure that we are running in a console and the user has not
// tricked our
// application into running this action from a public web server.
if (!$request instanceof ConsoleRequest) {
throw new \RuntimeException('You can only use this action from a console!');
}
// Get user email from console and check if the user used --verbose or
// -v flag
$userEmail = $request->getParam('userEmail');
$verbose = $request->getParam('verbose');
// reset new password
$newPassword = Rand::getString(16);
$console = Console::getInstance();
if (Confirm::prompt('Is this the correct answer? [y/n]', 'y', 'n')) {
$console->write("You chose YES\n");
} else {
$console->write("You chose NO\n");
}
if (!$verbose) {
return "Done! {$userEmail} has received an email with his new password.\n";
} else {
return "Done! New password for user {$userEmail} is '{$newPassword}'. It has also been emailed to him. \n";
}
}
示例7: testRoleSynchronisation
/**
* Test role synchronisation
*/
public function testRoleSynchronisation()
{
// create a first test ACL role
$query = $this->model->insert()->into('acl_role')->values(['name' => 'test role 1']);
$statement = $this->model->prepareStatementForSqlObject($query);
$statement->execute();
$this->aclRolesIds[] = $this->model->getAdapter()->getDriver()->getLastGeneratedValue();
// create a test user
$query = $this->model->insert()->into('user_list')->values(['nick_name' => Rand::getString(32), 'email' => Rand::getString(32), 'role' => $this->aclRolesIds[0]]);
$statement = $this->model->prepareStatementForSqlObject($query);
$statement->execute();
$this->usersIds[] = $this->model->getAdapter()->getDriver()->getLastGeneratedValue();
// delete the created ACL role
$query = $this->model->delete()->from('acl_role')->where(['id' => $this->aclRolesIds[0]]);
$statement = $this->model->prepareStatementForSqlObject($query);
$statement->execute();
// fire the delete ACL role event
AclEvent::fireDeleteAclRoleEvent($this->aclRolesIds[0]);
// check the created test user's role
$select = $this->model->select();
$select->from('user_list')->columns(['role'])->where(['user_id' => $this->usersIds[0]]);
$statement = $this->model->prepareStatementForSqlObject($select);
$resultSet = new ResultSet();
$result = $resultSet->initialize($statement->execute());
// user must be a default member
$this->assertEquals($result->current()['role'], AclBaseModel::DEFAULT_ROLE_MEMBER);
}
示例8: create
/**
* Bcrypt
*
* @param string $password
* @throws Exception\RuntimeException
* @return string
*/
public function create($password)
{
if (empty($this->salt)) {
$salt = Rand::getBytes(self::MIN_SALT_SIZE);
} else {
$salt = $this->salt;
}
$salt64 = substr(str_replace('+', '.', base64_encode($salt)), 0, 22);
/**
* Check for security flaw in the bcrypt implementation used by crypt()
* @see http://php.net/security/crypt_blowfish.php
*/
if (PHP_VERSION_ID >= 50307 && !$this->backwardCompatibility) {
$prefix = '$2y$';
} else {
$prefix = '$2a$';
// check if the password contains 8-bit character
if (preg_match('/[\\x80-\\xFF]/', $password)) {
throw new Exception\RuntimeException('The bcrypt implementation used by PHP can contain a security flaw ' . 'using password with 8-bit character. ' . 'We suggest to upgrade to PHP 5.3.7+ or use passwords with only 7-bit characters');
}
}
$hash = crypt($password, $prefix . $this->cost . '$' . $salt64);
if (strlen($hash) < 13) {
throw new Exception\RuntimeException('Error during the bcrypt generation');
}
return $hash;
}
示例9: export
public function export()
{
$path = __DIR__ . '/../../../../../../public/xls/';
if (!is_dir($path)) {
throw new \Exception("Please make sure that 'public/xls' directory exists");
}
$fileName = str_replace("/", ".", base64_encode(Rand::getBytes(6, true)) . '_' . date("Y-m-d-H:i:s") . '.xls');
$file = fopen($path . $fileName, "w");
$count = 0;
$html = null;
$html .= "<table>";
$html .= "<tr>";
foreach ($this->headers as $headers) {
$html .= "<th>{$headers}</th>";
}
$html .= "</tr>";
foreach ($this->resultFormatedData as $data) {
foreach ($data as $colunas) {
$count++;
if ($count == 0) {
$html .= "<tr>";
}
$html .= "<td>{$colunas}</td>";
if ($count == count($this->headers)) {
$html .= "</tr>";
$count = 0;
}
}
}
fputs($file, utf8_decode($html));
fclose($file);
return '/xls/' . $fileName;
}
示例10: runAction
public function runAction()
{
$em = $this->getEntityManager();
$console = $this->getServiceLocator()->get('console');
$schemaTool = new \Doctrine\ORM\Tools\SchemaTool($em);
$console->writeLine('建立資料表中, 請稍待!!', ColorInterface::GREEN);
$classes = $em->getMetadataFactory()->getAllMetadata();
if ($this->params()->fromRoute('re-create-database')) {
$schemaTool->dropSchema($classes);
}
$schemaTool->createSchema($classes);
// 安裝預設管理人員及選單
$username = 'admin';
$password = \Zend\Math\Rand::getString(8, null, true);
$user = new \Base\Entity\User();
$user->setUsername($username);
$user->setPassword(\Zend\Ldap\Attribute::createPassword($password));
$user->setDisplayName('管理者');
$user->setRole('admin');
$em->persist($user);
$em->flush();
$menu = new \Base\Entity\Menu();
$menu->setName('首頁');
$menu->setUser($user);
$params = ['max_records' => 10, 'order_kind' => 'desc', 'term' => ''];
$menu->setParams(serialize($params));
$em->persist($menu);
$em->flush();
$console->writeLine('建立完成!!', ColorInterface::GREEN);
$console->writeLine('預設帳號 ' . $username . ', 密碼 ' . $password, ColorInterface::GREEN);
}
示例11: __construct
/**
* @param array $options
*/
public function __construct(array $options = [])
{
(new Hydrator\ClassMethods())->hydrate($options, $this);
$this->updatedAt = new \DateTime('now');
$this->createdAt = new \DateTime('now');
$this->salt = base64_encode(Rand::getBytes(8, true));
$this->activationKey = md5($this->email . $this->salt);
}
示例12: provider
/**
* @return array
*/
public function provider()
{
$gender = new Gender();
$gender->setName(Rand::getString(4));
$gender->setAttention('attention:' . Rand::getString(4));
$gender->setSalutation('This is the salutation');
return [[$gender]];
}
示例13: provider
/**
* @return array
*/
public function provider()
{
$title = new Title();
$title->setName(Rand::getString(4));
$title->setAttention('attention:' . Rand::getString(4));
$title->setSalutation('This is the salutation');
return [[$title]];
}
示例14: generate
/**
* @param int $len
* @return string
* @throws \InvalidArgumentException
*/
public static function generate($len = 32)
{
if ($len > 255) {
throw new \InvalidArgumentException(sprintf("assoc handle len must be lower or equal to 255(%d)", $len));
}
$new_assoc_handle = Rand::getString($len, self::PrintableNonWhitespaceCharacters, true);
return $new_assoc_handle;
}
示例15: provider
/**
* @return array
*/
public function provider()
{
$contentType = new ContentType();
$contentType->setContentType('test/' . Rand::getString(12));
$contentType->setDescription('This is the description ' . Rand::getString(12));
$contentType->setExtension(Rand::getString(4));
return [[$contentType]];
}