我开始开发一个图像处理库并决定使用Scrutinizer进行测试和检查,但是我不确定如何优化我的代码来限制一些降低整体分数的统计数据。 / p>
我在下面显示的代码有“条件:6”,将其推至“B”等级。关于代码没有任何特殊之处,它会检查潜在的缺失权限或无效目录,并相应地抛出异常,因此在不使代码完全不同的情况下降低分数是非常困难的:
/**
* Writes the image to a writable source
*
* @param int $compression Compression level 0-9, defaults to 9
*
* @throws \StandardExceptions\IOExceptions\FileNotWritableException
* @throws \StandardExceptions\IOExceptions\DirectoryNotFoundException
* @throws \StandardExceptions\IOExceptions\DirectoryNotWritableException
*/
public function write($compression = 9)
{
$path = $this->getPath();
$directory = $path->getPathInfo();
if (file_exists($path->getPathname()) && !$path->isWritable()) {
throw new FileNotWritableException();
} elseif (!is_dir($directory->getPathname())) {
throw new DirectoryNotFoundException();
} elseif (is_dir($directory->getPathname()) && !$directory->isWritable()) {
throw new DirectoryNotWritableException();
}
$options = [
'png_compression_level' => $compression,
'resolution-x' => $this->getDensity()->getDensity(),
'resolution-y' => $this->getDensity()->getDensity(),
'resolution-units' => $this->mapDensity($this->getDensity()),
];
$this->getImage()->save($path, $options);
}
我不明白为什么我有6个条件,而那里只有3个条件。我不明白我怎么能降低这个!
答案 0 :(得分:0)
我试图将我的代码拆分成更多的函数,这些函数现在使代码的可读性降低,并且在类中创建了许多无用的函数,但至少它可以工作,并且我能够将每个块中的条件减少到1或2代码有效地将我的代码提升到" A"无处不在。
/**
* Writes the image to a writable source
*
* @param int $compression Compression level 0-9, defaults to 9
*/
public function write($compression = 9)
{
$this->checkFileIsWritable();
$this->checkDirectoryExists();
$this->checkDirectoryIsWritable();
$options = [
'png_compression_level' => $compression,
'resolution-x' => $this->getDensity()->getDensity(),
'resolution-y' => $this->getDensity()->getDensity(),
'resolution-units' => $this->mapDensity($this->getDensity()),
];
$this->getImage()->save($this->getPath(), $options);
}
/**
* Checks that the path is valid and throws exceptions
* if there is something wrong
*
* @throws \StandardExceptions\IOExceptions\FileNotWritableException
*/
public function checkFileIsWritable()
{
$path = $this->getPath();
if (file_exists($path->getPathname()) && !$path->isWritable()) {
throw new FileNotWritableException();
}
}
/**
* Checks that the path is valid and throws exceptions
* if there is something wrong
*
* @throws \StandardExceptions\IOExceptions\DirectoryNotFoundException
*/
public function checkDirectoryExists()
{
$path = $this->getPath();
$directory = $path->getPathInfo();
if (!is_dir($directory->getPathname())) {
throw new DirectoryNotFoundException();
}
}
/**
* Checks that the is writable
*
* @throws \StandardExceptions\IOExceptions\DirectoryNotWritableException
*/
public function checkDirectoryIsWritable()
{
$path = $this->getPath();
$directory = $path->getPathInfo();
if (is_dir($directory->getPathname()) && !$directory->isWritable()) {
throw new DirectoryNotWritableException();
}
}