PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/app/code/Magento/Persistent/Model/Session.php

https://gitlab.com/crazybutterfly815/magento2
PHP | 424 lines | 191 code | 38 blank | 195 comment | 14 complexity | 9c1700aeae13183af56f88b46daa7ed1 MD5 | raw file
  1. <?php
  2. /**
  3. * Copyright © 2016 Magento. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Persistent\Model;
  7. /**
  8. * Persistent Session Model
  9. *
  10. * @method int getCustomerId()
  11. * @method Session setCustomerId()
  12. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  13. */
  14. class Session extends \Magento\Framework\Model\AbstractModel
  15. {
  16. /**
  17. * Persistent cookie key length
  18. */
  19. const KEY_LENGTH = 50;
  20. /**
  21. * Persistent cookie name
  22. */
  23. const COOKIE_NAME = 'persistent_shopping_cart';
  24. /**
  25. * Fields which model does not save into `info` db field
  26. *
  27. * @var string[]
  28. */
  29. protected $_unserializableFields = [
  30. 'persistent_id',
  31. 'key',
  32. 'customer_id',
  33. 'website_id',
  34. 'info',
  35. 'updated_at',
  36. ];
  37. /**
  38. * If model loads expired sessions
  39. *
  40. * @var bool
  41. */
  42. protected $_loadExpired = false;
  43. /**
  44. * Persistent data
  45. *
  46. * @var \Magento\Persistent\Helper\Data
  47. */
  48. protected $_persistentData;
  49. /**
  50. * Json Helper
  51. *
  52. * @var \Magento\Framework\Json\Helper\Data
  53. */
  54. protected $jsonHelper;
  55. /**
  56. * @var \Magento\Framework\App\Config\ScopeConfigInterface
  57. */
  58. protected $_coreConfig;
  59. /**
  60. * Store manager
  61. *
  62. * @var \Magento\Store\Model\StoreManagerInterface
  63. */
  64. protected $_storeManager;
  65. /**
  66. * Cookie manager
  67. *
  68. * @var \Magento\Framework\Stdlib\CookieManagerInterface
  69. */
  70. protected $_cookieManager;
  71. /**
  72. * Cookie metadata factory
  73. *
  74. * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
  75. */
  76. protected $_cookieMetadataFactory;
  77. /**
  78. * @var \Magento\Framework\Math\Random
  79. */
  80. protected $mathRandom;
  81. /**
  82. * @var \Magento\Framework\Session\Config\ConfigInterface
  83. */
  84. protected $sessionConfig;
  85. /**
  86. * Request
  87. *
  88. * @var \Magento\Framework\App\Request\Http
  89. */
  90. private $request;
  91. /**
  92. * Constructor
  93. *
  94. * @param \Magento\Framework\Model\Context $context
  95. * @param \Magento\Framework\Registry $registry
  96. * @param \Magento\Framework\App\Config\ScopeConfigInterface $coreConfig
  97. * @param \Magento\Framework\Json\Helper\Data $jsonHelper
  98. * @param \Magento\Persistent\Helper\Data $persistentData
  99. * @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
  100. * @param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
  101. * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  102. * @param \Magento\Framework\Math\Random $mathRandom
  103. * @param \Magento\Framework\Session\Config\ConfigInterface $sessionConfig
  104. * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
  105. * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
  106. * @param array $data
  107. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  108. */
  109. public function __construct(
  110. \Magento\Framework\Model\Context $context,
  111. \Magento\Framework\Registry $registry,
  112. \Magento\Framework\App\Config\ScopeConfigInterface $coreConfig,
  113. \Magento\Framework\Json\Helper\Data $jsonHelper,
  114. \Magento\Persistent\Helper\Data $persistentData,
  115. \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
  116. \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory,
  117. \Magento\Store\Model\StoreManagerInterface $storeManager,
  118. \Magento\Framework\Math\Random $mathRandom,
  119. \Magento\Framework\Session\Config\ConfigInterface $sessionConfig,
  120. \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
  121. \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
  122. array $data = []
  123. ) {
  124. $this->jsonHelper = $jsonHelper;
  125. $this->_persistentData = $persistentData;
  126. $this->_coreConfig = $coreConfig;
  127. $this->_cookieManager = $cookieManager;
  128. $this->_cookieMetadataFactory = $cookieMetadataFactory;
  129. $this->_storeManager = $storeManager;
  130. $this->sessionConfig = $sessionConfig;
  131. $this->mathRandom = $mathRandom;
  132. parent::__construct($context, $registry, $resource, $resourceCollection, $data);
  133. }
  134. /**
  135. * Define resource model
  136. *
  137. * @return void
  138. * @codeCoverageIgnore
  139. */
  140. protected function _construct()
  141. {
  142. $this->_init(\Magento\Persistent\Model\ResourceModel\Session::class);
  143. }
  144. /**
  145. * Set if load expired persistent session
  146. *
  147. * @param bool $loadExpired
  148. * @return $this
  149. * @codeCoverageIgnore
  150. */
  151. public function setLoadExpired($loadExpired = true)
  152. {
  153. $this->_loadExpired = $loadExpired;
  154. return $this;
  155. }
  156. /**
  157. * Get if model loads expired sessions
  158. *
  159. * @return bool
  160. * @SuppressWarnings(PHPMD.BooleanGetMethodName)
  161. */
  162. public function getLoadExpired()
  163. {
  164. return $this->_loadExpired;
  165. }
  166. /**
  167. * Get date-time before which persistent session is expired
  168. *
  169. * @param int|string|\Magento\Store\Model\Store $store
  170. * @return string
  171. * @codeCoverageIgnore
  172. */
  173. public function getExpiredBefore($store = null)
  174. {
  175. return gmdate('Y-m-d H:i:s', time() - $this->_persistentData->getLifeTime($store));
  176. }
  177. /**
  178. * Serialize info for Resource Model to save
  179. * For new model check and set available cookie key
  180. *
  181. * @return $this
  182. */
  183. public function beforeSave()
  184. {
  185. parent::beforeSave();
  186. // Setting info
  187. $info = [];
  188. foreach ($this->getData() as $index => $value) {
  189. if (!in_array($index, $this->_unserializableFields)) {
  190. $info[$index] = $value;
  191. }
  192. }
  193. $this->setInfo($this->jsonHelper->jsonEncode($info));
  194. if ($this->isObjectNew()) {
  195. $this->setWebsiteId($this->_storeManager->getStore()->getWebsiteId());
  196. // Setting cookie key
  197. do {
  198. $this->setKey($this->mathRandom->getRandomString(self::KEY_LENGTH));
  199. } while (!$this->getResource()->isKeyAllowed($this->getKey()));
  200. }
  201. return $this;
  202. }
  203. /**
  204. * Set model data from info field
  205. *
  206. * @return $this
  207. */
  208. protected function _afterLoad()
  209. {
  210. parent::_afterLoad();
  211. $info = null;
  212. if ($this->getInfo()) {
  213. $info = $this->jsonHelper->jsonDecode($this->getInfo());
  214. }
  215. if (is_array($info)) {
  216. foreach ($info as $key => $value) {
  217. $this->setData($key, $value);
  218. }
  219. }
  220. return $this;
  221. }
  222. /**
  223. * Get persistent session by cookie key
  224. *
  225. * @param string $key
  226. * @return $this
  227. */
  228. public function loadByCookieKey($key = null)
  229. {
  230. if (null === $key) {
  231. $key = $this->_cookieManager->getCookie(self::COOKIE_NAME);
  232. }
  233. if ($key) {
  234. $this->load($key, 'key');
  235. }
  236. return $this;
  237. }
  238. /**
  239. * Load session model by specified customer id
  240. *
  241. * @param int $id
  242. * @return $this
  243. * @codeCoverageIgnore
  244. */
  245. public function loadByCustomerId($id)
  246. {
  247. return $this->load($id, 'customer_id');
  248. }
  249. /**
  250. * Delete customer persistent session by customer id
  251. *
  252. * @param int $customerId
  253. * @param bool $clearCookie
  254. * @return $this
  255. */
  256. public function deleteByCustomerId($customerId, $clearCookie = true)
  257. {
  258. if ($clearCookie) {
  259. $this->removePersistentCookie();
  260. }
  261. $this->getResource()->deleteByCustomerId($customerId);
  262. return $this;
  263. }
  264. /**
  265. * Remove persistent cookie
  266. *
  267. * @return $this
  268. * @api
  269. */
  270. public function removePersistentCookie()
  271. {
  272. $cookieMetadata = $this->_cookieMetadataFactory->createSensitiveCookieMetadata()
  273. ->setPath($this->sessionConfig->getCookiePath());
  274. $this->_cookieManager->deleteCookie(self::COOKIE_NAME, $cookieMetadata);
  275. return $this;
  276. }
  277. /**
  278. * Set persistent cookie
  279. *
  280. * @param int $duration Time in seconds.
  281. * @param string $path
  282. * @return $this
  283. * @api
  284. */
  285. public function setPersistentCookie($duration, $path)
  286. {
  287. $value = $this->getKey();
  288. $this->setCookie($value, $duration, $path);
  289. return $this;
  290. }
  291. /**
  292. * Postpone cookie expiration time if cookie value defined
  293. *
  294. * @param int $duration Time in seconds.
  295. * @param string $path
  296. * @return $this
  297. */
  298. public function renewPersistentCookie($duration, $path)
  299. {
  300. if ($duration === null) {
  301. return $this;
  302. }
  303. $value = $this->_cookieManager->getCookie(self::COOKIE_NAME);
  304. if (null !== $value) {
  305. $this->setCookie($value, $duration, $path);
  306. }
  307. return $this;
  308. }
  309. /**
  310. * Delete expired persistent sessions for the website
  311. *
  312. * @param null|int $websiteId
  313. * @return $this
  314. */
  315. public function deleteExpired($websiteId = null)
  316. {
  317. if ($websiteId === null) {
  318. $websiteId = $this->_storeManager->getStore()->getWebsiteId();
  319. }
  320. $lifetime = $this->_coreConfig->getValue(
  321. \Magento\Persistent\Helper\Data::XML_PATH_LIFE_TIME,
  322. 'website',
  323. intval($websiteId)
  324. );
  325. if ($lifetime) {
  326. $this->getResource()->deleteExpired($websiteId, gmdate('Y-m-d H:i:s', time() - $lifetime));
  327. }
  328. return $this;
  329. }
  330. /**
  331. * Delete 'persistent' cookie
  332. *
  333. * @return $this
  334. * @codeCoverageIgnore
  335. */
  336. public function afterDeleteCommit()
  337. {
  338. $this->removePersistentCookie();
  339. return parent::afterDeleteCommit();
  340. }
  341. /**
  342. * Set persistent shopping cart cookie.
  343. *
  344. * @param string $value
  345. * @param int $duration
  346. * @param string $path
  347. * @return void
  348. */
  349. private function setCookie($value, $duration, $path)
  350. {
  351. $publicCookieMetadata = $this->_cookieMetadataFactory->createPublicCookieMetadata()
  352. ->setDuration($duration)
  353. ->setPath($path)
  354. ->setSecure($this->getRequest()->isSecure())
  355. ->setHttpOnly(true);
  356. $this->_cookieManager->setPublicCookie(
  357. self::COOKIE_NAME,
  358. $value,
  359. $publicCookieMetadata
  360. );
  361. }
  362. /**
  363. * Get request object
  364. *
  365. * @return \Magento\Framework\App\Request\Http
  366. * @deprecated
  367. */
  368. private function getRequest()
  369. {
  370. if ($this->request == null) {
  371. $this->request = \Magento\Framework\App\ObjectManager::getInstance()
  372. ->get(\Magento\Framework\App\Request\Http::class);
  373. }
  374. return $this->request;
  375. }
  376. /**
  377. * Set `updated_at` to be always changed
  378. *
  379. * @return $this
  380. */
  381. public function save()
  382. {
  383. $this->setUpdatedAt(gmdate('Y-m-d H:i:s'));
  384. return parent::save();
  385. }
  386. }