/packages/Image/ImageCache/Managers/ImageCache.class.php
PHP | 97 lines | 57 code | 11 blank | 29 comment | 9 complexity | 31cc8097b285c343d3e0ed535e4e4d23 MD5 | raw file
1<?php
2class ImageCache
3{
4 protected $config;
5
6 public function __construct(Config $config){
7 $this->config = $config;
8
9 ensurePathLastSlash($this->config->cacheDir);
10 }
11
12 /**
13 * Generate image cache and return resulting path
14 *
15 * @param string $folderName
16 * @param Image $image
17 * @param boolean $forceGenerate
18 * @throws InvalidArgumentException
19 * @throws RuntimeException
20 * @return string
21 */
22 public function generateImageCache($folderName, Image $image, $forceGenerate = false){
23 if(!in_array($folderName, $this->config->folders->toArray())){
24 throw new InvalidArgumentException("There is no such folder defined with name $folderName!");
25 }
26 if(!file_exists($this->config->cacheDir . $folderName)){
27 throw new RuntimeException("There is no such folder $folderName in cache directory!");
28 }
29
30 $resultingFilePath = $this->config->cacheDir . $folderName . "/" . $image->fileName;
31
32 if($forceGenerate or !file_exists($resultingFilePath)){
33 switch ($image->getType()){
34 case Image::IMAGE_TYPE_JPEG:
35 $image->writeJpeg($resultingFilePath);
36 break;
37 case Image::IMAGE_TYPE_GIF:
38 $image->writeGif($resultingFilePath);
39 break;
40 case Image::IMAGE_TYPE_PNG:
41 $image->writePng($resultingFilePath);
42 break;
43 }
44 }
45
46 return $resultingFilePath;
47 }
48
49 /**
50 * Checks if image cache is present
51 *
52 * @param string $folderName
53 * @param string $fileName
54 * @throws InvalidArgumentException
55 * @throws RuntimeException
56 * @return boolean
57 */
58 public function isImageCached($folderName, $fileName){
59 if(!in_array($folderName, $this->config->folders->toArray())){
60 throw new InvalidArgumentException("There is no such folder defined with name $folderName!");
61 }
62 if(!file_exists($this->config->cacheDir . $folderName)){
63 throw new RuntimeException("There is no such folder $folderName in cache directory!");
64 }
65
66 $resultingFilePath = $this->config->cacheDir . $folderName . "/" . $fileName;
67
68 if(file_exists($resultingFilePath)){
69 return true;
70 }
71 return false;
72 }
73
74 /**
75 * Clear cache of given photo filename
76 * @param string $fileName
77 */
78 public function clearImageCache($fileName){
79 if(empty($fileName)){
80 throw new InvalidArgumentException("\$fileName is empty!");
81 }
82 foreach ($this->config->folders as $folderName){
83 if(file_exists($this->config->cacheDir . $folderName . "/" . $fileName)){
84 @unlink($this->config->cacheDir . $folderName . "/" . $fileName);
85 }
86 }
87 }
88
89 /**
90 * Clear whole image cache
91 */
92 public function clearWholeImageCache(){
93 foreach ($this->config->folders as $folderName){
94 @unlink($this->config->cacheDir . $folderName . "/*");
95 }
96 }
97}