|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
/** |
|
5
|
|
|
* BEdita\Mail |
|
6
|
|
|
*/ |
|
7
|
|
|
namespace BEdita\Mail\Mailer; |
|
8
|
|
|
|
|
9
|
|
|
use BEdita\Core\Model\Entity\User; |
|
10
|
|
|
use Cake\Core\Configure; |
|
11
|
|
|
use Cake\I18n\I18n; |
|
12
|
|
|
use Cake\Mailer\Mailer; |
|
13
|
|
|
use Cake\Utility\Hash; |
|
14
|
|
|
|
|
15
|
|
|
abstract class BaseMailer extends Mailer |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* Site url |
|
19
|
|
|
* |
|
20
|
|
|
* @var string|null |
|
21
|
|
|
*/ |
|
22
|
|
|
protected ?string $siteUrl = null; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Lang used, i.e. `it`, `en` |
|
26
|
|
|
* |
|
27
|
|
|
* @var string|null |
|
28
|
|
|
*/ |
|
29
|
|
|
protected ?string $lang = null; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* {@inheritDoc} |
|
33
|
|
|
* |
|
34
|
|
|
* Set common variables. |
|
35
|
|
|
*/ |
|
36
|
|
|
public function __construct($config) |
|
37
|
|
|
{ |
|
38
|
|
|
parent::__construct($config); |
|
39
|
|
|
|
|
40
|
|
|
$this->siteUrl = (string)Configure::read('Project.siteUrl'); |
|
41
|
|
|
$this->setViewVars('siteUrl', $this->siteUrl); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Set locale and language to use in email. |
|
46
|
|
|
* |
|
47
|
|
|
* @param string $lang The language |
|
48
|
|
|
* @return void |
|
49
|
|
|
*/ |
|
50
|
|
|
public function setLocale(string $lang): void |
|
51
|
|
|
{ |
|
52
|
|
|
$supported = ['it' => 'it_IT', 'en' => 'en_US']; |
|
53
|
|
|
if (!array_key_exists($lang, $supported)) { |
|
54
|
|
|
$this->lang = null; |
|
55
|
|
|
$this->setViewVars('lang', null); |
|
56
|
|
|
|
|
57
|
|
|
return; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
I18n::setLocale($supported[$lang]); |
|
61
|
|
|
$this->lang = $lang; |
|
62
|
|
|
$this->setViewVars(compact('lang')); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* Set locale from user. |
|
67
|
|
|
* First read `user_preferences.preferred_lang` then `nationality`. |
|
68
|
|
|
* Fallback `it`. |
|
69
|
|
|
* |
|
70
|
|
|
* @param \BEdita\Core\Model\Entity\User $user The user |
|
71
|
|
|
* @return void |
|
72
|
|
|
*/ |
|
73
|
|
|
public function setLocaleFromUser(User $user): void |
|
74
|
|
|
{ |
|
75
|
|
|
$lang = (string)Hash::get((array)$user->user_preferences, 'preferred_lang'); |
|
76
|
|
|
if (!empty($lang)) { |
|
77
|
|
|
$this->setLocale($lang); |
|
78
|
|
|
|
|
79
|
|
|
return; |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
$lang = 'it'; |
|
83
|
|
|
$nationality = $user->get('nationality'); |
|
84
|
|
|
if (!empty($nationality) && $nationality !== 'Italy') { |
|
85
|
|
|
$lang = 'en'; |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
|
|
$this->setLocale($lang); |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
|