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
Push — master ( e23e5a...cfdab8 )
by Sebastian
03:19 queued 01:40
created

rethrowExpectationFailedExceptionWithUpdateSnapshotsPrompt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
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\JsonDriver;
9
use Spatie\Snapshots\Drivers\VarDriver;
10
use Spatie\Snapshots\Drivers\XmlDriver;
11
use Spatie\Snapshots\Drivers\YamlDriver;
12
13
trait MatchesSnapshots
14
{
15
    /** @var int */
16
    protected $snapshotIncrementor;
17
18
    /** @var string[] */
19
    protected $snapshotChanges;
20
21
    /** @before */
22
    public function setUpSnapshotIncrementor()
23
    {
24
        $this->snapshotIncrementor = 0;
25
    }
26
27
    /** @after */
28
    public function markTestIncompleteIfSnapshotsHaveChanged()
29
    {
30
        if (empty($this->snapshotChanges)) {
31
            return;
32
        }
33
34
        if (count($this->snapshotChanges) === 1) {
35
            $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...
36
37
            return;
38
        }
39
40
        $formattedMessages = implode(PHP_EOL, array_map(function (string $message) {
41
            return "- {$message}";
42
        }, $this->snapshotChanges));
43
44
        $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...
45
    }
46
47
    public function assertMatchesSnapshot($actual, Driver $driver = null)
48
    {
49
        if (is_null($driver) && is_array($actual)) {
50
            $this->assertMatchesYamlSnapshot($actual);
51
52
            return;
53
        }
54
55
        $this->doSnapshotAssertion($actual, $driver ?? new VarDriver());
56
    }
57
58
    public function assertMatchesXmlSnapshot($actual)
59
    {
60
        $this->assertMatchesSnapshot($actual, new XmlDriver());
61
    }
62
63
    public function assertMatchesJsonSnapshot($actual)
64
    {
65
        $this->assertMatchesSnapshot($actual, new JsonDriver());
66
    }
67
68
    public function assertMatchesYamlSnapshot($actual)
69
    {
70
        $this->assertMatchesSnapshot($actual, new YamlDriver());
71
    }
72
73
    public function assertMatchesFileHashSnapshot($filePath)
74
    {
75
        if (! file_exists($filePath)) {
76
            $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...
77
        }
78
79
        $actual = sha1_file($filePath);
80
81
        $this->assertMatchesSnapshot($actual);
82
    }
83
84
    public function assertMatchesFileSnapshot($file)
85
    {
86
        $this->doFileSnapshotAssertion($file);
87
    }
88
89
    /**
90
     * Determines the snapshot's id. By default, the test case's class and
91
     * method names are used.
92
     *
93
     * @return string
94
     */
95
    protected function getSnapshotId(): string
96
    {
97
        return (new ReflectionClass($this))->getShortName().'__'.
98
            $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...
99
            $this->snapshotIncrementor;
100
    }
101
102
    /**
103
     * Determines the directory where snapshots are stored. By default a
104
     * `__snapshots__` directory is created at the same level as the test
105
     * class.
106
     *
107
     * @return string
108
     */
109
    protected function getSnapshotDirectory(): string
110
    {
111
        return dirname((new ReflectionClass($this))->getFileName()).
112
            DIRECTORY_SEPARATOR.
113
            '__snapshots__';
114
    }
115
116
    /**
117
     * Determines the directory where file snapshots are stored. By default a
118
     * `__snapshots__/files` directory is created at the same level as the
119
     * test class.
120
     *
121
     * @return string
122
     */
123
    protected function getFileSnapshotDirectory(): string
124
    {
125
        return $this->getSnapshotDirectory().
126
            DIRECTORY_SEPARATOR.
127
            'files';
128
    }
129
130
    /**
131
     * Determines whether or not the snapshot should be updated instead of
132
     * matched.
133
     *
134
     * Override this method it you want to use a different flag or mechanism
135
     * than `-d --update-snapshots`.
136
     *
137
     * @return bool
138
     */
139
    protected function shouldUpdateSnapshots(): bool
140
    {
141
        return in_array('--update-snapshots', $_SERVER['argv'], true);
142
    }
143
144
    protected function doSnapshotAssertion($actual, Driver $driver)
145
    {
146
        $this->snapshotIncrementor++;
147
148
        $snapshot = Snapshot::forTestCase(
149
            $this->getSnapshotId(),
150
            $this->getSnapshotDirectory(),
151
            $driver
152
        );
153
154
        if (! $snapshot->exists()) {
155
            $this->createSnapshotAndMarkTestIncomplete($snapshot, $actual);
156
        }
157
158
        if ($this->shouldUpdateSnapshots()) {
159
            try {
160
                // We only want to update snapshots which need updating. If the snapshot doesn't
161
                // match the expected output, we'll catch the failure, create a new snapshot and
162
                // mark the test as incomplete.
163
                $snapshot->assertMatches($actual);
164
            } catch (ExpectationFailedException $exception) {
165
                $this->updateSnapshotAndMarkTestIncomplete($snapshot, $actual);
166
            }
167
        }
168
169
        try {
170
            $snapshot->assertMatches($actual);
171
        } catch (ExpectationFailedException $exception) {
172
            $this->rethrowExpectationFailedExceptionWithUpdateSnapshotsPrompt($exception);
173
        }
174
    }
175
176
    protected function doFileSnapshotAssertion(string $filePath)
177
    {
178
        if (! file_exists($filePath)) {
179
            $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...
180
        }
181
182
        $fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
183
184
        if (empty($fileExtension)) {
185
            $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...
186
        }
187
188
        $fileSystem = Filesystem::inDirectory($this->getFileSnapshotDirectory());
189
190
        $this->snapshotIncrementor++;
191
192
        $snapshotId = $this->getSnapshotId().'.'.$fileExtension;
193
194
        // If $filePath has a different file extension than the snapshot, the test should fail
195
        if ($namesWithDifferentExtension = $fileSystem->getNamesWithDifferentExtension($snapshotId)) {
196
            // There is always only one existing snapshot with a different extension
197
            $existingSnapshotId = $namesWithDifferentExtension[0];
198
199
            if ($this->shouldUpdateSnapshots()) {
200
                $fileSystem->delete($existingSnapshotId);
201
202
                $fileSystem->copy($filePath, $snapshotId);
203
204
                $this->registerSnapshotChange("File snapshot updated for {$snapshotId}");
205
206
                return;
207
            }
208
209
            $expectedExtension = pathinfo($existingSnapshotId, PATHINFO_EXTENSION);
210
211
            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...
212
        }
213
214
        $failedSnapshotId = $snapshotId.'_failed.'.$fileExtension;
215
216
        if ($fileSystem->has($failedSnapshotId)) {
217
            $fileSystem->delete($failedSnapshotId);
218
        }
219
220
        if (! $fileSystem->has($snapshotId)) {
221
            $fileSystem->copy($filePath, $snapshotId);
222
223
            $this->registerSnapshotChange("File snapshot created for {$snapshotId}");
224
225
            return;
226
        }
227
228
        if (! $fileSystem->fileEquals($filePath, $snapshotId)) {
229
            if ($this->shouldUpdateSnapshots()) {
230
                $fileSystem->copy($filePath, $snapshotId);
231
232
                $this->registerSnapshotChange("File snapshot updated for {$snapshotId}");
233
234
                return;
235
            }
236
237
            $fileSystem->copy($filePath, $failedSnapshotId);
238
239
            $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...
240
        }
241
242
        $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...
243
    }
244
245
    protected function createSnapshotAndMarkTestIncomplete(Snapshot $snapshot, $actual)
246
    {
247
        $snapshot->create($actual);
248
249
        $this->registerSnapshotChange("Snapshot created for {$snapshot->id()}");
250
    }
251
252
    protected function updateSnapshotAndMarkTestIncomplete(Snapshot $snapshot, $actual)
253
    {
254
        $snapshot->create($actual);
255
256
        $this->registerSnapshotChange("Snapshot updated for {$snapshot->id()}");
257
    }
258
259
    protected function rethrowExpectationFailedExceptionWithUpdateSnapshotsPrompt($exception)
260
    {
261
        $newMessage = $exception->getMessage()."\n\n".
262
            'Snapshots can be updated by passing '.
263
            '`-d --update-snapshots` through PHPUnit\'s CLI arguments.';
264
265
        $exceptionReflection = new ReflectionObject($exception);
266
267
        $messageReflection = $exceptionReflection->getProperty('message');
268
        $messageReflection->setAccessible(true);
269
        $messageReflection->setValue($exception, $newMessage);
270
271
        throw $exception;
272
    }
273
274
    protected function registerSnapshotChange(string $message)
275
    {
276
        $this->snapshotChanges[] = $message;
277
    }
278
}
279