MemcachedCaster.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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\VarDumper\Caster;
  11. use Symfony\Component\VarDumper\Cloner\Stub;
  12. /**
  13. * @author Jan Schädlich <jan.schaedlich@sensiolabs.de>
  14. *
  15. * @final since Symfony 4.4
  16. */
  17. class MemcachedCaster
  18. {
  19. private static $optionConstants;
  20. private static $defaultOptions;
  21. public static function castMemcached(\Memcached $c, array $a, Stub $stub, $isNested)
  22. {
  23. $a += [
  24. Caster::PREFIX_VIRTUAL.'servers' => $c->getServerList(),
  25. Caster::PREFIX_VIRTUAL.'options' => new EnumStub(
  26. self::getNonDefaultOptions($c)
  27. ),
  28. ];
  29. return $a;
  30. }
  31. private static function getNonDefaultOptions(\Memcached $c): array
  32. {
  33. self::$defaultOptions = self::$defaultOptions ?? self::discoverDefaultOptions();
  34. self::$optionConstants = self::$optionConstants ?? self::getOptionConstants();
  35. $nonDefaultOptions = [];
  36. foreach (self::$optionConstants as $constantKey => $value) {
  37. if (self::$defaultOptions[$constantKey] !== $option = $c->getOption($value)) {
  38. $nonDefaultOptions[$constantKey] = $option;
  39. }
  40. }
  41. return $nonDefaultOptions;
  42. }
  43. private static function discoverDefaultOptions(): array
  44. {
  45. $defaultMemcached = new \Memcached();
  46. $defaultMemcached->addServer('127.0.0.1', 11211);
  47. $defaultOptions = [];
  48. self::$optionConstants = self::$optionConstants ?? self::getOptionConstants();
  49. foreach (self::$optionConstants as $constantKey => $value) {
  50. $defaultOptions[$constantKey] = $defaultMemcached->getOption($value);
  51. }
  52. return $defaultOptions;
  53. }
  54. private static function getOptionConstants(): array
  55. {
  56. $reflectedMemcached = new \ReflectionClass(\Memcached::class);
  57. $optionConstants = [];
  58. foreach ($reflectedMemcached->getConstants() as $constantKey => $value) {
  59. if (str_starts_with($constantKey, 'OPT_')) {
  60. $optionConstants[$constantKey] = $value;
  61. }
  62. }
  63. return $optionConstants;
  64. }
  65. }