SocketCaster.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. $uri = ($info['uri'] ?? '//');
  25. if (str_starts_with($uri, 'unix://')) {
  26. $uri .= $addr;
  27. } else {
  28. $uri .= \sprintf(str_contains($addr, ':') ? '[%s]:%s' : '%s:%s', $addr, $port);
  29. }
  30. $a[Caster::PREFIX_VIRTUAL.'uri'] = $uri;
  31. if (@socket_atmark($socket)) {
  32. $a[Caster::PREFIX_VIRTUAL.'atmark'] = true;
  33. }
  34. $a += [
  35. Caster::PREFIX_VIRTUAL.'timed_out' => $info['timed_out'],
  36. Caster::PREFIX_VIRTUAL.'blocked' => $info['blocked'],
  37. ];
  38. if (!$lastError = socket_last_error($socket)) {
  39. return $a;
  40. }
  41. static $errors;
  42. if (!$errors) {
  43. $errors = get_defined_constants(true)['sockets'] ?? [];
  44. $errors = array_flip(array_filter($errors, static fn ($k) => str_starts_with($k, 'SOCKET_E'), \ARRAY_FILTER_USE_KEY));
  45. }
  46. $a[Caster::PREFIX_VIRTUAL.'last_error'] = new ConstStub($errors[$lastError], socket_strerror($lastError));
  47. return $a;
  48. }
  49. }