CloudAssetsFullCheckTask::run()   B
last analyzed

Complexity

Conditions 10
Paths 14

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 7.6666
c 0
b 0
f 0
cc 10
nc 14
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Does a full status check on every file AND thumbnail/formatted/generated file.
4
 * Checks the following cases:
5
 *
6
 * 1. Local file doesn't exist                          -> downloads from cloud
7
 * 2. Local file is a placeholder but KeepLocal is true -> downloads from cloud
8
 * 3. Remote file is a placeholder but local in tact    -> clears status and re-uploads
9
 * 4. Meta data is missing                              -> restores meta
10
 * 5. Both remote and local are missing or corrupt      -> deletes if thumbnail, flags if not (writes to missing_files.csv)
11
 * 6. Local needs to be wrapped or uploaded             -> uploads as normal (via updateCloudStatus)
12
 *
13
 * @author Mark Guinn <[email protected]>
14
 * @date 02.06.2014
15
 * @package cloudassets
16
 * @subpackage tasks
17
 */
18
class CloudAssetsFullCheckTask extends BuildTask
19
{
20
	protected $title = 'Cloud Assets: Full Health Check';
21
	protected $description = 'Does a full status check on every file AND thumbnail/formatted/generated file.';
22
23
	protected $missing; // file handle
24
25
26
	/**
27
	 * @param $request
28
	 */
29
	public function run($request) {
30
		$buckets   = Config::inst()->get('CloudAssets', 'map');
31
		$start     = (int)$request->requestVar('start');
32
		$limit     = (int)$request->requestVar('limit');
33
		$path      = $request->requestVar('path');
34
35
		foreach ($buckets as $basePath => $cfg) {
0 ignored issues
show
Bug introduced by
The expression $buckets of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
36
			if (!empty($path) && $basePath != $path) continue;
37
			echo "Processing $basePath...\n";
38
			$baseQuery = File::get()->filter('Filename:StartsWith', ltrim($basePath, '/'));
39
			$total     = $baseQuery->count();
40
			if ($start && !$limit) $limit = $total;
41
			if ($limit) $baseQuery = $baseQuery->limit($limit, $start);
42
			$query     = $baseQuery->dataQuery()->query()->execute();
43
			foreach ($query as $i => $row) {
44
				$class = $row['ClassName'];
45
				$file  = new $class($row);
46
				echo ($i+$start) . "/$total: " . $file->Filename;
47
48
				$this->processFile($file);
49
50
				if ($file instanceof CloudImage) {
51
					foreach ($file->DerivedImages() as $thumbStore) {
0 ignored issues
show
Documentation Bug introduced by
The method DerivedImages does not exist on object<CloudImage>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
52
						$thumb = $thumbStore->getCloudImageCached();
53
						echo "\n   DERIVED: " . $thumb->Filename;
54
						$this->processFile($thumb);
55
					}
56
				}
57
58
				echo "\n";
59
			}
60
		}
61
62
		echo "done\n\n";
63
	}
64
65
66
	/**
67
	 * @param File $file
68
	 */
69
	protected function processFile(File $file) {
70
		$placeholder = Config::inst()->get('CloudAssets', 'file_placeholder');
71
72
		// 6. Local needs to be wrapped or uploaded             -> uploads as normal (via updateCloudStatus)
73
		$file->updateCloudStatus();
74
75
		$bucket = $file->getCloudBucket();
76
		if ($bucket && $bucket->hasMethod('getFileSize')) {
77
			$size = $bucket->getFileSize($file);
78
79
			// if the size matches the placeholder, go ahead and check the actual contents
80
			if ($size === strlen($placeholder)) {
81
				echo " Remote placeholder!";
82
				$content = $bucket->getContents($file);
83
				if ($content === $placeholder) $size = -1;
84
			}
85
86
			if ($size < 0) {
87
				if ($file->isLocalMissing()) {
88
					// 5. Both remote and local are missing or corrupt      -> deletes if thumbnail, flags if not (writes to missing_files.csv)
89
					if ($file instanceof CloudImageCached) {
90
						echo " Corrupted thumbnail deleted";
91
						$file->delete();
92
						return;
93
					} else {
94
						if (!isset($this->missing)) $this->missing = fopen(BASE_PATH . '/missing_files.csv', 'a');
95
						fputcsv($this->missing, array(date('Y-m-d H:i:s'), $file->ID, $file->Filename));
96
						echo " Corrupted in both locations!!!";
97
						return;
98
					}
99
				} else {
100
					// 3. Remote file is a placeholder but local in tact    -> clears status and re-uploads
101
					$file->CloudStatus = 'Local';
102
					$file->updateCloudStatus();
103
				}
104
			}
105
		}
106
107
		// 1. Local file doesn't exist                          -> downloads from cloud
108
		// 2. Local file is a placeholder but KeepLocal is true -> downloads from cloud
109
		$file->createLocalIfNeeded();
110
111
		// 4. Meta data is missing                              -> restores meta
112
		if ($file instanceof CloudImage && !$file->getCloudMeta('Dimensions')) {
0 ignored issues
show
Documentation Bug introduced by
The method getCloudMeta does not exist on object<CloudImage>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
113
			echo " Missing metadata!";
114
			if ($file->isLocalMissing()) $file->downloadFromCloud();
0 ignored issues
show
Documentation Bug introduced by
The method downloadFromCloud does not exist on object<CloudImage>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
Documentation Bug introduced by
The method isLocalMissing does not exist on object<CloudImage>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
115
			$file->setCloudMeta('Dimensions', $file->getDimensions('live'));
0 ignored issues
show
Documentation Bug introduced by
The method setCloudMeta does not exist on object<CloudImage>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
116
			$file->write();
117
		}
118
	}
119
120
}