ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
class.ilRandom.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */
3 
7 class ilRandom
8 {
12  public function __construct()
13  {
14  }
15 
19  private function logIfPossible(callable $c)
20  {
21  global $DIC;
22 
23  if (isset($DIC['ilLoggerFactory'])) {
24  $c($DIC->logger()->rnd());
25  }
26  }
27 
34  public function int($min = null, $max = null)
35  {
36  if (is_null($min)) {
37  $min = 0;
38  }
39  if (is_null($max)) {
40  $max = mt_getrandmax();
41  }
42 
43  if ($this->supportsRandomInt()) {
44  try {
45  return random_int($min, $max);
46  } catch (Exception $e) {
47  $this->logIfPossible(static function (ilLogger $logger) {
48  $logger->logStack(\ilLogLevel::ERROR);
49  $logger->error('No suitable random number generator found.');
50  });
51  throw $e;
52  } catch (Throwable $e) {
53  $this->logIfPossible(static function (ilLogger $logger) {
54  $logger->logStack(\ilLogLevel::ERROR);
55  $logger->error('max should be greater than min.');
56  });
57  throw $e;
58  }
59  }
60  // version 5.6 => use mt_rand
61  return mt_rand($min, $max);
62  }
63 
67  private function supportsRandomInt()
68  {
69  if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
70  return true;
71  }
72  return false;
73  }
74 }
int($min=null, $max=null)
__construct()
ilRandom constructor.
logStack($a_level=null, $a_message='')
log stack trace
global $DIC
Definition: saml.php:7
error($a_message)
logIfPossible(callable $c)
Wrapper for generation of random numbers, strings, bytes.
Component logger with individual log levels by component id.