MemcachedCaster.php 2.3 KB

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