Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the first file of a Finder::files() result?

Tags:

php

symfony

How can I get the first file with symfony/finder component?

I tried to do like this:

<?php
// ...
$finder = new Finder();
$finder
    ->files()
    ->in($this->getKernel()->getRootDir().'/../web/uploads/')
    ->name($filename);

    if (!$finder->count()) {
        throw new NotFoundHttpException('Image not found');
    }

    dump(
        $finder->count(), 
        $finder->getIterator()->current(), 
        $finder->getIterator()->valid()
    );

and I get this result:

1
null
false
like image 362
Dmitry Avatar asked Mar 27 '15 10:03

Dmitry


2 Answers

$iterator = $finder->getIterator();
$iterator->rewind();
$firstFile = $iterator->current();
like image 63
k0pernikus Avatar answered Nov 17 '22 18:11

k0pernikus


Try to rewind first or \var_dump(\iterator_to_array($finder));.

The sequence of an iterator is:

  • rewind
  • valid
  • current/key
  • next
  • valid
  • current/key
  • next
  • ...
like image 6
Aitch Avatar answered Nov 17 '22 20:11

Aitch