zenstruck / browser

A fluent interface for your Symfony functional tests.
MIT License
185 stars 17 forks source link

Improve file saving #120

Closed welcoMattic closed 1 year ago

welcoMattic commented 1 year ago

Actually we have saveSource method to save source of the requested URL. However, I'm trying to save a zip file with this method, and it results to a corrupted zip (because of the prepend text content to the source file, https://github.com/zenstruck/browser/blob/1.x/src/Browser/Session.php#L98-L112)

It could be useful to have a dedicated method to save files as raw content (HTML or not).

kbond commented 1 year ago

Maybe we could change saveSource to:

public function saveSource(string $filename, bool $raw = false): static;
welcoMattic commented 1 year ago

I'm trying to modify saveSource to this, yes. I'll let you know if I achieve something interesting to contribute it upstream, here ;)

welcoMattic commented 1 year ago

"It works!" ©

I will soon open a PR!

final public function saveSource(string $filename, bool $raw = false): self
public function source(bool $raw = false): string
{
    $ret = '';

    if (!$raw) {
        $ret = "<!--\n";

        try {
            $ret .= "URL: {$this->getCurrentUrl()} ({$this->getStatusCode()})\n\n";

            foreach ($this->getResponseHeaders() as $header => $values) {
                foreach ((array) $values as $value) {
                    $ret .= "{$header}: {$value}\n";
                }
            }
        } catch (DriverException $e) {
            $ret = "URL: {$this->getCurrentUrl()}\n";
        }

        $ret .= "-->\n";
    }

    try {
        $ret .= $this->json();
    } catch (DriverException $e) {
        $ret .= $raw ? $this->getDriver()->getContent() : \trim($this->getDriver()->getContent());
    }

    return $ret;
}