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