SessionProfileStorage::makeActiveProfile()   B
last analyzed

Complexity

Conditions 7
Paths 7

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 15
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 29
rs 8.8333
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SixtyEightPublishers\i18n\Storage;
6
7
use Nette\SmartObject;
8
use Nette\Http\Session;
9
use SixtyEightPublishers\i18n\Profile\ActiveProfile;
10
use SixtyEightPublishers\i18n\Profile\ProfileInterface;
11
use SixtyEightPublishers\i18n\Exception\InvalidArgumentException;
12
use SixtyEightPublishers\i18n\Profile\ActiveProfileChangeNotifier;
13
14
final class SessionProfileStorage implements ProfileStorageInterface
15
{
16
	use SmartObject;
17
18
	private const SESSION_SECTION = 'SixtyEightPublishers.Application';
19
20
	/** @var NULL|\SixtyEightPublishers\i18n\Profile\ActiveProfile */
21
	private $profile;
0 ignored issues
show
introduced by
The private property $profile is not used, and could be removed.
Loading history...
22
23
	/** @var \Nette\Http\SessionSection  */
24
	private $session;
25
26
	/** @var \SixtyEightPublishers\i18n\Profile\ActiveProfileChangeNotifier  */
27
	private $notifier;
28
29
	/**
30
	 * @param \Nette\Http\Session                                            $session
31
	 * @param \SixtyEightPublishers\i18n\Profile\ActiveProfileChangeNotifier $notifier
32
	 */
33
	public function __construct(Session $session, ActiveProfileChangeNotifier $notifier)
34
	{
35
		$this->session = $session->getSection(self::SESSION_SECTION);
36
		$this->notifier = $notifier;
37
	}
38
39
	/**
40
	 * {@inheritdoc}
41
	 */
42
	public function makeActiveProfile(ProfileInterface $profile): ActiveProfile
43
	{
44
		$profile = new ActiveProfile($profile, $this->notifier, $this);
45
46
		if ($profile->getName() !== $this->session['profileName']) {
47
			$this->session['profileName'] = $profile->getName();
48
49
			foreach ([ 'profileCountry', 'profileLanguage', 'profileCurrency' ] as $item) {
50
				if (isset($this->session[$item])) {
51
					unset($this->session[$item]);
52
				}
53
			}
54
55
			return $profile;
56
		}
57
58
		foreach ([ 'changeCountry' => 'profileCountry', 'changeLanguage' => 'profileLanguage', 'changeCurrency' => 'profileCurrency'] as $method => $item) {
59
			if (!isset($this->session[$item])) {
60
				continue;
61
			}
62
63
			try {
64
				$profile->{$method}($this->session[$item], FALSE);
65
			} catch (InvalidArgumentException $e) {
66
				trigger_error($e->getMessage());
67
			}
68
		}
69
70
		return $profile;
71
	}
72
73
	/**
74
	 * {@inheritdoc}
75
	 */
76
	public function persistActiveProfile(ActiveProfile $profile): void
77
	{
78
		$this->session['profileName'] = $profile->getName();
79
		$this->session['profileCountry'] = $profile->getCountry();
80
		$this->session['profileLanguage'] = $profile->getLanguage();
81
		$this->session['profileCurrency'] = $profile->getCurrency();
82
	}
83
}
84