silverstripe

How Can I filter by a function in silverstripe


I want to get a list of Files that are missing for a SilverStripe report.

The filesize is not directly stored in the database, instead I have to call method getSize()

If I try to iterate through the records and just choose the empty records, I only get the first level of the file hierarchy

    $all_files = File::get()->sort('FileFilename');
    $list = new ArrayList();

    foreach ($all_files as $file) {
      $file->mysize = $file->getSize();
      if($file->getSize() == "" && $file->ClassName != 'SilverStripe\Assets\Folder'){
         $list->push($file);
      }
    }
    return $list;

How can I get all the records that are empty files?


Solution

  • there are 2 parts to your question:

    to filter by a function, there is:

    $list = $all_files->filterByCallback(function($file) { 
      return $file->getSize() == "" && $file->ClassName != 'SilverStripe\Assets\Folder';
    });
    

    This is a nice shorthand but does exactly what you are doing with your foreach


    For the second part of your question:

    I think you misunderstood how hierarchy in SilverStripe works.
    If you do File::get() you will get all files regardless of their position in the hierarchy.

    So you already have what you want I think. But if you only want files at the top level, you have to do $files = File::get()->filter(["ParentID" => 0]) and if you want a tree, then do a recursive loop with $file->Children().
    Or you do what you've already done: fetch all of them, and then build a tree yourself based on the ParentID.