GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#76)
by Tom
01:06
created

MatchesSnapshots::assertMatchesHtmlSnapshot()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\Snapshots;
4
5
use PHPUnit\Framework\ExpectationFailedException;
6
use ReflectionClass;
7
use ReflectionObject;
8
use Spatie\Snapshots\Drivers\HtmlDriver;
9
use Spatie\Snapshots\Drivers\JsonDriver;
10
use Spatie\Snapshots\Drivers\VarDriver;
11
use Spatie\Snapshots\Drivers\XmlDriver;
12
use Spatie\Snapshots\Drivers\YamlDriver;
13
14
trait MatchesSnapshots
15
{
16
    /** @var int */
17
    protected $snapshotIncrementor;
18
19
    /** @var string[] */
20
    protected $snapshotChanges;
21
22
    /** @before */
23
    public function setUpSnapshotIncrementor()
24
    {
25
        $this->snapshotIncrementor = 0;
26
    }
27
28
    /** @after */
29
    public function markTestIncompleteIfSnapshotsHaveChanged()
30
    {
31
        if (empty($this->snapshotChanges)) {
32
            return;
33
        }
34
35
        if (count($this->snapshotChanges) === 1) {
36
            $this->markTestIncomplete($this->snapshotChanges[0]);
0 ignored issues
show
Bug introduced by
The method markTestIncomplete() does not exist on Spatie\Snapshots\MatchesSnapshots. Did you maybe mean markTestIncompleteIfSnapshotsHaveChanged()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
37
38
            return;
39
        }
40
41
        $formattedMessages = implode(PHP_EOL, array_map(function (string $message) {
42
            return "- {$message}";
43
        }, $this->snapshotChanges));
44
45
        $this->markTestIncomplete($formattedMessages);
0 ignored issues
show
Bug introduced by
The method markTestIncomplete() does not exist on Spatie\Snapshots\MatchesSnapshots. Did you maybe mean markTestIncompleteIfSnapshotsHaveChanged()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
46
    }
47
48
    public function assertMatchesSnapshot($actual, Driver $driver = null)
49
    {
50
        if (is_null($driver) && is_array($actual)) {
51
            $this->assertMatchesYamlSnapshot($actual);
52
53
            return;
54
        }
55
56
        $this->doSnapshotAssertion($actual, $driver ?? new VarDriver());
57
    }
58
59
    public function assertMatchesHtmlSnapshot($actual)
60
    {
61
        $this->assertMatchesSnapshot($actual, new HtmlDriver());
62
    }
63
64
    public function assertMatchesXmlSnapshot($actual)
65
    {
66
        $this->assertMatchesSnapshot($actual, new XmlDriver());
67
    }
68
69
    public function assertMatchesJsonSnapshot($actual)
70
    {
71
        $this->assertMatchesSnapshot($actual, new JsonDriver());
72
    }
73
74
    public function assertMatchesYamlSnapshot($actual)
75
    {
76
        $this->assertMatchesSnapshot($actual, new YamlDriver());
77
    }
78
79
    public function assertMatchesFileHashSnapshot($filePath)
80
    {
81
        if (! file_exists($filePath)) {
82
            $this->fail('File does not exist');
0 ignored issues
show
Bug introduced by
It seems like fail() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
83
        }
84
85
        $actual = sha1_file($filePath);
86
87
        $this->assertMatchesSnapshot($actual);
88
    }
89
90
    public function assertMatchesFileSnapshot($file)
91
    {
92
        $this->doFileSnapshotAssertion($file);
93
    }
94
95
    /**
96
     * Determines the snapshot's id. By default, the test case's class and
97
     * method names are used.
98
     *
99
     * @return string
100
     */
101
    protected function getSnapshotId(): string
102
    {
103
        return (new ReflectionClass($this))->getShortName().'__'.
104
            $this->getName().'__'.
0 ignored issues
show
Bug introduced by
It seems like getName() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
105
            $this->snapshotIncrementor;
106
    }
107
108
    /**
109
     * Determines the directory where snapshots are stored. By default a
110
     * `__snapshots__` directory is created at the same level as the test
111
     * class.
112
     *
113
     * @return string
114
     */
115
    protected function getSnapshotDirectory(): string
116
    {
117
        return dirname((new ReflectionClass($this))->getFileName()).
118
            DIRECTORY_SEPARATOR.
119
            '__snapshots__';
120
    }
121
122
    /**
123
     * Determines the directory where file snapshots are stored. By default a
124
     * `__snapshots__/files` directory is created at the same level as the
125
     * test class.
126
     *
127
     * @return string
128
     */
129
    protected function getFileSnapshotDirectory(): string
130
    {
131
        return $this->getSnapshotDirectory().
132
            DIRECTORY_SEPARATOR.
133
            'files';
134
    }
135
136
    /**
137
     * Determines whether or not the snapshot should be updated instead of
138
     * matched.
139
     *
140
     * Override this method it you want to use a different flag or mechanism
141
     * than `-d --update-snapshots`.
142
     *
143
     * @return bool
144
     */
145
    protected function shouldUpdateSnapshots(): bool
146
    {
147
        return in_array('--update-snapshots', $_SERVER['argv'], true);
148
    }
149
150
    protected function doSnapshotAssertion($actual, Driver $driver)
151
    {
152
        $this->snapshotIncrementor++;
153
154
        $snapshot = Snapshot::forTestCase(
155
            $this->getSnapshotId(),
156
            $this->getSnapshotDirectory(),
157
            $driver
158
        );
159
160
        if (! $snapshot->exists()) {
161
            $this->createSnapshotAndMarkTestIncomplete($snapshot, $actual);
162
        }
163
164
        if ($this->shouldUpdateSnapshots()) {
165
            try {
166
                // We only want to update snapshots which need updating. If the snapshot doesn't
167
                // match the expected output, we'll catch the failure, create a new snapshot and
168
                // mark the test as incomplete.
169
                $snapshot->assertMatches($actual);
170
            } catch (ExpectationFailedException $exception) {
171
                $this->updateSnapshotAndMarkTestIncomplete($snapshot, $actual);
172
            }
173
        }
174
175
        try {
176
            $snapshot->assertMatches($actual);
177
        } catch (ExpectationFailedException $exception) {
178
            $this->rethrowExpectationFailedExceptionWithUpdateSnapshotsPrompt($exception);
179
        }
180
    }
181
182
    protected function doFileSnapshotAssertion(string $filePath)
183
    {
184
        if (! file_exists($filePath)) {
185
            $this->fail('File does not exist');
0 ignored issues
show
Bug introduced by
It seems like fail() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
186
        }
187
188
        $fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
189
190
        if (empty($fileExtension)) {
191
            $this->fail("Unable to make a file snapshot, file does not have a file extension ({$filePath})");
0 ignored issues
show
Bug introduced by
It seems like fail() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
192
        }
193
194
        $fileSystem = Filesystem::inDirectory($this->getFileSnapshotDirectory());
195
196
        $this->snapshotIncrementor++;
197
198
        $snapshotId = $this->getSnapshotId().'.'.$fileExtension;
199
200
        // If $filePath has a different file extension than the snapshot, the test should fail
201
        if ($namesWithDifferentExtension = $fileSystem->getNamesWithDifferentExtension($snapshotId)) {
202
            // There is always only one existing snapshot with a different extension
203
            $existingSnapshotId = $namesWithDifferentExtension[0];
204
205
            if ($this->shouldUpdateSnapshots()) {
206
                $fileSystem->delete($existingSnapshotId);
207
208
                $fileSystem->copy($filePath, $snapshotId);
209
210
                $this->registerSnapshotChange("File snapshot updated for {$snapshotId}");
211
212
                return;
213
            }
214
215
            $expectedExtension = pathinfo($existingSnapshotId, PATHINFO_EXTENSION);
216
217
            return $this->fail("File did not match the snapshot file extension (expected: {$expectedExtension}, was: {$fileExtension})");
0 ignored issues
show
Bug introduced by
It seems like fail() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
218
        }
219
220
        $failedSnapshotId = $snapshotId.'_failed.'.$fileExtension;
221
222
        if ($fileSystem->has($failedSnapshotId)) {
223
            $fileSystem->delete($failedSnapshotId);
224
        }
225
226
        if (! $fileSystem->has($snapshotId)) {
227
            $fileSystem->copy($filePath, $snapshotId);
228
229
            $this->registerSnapshotChange("File snapshot created for {$snapshotId}");
230
231
            return;
232
        }
233
234
        if (! $fileSystem->fileEquals($filePath, $snapshotId)) {
235
            if ($this->shouldUpdateSnapshots()) {
236
                $fileSystem->copy($filePath, $snapshotId);
237
238
                $this->registerSnapshotChange("File snapshot updated for {$snapshotId}");
239
240
                return;
241
            }
242
243
            $fileSystem->copy($filePath, $failedSnapshotId);
244
245
            $this->fail("File did not match snapshot ({$snapshotId})");
0 ignored issues
show
Bug introduced by
It seems like fail() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
246
        }
247
248
        $this->assertTrue(true);
0 ignored issues
show
Bug introduced by
It seems like assertTrue() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
249
    }
250
251
    protected function createSnapshotAndMarkTestIncomplete(Snapshot $snapshot, $actual)
252
    {
253
        $snapshot->create($actual);
254
255
        $this->registerSnapshotChange("Snapshot created for {$snapshot->id()}");
256
    }
257
258
    protected function updateSnapshotAndMarkTestIncomplete(Snapshot $snapshot, $actual)
259
    {
260
        $snapshot->create($actual);
261
262
        $this->registerSnapshotChange("Snapshot updated for {$snapshot->id()}");
263
    }
264
265
    protected function rethrowExpectationFailedExceptionWithUpdateSnapshotsPrompt($exception)
266
    {
267
        $newMessage = $exception->getMessage()."\n\n".
268
            'Snapshots can be updated by passing '.
269
            '`-d --update-snapshots` through PHPUnit\'s CLI arguments.';
270
271
        $exceptionReflection = new ReflectionObject($exception);
272
273
        $messageReflection = $exceptionReflection->getProperty('message');
274
        $messageReflection->setAccessible(true);
275
        $messageReflection->setValue($exception, $newMessage);
276
277
        throw $exception;
278
    }
279
280
    protected function registerSnapshotChange(string $message)
281
    {
282
        $this->snapshotChanges[] = $message;
283
    }
284
}
285