Detect if page exists on router

Currently the contents of a folder contains only images and the associated data file.

picture/painting-001.jpg
picture/painting-001.jpg.txt
picture/painting-002.jpg
picture/painting-002.jpg.txt
…
picture/painting-023.jpg
picture/painting-023.jpg.txt

As number of pictures is growing, I want to use page for future images. I will create a specific directory with an associated template :

picture/painting-024/painting.txt
picture/painting-024/painting-024a.jpg
picture/painting-024/painting-024b.jpg
picture/painting-024/painting-024c.jpg
…

I don’t want to spend time to convert all images now so I decided to create virtual pages for these old pictures according to this algorithm:

IF the page exists THEN [1]
   display page
ELSE IF image exists THEN  [2]
   create a virtual page with the image information
ELSE  [3]
   display an error message
ENDIF

I tried to implement this algorithm but failed. After a while I noticed that the routing didn’t work anymore whatever the code used. Like there’s a cache somewhere…

pattern' => 'paintings/(:num)/(:alphanum)',
action' => function ($year,$reference) {
     if($page = page('paintings/'.$year.'/'.$reference)->exists()):
         // [1]
         $this->next();

      // else if... TBD
         // [2]
      else:
         return '<html><body>'.$year.'::'.$reference. '</body></html>';
      endif;
     }

I know this is quite simple but I can’t find the syntax!! Please help!