Check if File:getById is empty

Permalink
Hey

In my block I update a PDF and want to show it in frontend. In view.php I´m getting the file path by $file = File::getById($content). How is it possible to check if the file is not available?

micrdy
View Replies:
JohntheFish replied on at Permalink Reply
JohntheFish
A failed getByID returns null, so pretty much any null or false test will work. Just which is really a matter of coding style and what fits in with other similar checks and what php version(s) you need the code to work with.

if($file){
  // assume a valid file object
}


if(!empty($file)){
  // assume a valid file object
}


if(is_object($file)){
  // its a valid object and assume it is of type file
}


if($file instanceof File){
  // its a valid file object
}


if(is_a($file, 'File'){
  // its a valid file object
}


You can also combine more than one of the above with &&.

Some getByID methods, like page/collection objects, can also return an object with an error state, so you sometimes see
if(is_object($page) && !$page->isError()){
  // its a valid page object
}
micrdy replied on at Permalink Reply
micrdy
Hey John. Thanks for your reply! But I think my question is bad!

Let´s assume that I´m showing a picture with the image-block. The image is shown. Yeah. But now someone removes the image from the server. The database-value for the image (e.g. imageId: 2) is still there but not the image itself. I´m submitting a new add-on to the marketplace but one of the PRB members said, that I have to check if the file/image is available before I get the version. So I got this code:

$file = File::getById($content);
$filePath = $file->getVersion()->getRelativePath();


Now, how is it possible to ensure, that the $file-getVersion() is not called, when the file is not longer available.
JohntheFish replied on at Permalink Reply
JohntheFish
Maybe something like below. Each time you get an object, check it exists before doing anything with it.
$file = File::getById($content);
$rel_path = null;
if(!empty($file)){
  $fv = $file->getVersion();
  if(!empty($fv)){
    $rel_path = $fv->getRelativePath();
  }
}
if($rel_path !== null){
  // whatever
} else {
  // maybe show something else
}
pvernaglia replied on at Permalink Reply
pvernaglia
I think this will do it

for 5.6
$file = File::getById($content);
if ($file instanceof File) {
 $filePath = $file->getVersion()->getRelativePath();
}
for 5.7
$file = File::getById($content);
if ($file instanceof \Concrete\Core\File\File) {
 $filePath = $file->getVersion()->getRelativePath();
}