DataAccess.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace Favicon;
  3. /**
  4. * DataAccess is a wrapper used to read/write data locally or remotly
  5. * Aside from SOLID principles, this wrapper is also useful to mock remote resources in unit tests
  6. * Note: remote access warning are silenced because we don't care if a website is unreachable
  7. **/
  8. class DataAccess {
  9. public function retrieveUrl($url) {
  10. $this->set_context();
  11. return @file_get_contents($url);
  12. }
  13. public function retrieveHeader($url) {
  14. $this->set_context();
  15. $headers = @get_headers($url, 1);
  16. return is_array($headers) ? array_change_key_case($headers) : array();
  17. }
  18. public function saveCache($file, $data) {
  19. file_put_contents($file, $data);
  20. }
  21. public function readCache($file) {
  22. return file_get_contents($file);
  23. }
  24. private function set_context() {
  25. stream_context_set_default(
  26. array(
  27. 'http' => array(
  28. 'method' => 'GET',
  29. 'follow_location' => 0,
  30. 'max_redirects' => 1,
  31. 'timeout' => 10,
  32. 'header' => "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:20.0; Favicon; +https://github.com/ArthurHoaro/favicon) Gecko/20100101 Firefox/32.0\r\n",
  33. )
  34. )
  35. );
  36. }
  37. }