1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Bridges\HttpDI;
9:
10: use Nette;
11:
12:
13: 14: 15:
16: class SessionExtension extends Nette\DI\CompilerExtension
17: {
18: public $defaults = [
19: 'debugger' => false,
20: 'autoStart' => 'smart',
21: 'expiration' => null,
22: ];
23:
24:
25: private $debugMode;
26:
27:
28: private $cliMode;
29:
30:
31: public function __construct($debugMode = false, $cliMode = false)
32: {
33: $this->debugMode = $debugMode;
34: $this->cliMode = $cliMode;
35: }
36:
37:
38: public function loadConfiguration()
39: {
40: $builder = $this->getContainerBuilder();
41: $config = $this->getConfig() + $this->defaults;
42: $this->setConfig($config);
43:
44: $session = $builder->addDefinition($this->prefix('session'))
45: ->setFactory(Nette\Http\Session::class);
46:
47: if ($config['expiration']) {
48: $session->addSetup('setExpiration', [$config['expiration']]);
49: }
50: if (isset($config['cookieDomain']) && $config['cookieDomain'] === 'domain') {
51: $config['cookieDomain'] = $builder::literal('$this->getByType(Nette\Http\IRequest::class)->getUrl()->getDomain(2)');
52: }
53: if (isset($config['cookieSecure']) && $config['cookieSecure'] === 'auto') {
54: $config['cookieSecure'] = $builder::literal('$this->getByType(Nette\Http\IRequest::class)->isSecured()');
55: }
56:
57: if ($this->debugMode && $config['debugger']) {
58: $session->addSetup('@Tracy\Bar::addPanel', [
59: new Nette\DI\Statement(Nette\Bridges\HttpTracy\SessionPanel::class),
60: ]);
61: }
62:
63: unset($config['expiration'], $config['autoStart'], $config['debugger']);
64: if (!empty($config)) {
65: $session->addSetup('setOptions', [$config]);
66: }
67:
68: if ($this->name === 'session') {
69: $builder->addAlias('session', $this->prefix('session'));
70: }
71: }
72:
73:
74: public function afterCompile(Nette\PhpGenerator\ClassType $class)
75: {
76: if ($this->cliMode) {
77: return;
78: }
79:
80: $initialize = $class->getMethod('initialize');
81: $config = $this->getConfig();
82: $name = $this->prefix('session');
83:
84: if ($config['autoStart'] === 'smart') {
85: $initialize->addBody('$this->getService(?)->exists() && $this->getService(?)->start();', [$name, $name]);
86:
87: } elseif ($config['autoStart']) {
88: $initialize->addBody('$this->getService(?)->start();', [$name]);
89: }
90: }
91: }
92: