function string_cast_for_switch()

in src/legacy_fixme/coercions.php [526:582]


function string_cast_for_switch(
  mixed $value,
  ?arraykey $first_truthy = null,
  ?arraykey $first_zeroish = null,
  ?arraykey $first_falsy = null,
  dict<arraykey, int> $intish_vals = dict[],
  dict<arraykey, float> $floatish_vals = dict[],
)[]: string {
  $default = SWITCH_STRING_SENTINEL;
  $orig_is_str = $value is string;
  if ($value is string) {
    if (!\is_numeric($value)) return $value;
    $default = $value;
    $value = \HH\str_to_numeric($value) as nonnull;
    // fallthrough
  }

  if ($value is null) return '';

  if ($value is resource) $value = (float)($value);

  if ($value is float) {
    if (Math\floor($value) === $value) {
      $value = (int)$value;
      // fallthrough
    } else {
      if ($orig_is_str) {
        $floatish_vals = Dict\filter_keys($floatish_vals, \is_numeric<>);
      }
      return C\find_key($floatish_vals, $n ==> $n === $value) as ?string ??
        $default;
    }
  }
  if ($value is int) {
    if ($orig_is_str) {
      $intish_vals = Dict\filter_keys($intish_vals, \is_numeric<>);
      // fallthrough
    } else if ($value === 0) {
      return $first_zeroish as ?string ?? $default;
    }
    return C\find_key($intish_vals, $n ==> $n === $value) as ?string ??
      $default;
  }

  if ($value === true) {
    return $first_truthy as ?string ?? SWITCH_STRING_SENTINEL;
  }
  if ($value === false) {
    return $first_falsy as ?string ?? SWITCH_STRING_SENTINEL;
  }

  if ($value is \StringishObject && !($value is \ConstCollection<_>)) {
    return (string)($value as dynamic); // this will throw
  }

  return SWITCH_STRING_SENTINEL;
}