ILIAS  release_5-3 Revision v5.3.23-19-g915713cf615
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  private $logger = null;
13 
17  public function __construct()
18  {
19  }
20 
24  private function logIfPossible(callable $c)
25  {
26  global $DIC;
27 
28  if (isset($DIC['ilLoggerFactory'])) {
29  $c($DIC->logger()->rnd());
30  }
31  }
32 
39  public function int($min = null, $max = null)
40  {
41  if(is_null($min)) {
42  $min = 0;
43  }
44  if(is_null($max)) {
45  $max = mt_getrandmax();
46  }
47 
48  if($this->supportsRandomInt()) {
49  try {
50  return random_int($min, $max);
51  } catch (Exception $e) {
52  $this->logIfPossible(static function (ilLogger $logger) {
53  $logger->logStack(\ilLogLevel::ERROR);
54  $logger->error('No suitable random number generator found.');
55  });
56  throw $e;
57  } catch (Throwable $e) {
58  $this->logIfPossible(static function (ilLogger $logger) {
59  $logger->logStack(\ilLogLevel::ERROR);
60  $logger->error('max should be greater than min.');
61  });
62  throw $e;
63  }
64  }
65  // version 5.6 => use mt_rand
66  return mt_rand($min, $max);
67  }
68 
72  private function supportsRandomInt()
73  {
74  if(version_compare(PHP_VERSION , '7.0.0', '>=')) {
75  return true;
76  }
77  return false;
78  }
79 
80 }
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.