-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathVipsTargetResource.php
54 lines (46 loc) · 1.42 KB
/
VipsTargetResource.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
namespace Jcupitt\Vips;
class VipsTargetResource extends VipsTargetCustom
{
/**
* @var resource
*/
private $resource;
/**
* The resource passed in will become "owned" by this class.
* On destruction of this class, the resource will be closed.
*
* @param resource $resource
*/
public function __construct($resource)
{
$this->resource = $resource;
parent::__construct();
$this->onWrite(static function (string $buffer) use (&$resource): int {
return fwrite($resource, $buffer) ?: 0;
});
$this->onEnd(static function () use (&$resource): void {
fclose($resource);
});
$meta = stream_get_meta_data($resource);
// See: https://www.php.net/manual/en/function.fopen.php
if (substr($meta['mode'], -1) === '+') {
$this->onRead(static function (int $length) use (&$resource): ?string {
return fread($resource, $length) ?: null;
});
}
if ($meta['seekable']) {
$this->onSeek(static function (int $offset, int $whence) use (&$resource): int {
fseek($resource, $offset, $whence);
return ftell($resource);
});
}
}
public function __destruct()
{
if (is_resource($this->resource)) {
fclose($this->resource);
}
parent::__destruct();
}
}