PageRenderTime 57ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/class.smushit.php

http://github.com/tylerhall/smushit-php
PHP | 90 lines | 72 code | 13 blank | 5 comment | 6 complexity | cbdfe16c71e2ed88688957e96ef80575 MD5 | raw file
  1. <?PHP
  2. // smushit-php - a PHP client for Yahoo!'s Smush.it web service
  3. //
  4. // June 24, 2010
  5. // Tyler Hall <tylerhall@gmail.com>
  6. // http://github.com/tylerhall/smushit-php/tree/master
  7. class SmushIt
  8. {
  9. const SMUSH_URL = 'http://www.smushit.com/ysmush.it/ws.php?';
  10. public $filename;
  11. public $url;
  12. public $compressedUrl;
  13. public $size;
  14. public $compressedSize;
  15. public $savings;
  16. public $error;
  17. public function __construct($data = null)
  18. {
  19. if(!is_null($data))
  20. {
  21. if(preg_match('/https?:\/\//', $data) == 1)
  22. $this->smushURL($data);
  23. else
  24. $this->smushFile($data);
  25. }
  26. }
  27. public function smushURL($url)
  28. {
  29. $this->url = $url;
  30. $ch = curl_init();
  31. curl_setopt($ch, CURLOPT_URL, self::SMUSH_URL . 'img=' . $url);
  32. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  33. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  34. $json_str = curl_exec($ch);
  35. curl_close($ch);
  36. return $this->parseResponse($json_str);
  37. }
  38. public function smushFile($filename)
  39. {
  40. $this->filename = $filename;
  41. if(!is_readable($filename))
  42. {
  43. $this->error = 'Could not read file';
  44. return false;
  45. }
  46. $ch = curl_init();
  47. curl_setopt($ch, CURLOPT_URL, self::SMUSH_URL);
  48. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  49. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  50. curl_setopt($ch, CURLOPT_POST, true);
  51. curl_setopt($ch, CURLOPT_POSTFIELDS, array('files' => '@' . $filename));
  52. $json_str = curl_exec($ch);
  53. curl_close($ch);
  54. return $this->parseResponse($json_str);
  55. }
  56. private function parseResponse($json_str)
  57. {
  58. $this->error = null;
  59. $json = json_decode($json_str);
  60. if(is_null($json))
  61. {
  62. $this->error = 'Bad response from Smush.it web service';
  63. return false;
  64. }
  65. if(isset($json->error))
  66. {
  67. $this->error = $json->error;
  68. return false;
  69. }
  70. $this->filename = substr (strrchr ($json->src, '/'), 1 );
  71. $this->size = $json->src_size;
  72. $this->compressedUrl = rawurldecode ($json->dest);
  73. $this->compressedSize = $json->dest_size;
  74. $this->savings = $json->percent;
  75. return true;
  76. }
  77. }