1 | <?php |
||
5 | use Spatie\Snapshots\Driver; |
||
6 | use Spatie\Snapshots\Filesystem; |
||
7 | |||
8 | class Snapshot |
||
9 | { |
||
10 | private string $id; |
||
|
|||
11 | |||
12 | private Filesystem $filesystem; |
||
13 | |||
14 | private Driver $driver; |
||
15 | |||
16 | public function __construct( |
||
17 | string $id, |
||
18 | Filesystem $filesystem, |
||
19 | Driver $driver |
||
20 | ) { |
||
21 | $this->id = $id; |
||
22 | $this->filesystem = $filesystem; |
||
23 | $this->driver = $driver; |
||
24 | } |
||
25 | |||
26 | public static function forTestCase( |
||
27 | string $id, |
||
28 | string $directory, |
||
29 | Driver $driver |
||
30 | ): self { |
||
31 | $filesystem = Filesystem::inDirectory($directory); |
||
32 | |||
33 | return new self($id, $filesystem, $driver); |
||
34 | } |
||
35 | |||
36 | public function id(): string |
||
37 | { |
||
38 | return $this->id; |
||
39 | } |
||
40 | |||
41 | public function filename(): string |
||
42 | { |
||
43 | $file = $this->id.'.'.$this->driver->extension(); |
||
44 | // Remove anything which isn't a word, whitespace, number |
||
45 | // or any of the following caracters -_~,;[](). |
||
46 | $file = preg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $file); |
||
47 | // Remove any runs of periods |
||
48 | $file = preg_replace("([\.]{2,})", '', $file); |
||
49 | |||
50 | return $file; |
||
51 | } |
||
52 | |||
53 | public function exists(): bool |
||
54 | { |
||
55 | return $this->filesystem->has($this->filename()); |
||
56 | } |
||
57 | |||
58 | public function assertMatches($actual) |
||
59 | { |
||
60 | $this->driver->match($this->filesystem->read($this->filename()), $actual); |
||
61 | } |
||
62 | |||
63 | public function create($actual) |
||
64 | { |
||
65 | $this->filesystem->put($this->filename(), $this->driver->serialize($actual)); |
||
66 | } |
||
67 | } |
||
68 |