SocketCaster.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 Nicolas Grekas <p@tchwork.com>
  14. * @author Alexandre Daubois <alex.daubois@gmail.com>
  15. *
  16. * @internal
  17. */
  18. final class SocketCaster
  19. {
  20. public static function castSocket(\Socket $socket, array $a, Stub $stub, bool $isNested): array
  21. {
  22. socket_getsockname($socket, $addr, $port);
  23. $info = stream_get_meta_data(socket_export_stream($socket));
  24. if (\PHP_VERSION_ID >= 80300) {
  25. $uri = ($info['uri'] ?? '//');
  26. if (str_starts_with($uri, 'unix://')) {
  27. $uri .= $addr;
  28. } else {
  29. $uri .= \sprintf(str_contains($addr, ':') ? '[%s]:%s' : '%s:%s', $addr, $port);
  30. }
  31. $a[Caster::PREFIX_VIRTUAL.'uri'] = $uri;
  32. if (@socket_atmark($socket)) {
  33. $a[Caster::PREFIX_VIRTUAL.'atmark'] = true;
  34. }
  35. }
  36. $a += [
  37. Caster::PREFIX_VIRTUAL.'timed_out' => $info['timed_out'],
  38. Caster::PREFIX_VIRTUAL.'blocked' => $info['blocked'],
  39. ];
  40. if (!$lastError = socket_last_error($socket)) {
  41. return $a;
  42. }
  43. static $errors;
  44. if (!$errors) {
  45. $errors = get_defined_constants(true)['sockets'] ?? [];
  46. $errors = array_flip(array_filter($errors, static fn ($k) => str_starts_with($k, 'SOCKET_E'), \ARRAY_FILTER_USE_KEY));
  47. }
  48. $a[Caster::PREFIX_VIRTUAL.'last_error'] = new ConstStub($errors[$lastError], socket_strerror($lastError));
  49. return $a;
  50. }
  51. }