Client.php
9 years ago
Exception.php
10 years ago
Result.php
10 years ago
ResultMeta.php
10 years ago
Source.php
10 years ago
Source.php
70 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Tinify; |
| 4 | |
| 5 | class Source { |
| 6 | private $url, $commands; |
| 7 | |
| 8 | public static function fromFile($path) { |
| 9 | return self::fromBuffer(file_get_contents($path)); |
| 10 | } |
| 11 | |
| 12 | public static function fromBuffer($string) { |
| 13 | $response = Tinify::getClient()->request("post", "/shrink", $string); |
| 14 | return new self($response->headers["location"]); |
| 15 | } |
| 16 | |
| 17 | public static function fromUrl($url) { |
| 18 | $body = array("source" => array("url" => $url)); |
| 19 | $response = Tinify::getClient()->request("post", "/shrink", $body); |
| 20 | return new self($response->headers["location"]); |
| 21 | } |
| 22 | |
| 23 | public function __construct($url, $commands = array()) { |
| 24 | $this->url = $url; |
| 25 | $this->commands = $commands; |
| 26 | } |
| 27 | |
| 28 | public function preserve() { |
| 29 | $options = $this->flatten(func_get_args()); |
| 30 | $commands = array_merge($this->commands, array("preserve" => $options)); |
| 31 | return new self($this->url, $commands); |
| 32 | } |
| 33 | |
| 34 | public function resize($options) { |
| 35 | $commands = array_merge($this->commands, array("resize" => $options)); |
| 36 | return new self($this->url, $commands); |
| 37 | } |
| 38 | |
| 39 | public function store($options) { |
| 40 | $response = Tinify::getClient()->request("post", $this->url, |
| 41 | array_merge($this->commands, array("store" => $options))); |
| 42 | return new Result($response->headers, $response->body); |
| 43 | } |
| 44 | |
| 45 | public function result() { |
| 46 | $response = Tinify::getClient()->request("get", $this->url, $this->commands); |
| 47 | return new Result($response->headers, $response->body); |
| 48 | } |
| 49 | |
| 50 | public function toFile($path) { |
| 51 | return $this->result()->toFile($path); |
| 52 | } |
| 53 | |
| 54 | public function toBuffer() { |
| 55 | return $this->result()->toBuffer(); |
| 56 | } |
| 57 | |
| 58 | private static function flatten($options) { |
| 59 | $flattened = array(); |
| 60 | foreach ($options as $option) { |
| 61 | if (is_array($option)) { |
| 62 | $flattened = array_merge($flattened, $option); |
| 63 | } else { |
| 64 | array_push($flattened, $option); |
| 65 | } |
| 66 | } |
| 67 | return $flattened; |
| 68 | } |
| 69 | } |
| 70 |