Passed
Push — main ( 14ab13...6331ec )
by Sammy
05:53
created

Lezer.php (3 issues)

Labels
Severity
1
<?php
2
/*
3
 * i18n class called Lezer, shorthand L
4
 * honnors Ludwik *Lejzer* Zamenhof (Polish: Ludwik Łazarz Zamenhof; 15 December [O.S. 3 December] 1859 – 14 April [O.S. 1 April] 1917),
5
 * a medical doctor, inventor, and writer; most widely known for creating Esperanto.
6
 *
7
 * also Lezer is dutch for Reader, and it sounds like LASER, which is kinda cool.
8
 */
9
namespace HexMakina\Lezer;
10
11
use \HexMakina\LocalFS\FileSystem;
12
use \HexMakina\Format\Tempo\{Dato,DatoTempo,Tempo};
0 ignored issues
show
The type HexMakina\Format\Tempo\Dato was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
The type HexMakina\Format\Tempo\DatoTempo was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
The type HexMakina\Format\Tempo\Tempo was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
14
class Lezer extends \i18n{
15
16
  private $detected_language_files = [];
17
  private $detected_language_env = [];
18
19
  // protected $basePath = 'locale';
20
  // protected $filePath = 'locale/{LANGUAGE}/user_interface.ini'; // uses gettext hierarchy
21
  // protected $cachePath = 'locale/cache/';
22
  // protected $fallbackLang = 'fra';  // uses ISO-639-3
23
  protected $currentLang = null;
24
25
  public function one_language()
26
  {
27
    $this->detect_language_files();
28
    $this->detect_language_env();
29
    $the_one_language = current(array_intersect($this->detect_language_files(), $this->detect_language_env()));
30
31
    if($the_one_language)
32
      $this->setForcedLang($the_one_language);
33
34
    return $the_one_language;
35
  }
36
37
  public function detect_language_files()
38
  {
39
    $files = FileSystem::preg_scandir(dirname($this->filePath), '/.json$/');
40
    if(empty($files))
41
      return [];
42
43
    $files = implode('',$files);
44
    $res = preg_match_all('/([a-z]{3})\.json/', $files, $m);
45
    if($res) // false or 0 is none found
46
      $this->detected_language_files = $m[1];
47
    return $this->detected_language_files;
48
  }
49
50
  /**
51
   * getUserLangs()
52
   * Returns the user languages
53
   * Normally it returns an array like this:
54
   * 1. Forced language
55
   * 2. Language in $_GET['lang']
56
   * 3. Language in $_SESSION['lang']
57
   * 4. COOKIE
58
   * 5. Fallback language
59
   * Note: duplicate values are deleted.
60
   *
61
   * @return array with the user languages sorted by priority.
62
   */
63
  public function detect_language_env() {
64
      $userLangs = array();
65
66
      // 1. forced language
67
      if ($this->forcedLang != NULL) {
68
          $userLangs['forced'] = $this->forcedLang;
69
      }
70
71
      // 2. GET parameter 'lang'
72
      if (isset($_GET['lang']) && is_string($_GET['lang'])) {
73
          $userLangs['get'] = $_GET['lang'];
74
      }
75
76
      // 3. SESSION parameter 'lang'
77
      if (isset($_SESSION['lang']) && is_string($_SESSION['lang'])) {
78
          $userLangs['session'] = $_SESSION['lang'];
79
      }
80
81
      // 4. COOKIES
82
      if (isset($_COOKIE['lang']) && is_string($_COOKIE['lang'])) {
83
          $userLangs['cookie'] = $_COOKIE['lang'];
84
      }
85
86
      // Lowest priority: fallback
87
      $userLangs['fallback'] = $this->fallbackLang;
88
      // remove duplicate elements
89
      $userLangs = array_unique($userLangs);
90
91
      // remove illegal userLangs
92
      foreach ($userLangs as $key => $value) {
93
          // only allow a-z, A-Z and 0-9 and _ and -
94
          if (preg_match('/^[a-zA-Z0-9_-]*$/', $value) === 1)
95
              $this->detected_language_env[$key] = $value;
96
      }
97
98
      return $this->detected_language_env;
99
  }
100
101
102
  public static function model_type_to_label($form_model)
103
  {
104
    return L(sprintf('MODEL_%s_INSTANCE',get_class($form_model)::model_type()));
105
  }
106
  public static function field_name_to_label($form_model, $field_name)
107
  {
108
    return L(sprintf('MODEL_%s_FIELD_%s',(get_class($form_model))::model_type(), $field_name));
109
  }
110
111
  // options['decimals'] = int
112
  // options['abbrev'] = mixed: key needs to be set
113
  public static function when($event, $options=[])
114
  {
115
    try {
116
      $amount_of_days = DatoTempo::days_diff(new \DateTime($event), new \DateTime());
117
118
    } catch (\Exception $e) {
119
      return __FUNCTION__.': error';
120
    }
121
122
    if($amount_of_days === -1)
123
      return L('DATETIME_RANGE_YESTERDAY');
124
    elseif($amount_of_days === 0)
125
      return L('DATETIME_RANGE_TODAY');
126
    elseif($amount_of_days === 1)
127
      return L('DATETIME_RANGE_TOMORROW');
128
129
130
    $datetime_parts = [
131
      'y' => 'DATETIME_UNIT_YEAR',
132
      'm' => 'DATETIME_UNIT_MONTH',
133
      'w' => 'DATETIME_UNIT_WEEK',
134
      'd' => 'DATETIME_UNIT_DAY',
135
      'h' => 'DATETIME_UNIT_HOUR',
136
      'i' => 'DATETIME_UNIT_MINUTE',
137
      's' => 'DATETIME_UNIT_SECOND'
138
    ];
139
140
    $date_diff = DatoTempo::days_diff_in_parts(abs($amount_of_days));
141
    $ordering = [];
142
    foreach($datetime_parts as $unit => $label)
143
    {
144
      if(!isset($date_diff[$unit]))
145
        continue;
146
147
      $qty = (int)$date_diff[$unit];
148
149
      if($qty === 0)
150
        continue;
151
152
      if(isset($options['abbrev']))
153
        $label.= '_ABBREV';
154
      elseif($qty > 1)
155
        $label.= '_PLURAL';
156
157
      $ordering[$unit] = $qty.' '.L($label).'.';
158
    }
159
    $ret = (isset($amount_of_days) && $amount_of_days >= 0) ? L('DATETIME_RANGE_PREFIX_FUTURE') : L('DATETIME_RANGE_PREFIX_PAST');
160
    $ret.= ' '.implode(' & ', array_slice($ordering, 0,2));
161
162
    return $ret;
163
  }
164
165
  public static function time($time_string, $short=true)
166
  {
167
    if ($short === true)
168
      $time_string = substr($time_string, 0, 5);
169
    return $time_string;
170
  }
171
172
  public static function human_date($date_string, $short=true)
173
  {
174
    if($date_string === '0000-00-00' || empty($date_string))
175
      return L('MODEL_common_VALUE_EMPTY');
176
177
    if(preg_match('/^[0-9]{4}$/', $date_string) === 1)
178
      return intval($date_string);
179
180
    list($year, $month, $day) = explode('-',$date_string);
181
182
    $ret = intval($day).' '.L("DATETIME_CALENDAR_MONTH_$month");
183
184
    if($short === true && Dato::format(null, 'Y') === $year)
185
      return $ret;
186
    else
187
      return "$ret $year";
188
  }
189
190
  public static function human_month($date_string)
191
  {
192
    return L('DATETIME_CALENDAR_MONTH_'.Dato::format($date_string, 'm'));
193
  }
194
195
  public static function human_day($date_string)
196
  {
197
    return L('DATETIME_CALENDAR_DAY_'.Dato::format($date_string, 'N'));
198
  }
199
200
  public static function human_seconds($seconds)
201
  {
202
    $hours = floor($seconds / 3600);
203
    $mins = floor(($seconds-$hours*3600) / 60);
204
    $secs = floor($seconds % 60);
205
206
    $hours_format ='%dh %dm %ds';
207
    return sprintf($hours_format, $hours, $mins, $secs);
208
  }
209
210
211
}
212
213
?>
214