PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/backend/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Profiler/RedisProfilerStorage.php

https://gitlab.com/x33n/Backbone-Music-Store
PHP | 381 lines | 214 code | 73 blank | 94 comment | 31 complexity | 17d39a18eafb92c87216f08e2aa693f5 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\Profiler;
  11. use Redis;
  12. /**
  13. * RedisProfilerStorage stores profiling information in Redis.
  14. *
  15. * @author Andrej Hudec <pulzarraider@gmail.com>
  16. */
  17. class RedisProfilerStorage implements ProfilerStorageInterface
  18. {
  19. const TOKEN_PREFIX = 'sf_profiler_';
  20. const REDIS_OPT_SERIALIZER = 1;
  21. const REDIS_OPT_PREFIX = 2;
  22. const REDIS_SERIALIZER_NONE = 0;
  23. const REDIS_SERIALIZER_PHP = 1;
  24. protected $dsn;
  25. protected $lifetime;
  26. /**
  27. * @var Redis
  28. */
  29. private $redis;
  30. /**
  31. * Constructor.
  32. *
  33. * @param string $dsn A data source name
  34. * @param string $username Not used
  35. * @param string $password Not used
  36. * @param int $lifetime The lifetime to use for the purge
  37. */
  38. public function __construct($dsn, $username = '', $password = '', $lifetime = 86400)
  39. {
  40. $this->dsn = $dsn;
  41. $this->lifetime = (int) $lifetime;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function find($ip, $url, $limit, $method)
  47. {
  48. $indexName = $this->getIndexName();
  49. if (!$indexContent = $this->getValue($indexName, self::REDIS_SERIALIZER_NONE)) {
  50. return array();
  51. }
  52. $profileList = explode("\n", $indexContent);
  53. $result = array();
  54. foreach ($profileList as $item) {
  55. if ($limit === 0) {
  56. break;
  57. }
  58. if ($item == '') {
  59. continue;
  60. }
  61. list($itemToken, $itemIp, $itemMethod, $itemUrl, $itemTime, $itemParent) = explode("\t", $item, 6);
  62. if ($ip && false === strpos($itemIp, $ip) || $url && false === strpos($itemUrl, $url) || $method && false === strpos($itemMethod, $method)) {
  63. continue;
  64. }
  65. $result[$itemToken] = array(
  66. 'token' => $itemToken,
  67. 'ip' => $itemIp,
  68. 'method' => $itemMethod,
  69. 'url' => $itemUrl,
  70. 'time' => $itemTime,
  71. 'parent' => $itemParent,
  72. );
  73. --$limit;
  74. }
  75. usort($result, function($a, $b) {
  76. if ($a['time'] === $b['time']) {
  77. return 0;
  78. }
  79. return $a['time'] > $b['time'] ? -1 : 1;
  80. });
  81. return $result;
  82. }
  83. /**
  84. * {@inheritdoc}
  85. */
  86. public function purge()
  87. {
  88. // delete only items from index
  89. $indexName = $this->getIndexName();
  90. $indexContent = $this->getValue($indexName, self::REDIS_SERIALIZER_NONE);
  91. if (!$indexContent) {
  92. return false;
  93. }
  94. $profileList = explode("\n", $indexContent);
  95. $result = array();
  96. foreach ($profileList as $item) {
  97. if ($item == '') {
  98. continue;
  99. }
  100. if (false !== $pos = strpos($item, "\t")) {
  101. $result[] = $this->getItemName(substr($item, 0, $pos));
  102. }
  103. }
  104. $result[] = $indexName;
  105. return $this->delete($result);
  106. }
  107. /**
  108. * {@inheritdoc}
  109. */
  110. public function read($token)
  111. {
  112. if (empty($token)) {
  113. return false;
  114. }
  115. $profile = $this->getValue($this->getItemName($token), self::REDIS_SERIALIZER_PHP);
  116. if (false !== $profile) {
  117. $profile = $this->createProfileFromData($token, $profile);
  118. }
  119. return $profile;
  120. }
  121. /**
  122. * {@inheritdoc}
  123. */
  124. public function write(Profile $profile)
  125. {
  126. $data = array(
  127. 'token' => $profile->getToken(),
  128. 'parent' => $profile->getParentToken(),
  129. 'children' => array_map(function ($p) { return $p->getToken(); }, $profile->getChildren()),
  130. 'data' => $profile->getCollectors(),
  131. 'ip' => $profile->getIp(),
  132. 'method' => $profile->getMethod(),
  133. 'url' => $profile->getUrl(),
  134. 'time' => $profile->getTime(),
  135. );
  136. $profileIndexed = false !== $this->getValue($this->getItemName($profile->getToken()));
  137. if ($this->setValue($this->getItemName($profile->getToken()), $data, $this->lifetime, self::REDIS_SERIALIZER_PHP)) {
  138. if (!$profileIndexed) {
  139. // Add to index
  140. $indexName = $this->getIndexName();
  141. $indexRow = implode("\t", array(
  142. $profile->getToken(),
  143. $profile->getIp(),
  144. $profile->getMethod(),
  145. $profile->getUrl(),
  146. $profile->getTime(),
  147. $profile->getParentToken(),
  148. ))."\n";
  149. return $this->appendValue($indexName, $indexRow, $this->lifetime);
  150. }
  151. return true;
  152. }
  153. return false;
  154. }
  155. /**
  156. * Internal convenience method that returns the instance of Redis.
  157. *
  158. * @return Redis
  159. */
  160. protected function getRedis()
  161. {
  162. if (null === $this->redis) {
  163. if (!preg_match('#^redis://(?(?=\[.*\])\[(.*)\]|(.*)):(.*)$#', $this->dsn, $matches)) {
  164. throw new \RuntimeException(sprintf('Please check your configuration. You are trying to use Redis with an invalid dsn "%s". The expected format is "redis://[host]:port".', $this->dsn));
  165. }
  166. $host = $matches[1] ?: $matches[2];
  167. $port = $matches[3];
  168. if (!extension_loaded('redis')) {
  169. throw new \RuntimeException('RedisProfilerStorage requires that the redis extension is loaded.');
  170. }
  171. $redis = new Redis;
  172. $redis->connect($host, $port);
  173. $redis->setOption(self::REDIS_OPT_PREFIX, self::TOKEN_PREFIX);
  174. $this->redis = $redis;
  175. }
  176. return $this->redis;
  177. }
  178. /**
  179. * Set instance of the Redis
  180. *
  181. * @param Redis $redis
  182. */
  183. public function setRedis($redis)
  184. {
  185. $this->redis = $redis;
  186. }
  187. private function createProfileFromData($token, $data, $parent = null)
  188. {
  189. $profile = new Profile($token);
  190. $profile->setIp($data['ip']);
  191. $profile->setMethod($data['method']);
  192. $profile->setUrl($data['url']);
  193. $profile->setTime($data['time']);
  194. $profile->setCollectors($data['data']);
  195. if (!$parent && $data['parent']) {
  196. $parent = $this->read($data['parent']);
  197. }
  198. if ($parent) {
  199. $profile->setParent($parent);
  200. }
  201. foreach ($data['children'] as $token) {
  202. if (!$token) {
  203. continue;
  204. }
  205. if (!$childProfileData = $this->getValue($this->getItemName($token), self::REDIS_SERIALIZER_PHP)) {
  206. continue;
  207. }
  208. $profile->addChild($this->createProfileFromData($token, $childProfileData, $profile));
  209. }
  210. return $profile;
  211. }
  212. /**
  213. * Gets the item name.
  214. *
  215. * @param string $token
  216. *
  217. * @return string
  218. */
  219. private function getItemName($token)
  220. {
  221. $name = $token;
  222. if ($this->isItemNameValid($name)) {
  223. return $name;
  224. }
  225. return false;
  226. }
  227. /**
  228. * Gets the name of the index.
  229. *
  230. * @return string
  231. */
  232. private function getIndexName()
  233. {
  234. $name = 'index';
  235. if ($this->isItemNameValid($name)) {
  236. return $name;
  237. }
  238. return false;
  239. }
  240. private function isItemNameValid($name)
  241. {
  242. $length = strlen($name);
  243. if ($length > 2147483648) {
  244. throw new \RuntimeException(sprintf('The Redis item key "%s" is too long (%s bytes). Allowed maximum size is 2^31 bytes.', $name, $length));
  245. }
  246. return true;
  247. }
  248. /**
  249. * Retrieves an item from the Redis server.
  250. *
  251. * @param string $key
  252. * @param int $serializer
  253. *
  254. * @return mixed
  255. */
  256. private function getValue($key, $serializer = self::REDIS_SERIALIZER_NONE)
  257. {
  258. $redis = $this->getRedis();
  259. $redis->setOption(self::REDIS_OPT_SERIALIZER, $serializer);
  260. return $redis->get($key);
  261. }
  262. /**
  263. * Stores an item on the Redis server under the specified key.
  264. *
  265. * @param string $key
  266. * @param mixed $value
  267. * @param int $expiration
  268. * @param int $serializer
  269. *
  270. * @return Boolean
  271. */
  272. private function setValue($key, $value, $expiration = 0, $serializer = self::REDIS_SERIALIZER_NONE)
  273. {
  274. $redis = $this->getRedis();
  275. $redis->setOption(self::REDIS_OPT_SERIALIZER, $serializer);
  276. return $redis->setex($key, $expiration, $value);
  277. }
  278. /**
  279. * Appends data to an existing item on the Redis server.
  280. *
  281. * @param string $key
  282. * @param string $value
  283. * @param int $expiration
  284. *
  285. * @return Boolean
  286. */
  287. private function appendValue($key, $value, $expiration = 0)
  288. {
  289. $redis = $this->getRedis();
  290. $redis->setOption(self::REDIS_OPT_SERIALIZER, self::REDIS_SERIALIZER_NONE);
  291. if ($redis->exists($key)) {
  292. $redis->append($key, $value);
  293. return $redis->setTimeout($key, $expiration);
  294. }
  295. return $redis->setex($key, $expiration, $value);
  296. }
  297. /**
  298. * Removes the specified keys.
  299. *
  300. * @param array $keys
  301. *
  302. * @return Boolean
  303. */
  304. private function delete(array $keys)
  305. {
  306. return (bool) $this->getRedis()->delete($keys);
  307. }
  308. }