Checking for exist() throws null exception?

Hello there,

I got a problem with checking whether a file exists or not when using the following code:

<?php
   foreach( $sponsors as $img_name ) {
   
      if( $all_sponsors->image($img_name)->exists() ) {
      // do something
   }
?>

To give you some background of the problem. I got sponsors which are just image files with a link as meta information. Now I created a checkbox field that pulls in every image as a checkbox item that you can select. If you hit save you get something like this:

Mainsponsor.txt

Title: Main Sponsors
----
Selected-sponsors: cewe.gif, nikon.png, something.jpg

Now if someone would delete an image (so to speak remove a sponsor by deleting e.g. nikon.png) the data in the file mainsponsor.txt would not change and thus link to a file that does not exist anymore.

Strangely my code breaks when I try to check if the file exists with the following error:
Fatal error: Method Kirby\Patterns\Pattern::__toString() must not throw an exception, caught Error: Call to a member function exists() on null in C:\xampp\htdocs\ww\site\plugins\patterns\lib\helpers.php on line 0

What can I do to avoid a nullpointer exception there?

Thank you

You can just check if the image exists like this:

if( $image = $all_sponsors->image($img_name) ) {
      // do something
   }

:kissing_heart: thank you that works now.

Could you explain why my code was wrong? Shouldn’t I be able to use the exist() function or why is my approach wrong here?

I have no answer at the moment, I’m afraid :blush:

Edit: Somehow it makes sense that you can’t call a method on an object that does not exist, which would, however, render the method pretty useless.

I think exists()only works for Kirby file objects. If the file doesn’t exist,

$all_sponsors->image($img_name)

won’t return a file object and so the method can’t be used …

That’s what I said above, but that’s exactly what you want to check with this method, i.e. if the file object exists.

Oh, I seem to be too tired … somehow didn’t saw your edit … sorry :neutral_face:

No problem at all :slight_smile:

To explain the purpose of the exists() method: It’s part of the Toolkit Media class. Media objects can be created even if the file does not actually exist. In Kirby you will get null however. :slight_smile:

@lukasbestle Yes, certainly, but maybe we should remove it as method from $file in the cheat sheet, then, as it does not make sense?

I don’t think we can remove it (docs inheritance), but maybe we should add a note to it that it can’t be used when chaining.

2 Likes

Please do that, we just spent a good ammount of time trying to figure out what was happening and ended up asking ourselves ‘why does exist exists?’ :wink:

Other than pointing at the inheritance the cheat sheet for exist is pretty empty, anything would have helped.

Thank you