I've got a FileLocations class which stores the path's to specific files.
class FileLocations
{
/**
* @var array
*/
private $files = [];
/**
* @param array $files
*
* @throws \Exception
*/
public function __construct (array $files) {
if (!$this->areValidFiles($files)) {
throw new Exception;
}
$this->files = $files;
}
/**
* @param $files
*
* @return bool
*/
private function areValidFiles (array $files) {
foreach ($files as $file) {
return is_file($file);
}
return false;
}
/**
* @return array
*/
public function getFiles () {
return $this->files;
}
}
I've wanted to validate each file (with is_file), so i made the areValidFiles function and looped through every array index which it gets. On each array item it's doing an check.
When i run this code like this:
$fileLocations = new FileLocations(['doesExist.js', 'doesnotExist.js']);
var_dump($fileLocations->getFiles());
It only does the validation for the first file and doesn't even reconize that there is a second file passed in the arguments.
It also doesn't throw an exception.
Questions
How does this come that it only reconizes one file in the validation and not throws an exception on the second file that doesn't even exist?
How can I make it so that i will be able to pass more parameters inside the
areValidFilesfunction?
return is_file()is causing the foreach to abort after the first time. Remove that is the first step to solve this. What should happen when it finds a file that does not exist?return is_file()basically exits the function, stopping it from looping through the rest of the array.foreach $files as $file: if not is_file($file): throw new Exception. Otherwise you could replace thethrow new Exceptionwithreturn false.