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 ( ad2a41...654aae )
by Sebastian
04:38 queued 02:53
created

MatchesSnapshots::assertMatchesSnapshot()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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