private static function writeOutput()

in src/markdown-extensions/extracted-code-blocks/ExtractFilter.php [147:217]


  private static function writeOutput(
    string $output,
    ?string $path_to_sanitize,
    string $hack_file_path,
    Files $out_file,
    Files $example_file,
    Files $expectf_file,
    Files $expectregex_file,
    bool $needs_example,
  ): void {
    // Ensure newline at the end of the file.
    if ($output !== '' && !Str\ends_with($output, "\n")) {
      $output .= "\n";
    }

    $out_path = $hack_file_path.'.'.$out_file;
    $example_path = $hack_file_path.'.'.$example_file;
    $expectf_path = $hack_file_path.'.'.$expectf_file;
    $expectregex_path = $hack_file_path.'.'.$expectregex_file;

    if (\file_exists($expectf_path) || \file_exists($expectregex_path)) {
      // Only generate example output.
      invariant(
        $needs_example && !\file_exists($example_path),
        'Tried to auto-generate %s but it already exist (or should not exist)!',
        $example_path,
      );
      \file_put_contents(
        $example_path,
        $path_to_sanitize is nonnull
          ? Str\replace($output, $path_to_sanitize, '/home/example')
          : $output,
      );
    } else if (
      $path_to_sanitize is nonnull && Str\contains($output, $path_to_sanitize)
    ) {
      // Note: One of these may have been explicitly specified in the code
      // block, in which case only auto-generate the other one.
      invariant(
        ($needs_example && !\file_exists($example_path)) ||
        !\file_exists($expectf_path),
        'Tried to auto-generate %s and/or %s but both already exist (or '.
        'should not exist)!',
        $example_path,
        $expectf_path,
      );

      if ($needs_example && !\file_exists($example_path)) {
        \file_put_contents(
          $example_path,
          Str\replace($output, $path_to_sanitize, '/home/example'),
        );
      }

      if (!\file_exists($expectf_path)) {
        \file_put_contents(
          $expectf_path,
          Str\replace($output, '%', '%%')
            |> Str\replace($$, $path_to_sanitize, '%s')
            |> Regex\replace($$, re"/string\\([0-9]+\\)/", 'string(%d)'),
        );
      }
    } else {
      invariant(
        !\file_exists($out_path),
        'Tried to auto-generate %s but it already exists!',
        $out_path,
      );
      \file_put_contents($out_path, $output);
    }
  }