Guest User

Untitled

a guest
Oct 19th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. <?php declare(strict_types=1);
  2.  
  3. define('CACHE_FILE','/home/seb/.cache/test_php_{file}.txt');
  4.  
  5. print 'get(yep) -> '.get('yep').PHP_EOL;
  6. print 'cache file for yep : '.cache_file_path('yep');
  7.  
  8. function get(string $x): ?string {
  9. return cached($x) ?? fetch($x); // @todo fetch is not supposed to cache, no implicite.
  10. }
  11.  
  12. function cached(string $x): ?string {
  13. $content = fread(cache_file_stream($x),filesize(cache_file_path($x)));
  14. return $content === false ? null : $content;
  15. }
  16.  
  17. function fetch(string $x): ?string {
  18. $content = (string)time(); // fake content
  19. throw new \LogicException('re implement this');
  20. return cache($x, $content);
  21. }
  22.  
  23. function cache(string $x, string $content): string {
  24. if(false === fwrite(cache_file_stream($x), $content)) {
  25. throw new FailToWriteToFile(cache_file_path($x));
  26. };
  27. return $content;
  28. }
  29.  
  30. /** @return resource */
  31. function cache_file_stream(string $x)/*: resource*/ {
  32. if(false === ($resource = fopen(cache_file_path($x), 'c+'))) {
  33. throw new FailToOpenFile(cache_file_path($x));
  34. }
  35. return $resource;
  36. }
  37.  
  38. function cache_file_path(string $x): string {
  39. return strtr(CACHE_FILE,['{file}' => crc32($x)]);
  40. }
Add Comment
Please, Sign In to add comment