FilesystemIteratorΒΆ

FilesystemIterator seems preferrable to be prefered to DirectoryIterator. See http://stackoverflow.com/questions/12532064/difference-between-directoryiterator-and-filesystemiterator

<?php
 require_once("loader/SplClassLoader.php");

 $loader = new SplClassLoader('Library', 'src/');
 $loader->register();
 use Library\FileListitemsBuilder;

 try {

    // Build the order list of .iso files.
    $builder = new FileListitemsBuilder();

     echo $builder;

 } catch (Exception $e) {

     echo get_class($e) . ": " . $e->getMessage();
 }

The FileListitemsBuilder belows uses FilesystemIterator and a derived FilterIterator class, FileExtensionFilter.

 <?php
 namespace Jeremiah;

 class FileOrderedlistBuilder {

    private $FileIter;
    private $prefix;
    private $suffix;

    public function __construct($extension)
    {
       $FileSystemIter = new \FilesystemIterator(".", \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS);

       $this->FileIter = new FileExtensionFilter($FileSystemIter, $extension);
    }

    public function getListItems()
    {
        $files = array();

        $html = '';

        foreach ($this->FileIter as $fileInfo) {

           $files[$fileInfo->getPathname()]  = $fileInfo->getFileName();
       }

       natsort($files);

       foreach ($files as $key => $filename) {

          $html .= "<li><a href='" . $key . "'>" . $filename . "</a></li>\n";
       }

       return $html;
    }
 }


class FileExtensionFilter extends \FilterIterator {

    private $extension;

    public function __construct(\Iterator $iter, $extension_filter)
    {
         parent::__construct($iter);
         $this->extension = $extension_filter;
    }

    public function accept()
    {
         $splfileinfo = $this->getInnerIterator()->current();

         if ($splfileinfo->isFile() === false) {

             return false;
         }

         $ext =  $splfileinfo->getExtension();

         if($ext == $this->extension) {

             return true;
         }

         return false;
    }
 }