0

I try to find all the controller files of a java code repository in php script.(Lets say CustomerController.java for example)

Here is the solution i have tried to achieve this goal:

$fileScan = glob($currentDirectory . "**/*Controller.java");

But it returns nothing. I have also tried different combinations like:

"**Controller*.java", "*/*Controller*.java" etc.

But not luck.

Am i missing something here about glob function?

metzelder
  • 655
  • 2
  • 15
  • 35
  • what's the `$currentDirectory` and what is the actual path to your controllers from the webserver ie. `/var/www/yourcode/controllers/` – amurrell Jan 23 '19 at 09:01
  • `glob` is not that powerful in PHP. You can specify patterns like `*/*/*Class.php` but `**` does not have any extended effect. – Pinke Helga Jan 23 '19 at 09:04
  • If you know the platform PHP is running on and system access is not locked, you can find files much faster using shell commands. I even wrote some OS switch in the past to use `find` on iX or `dir /r` on Windows or fallback to PHP when system access is not available. This makes sense when frequently scanning large file systems. – Pinke Helga Jan 23 '19 at 09:35
  • Unfortunately system access is locked. I trigger the script as an admin service user. – metzelder Jan 23 '19 at 09:41
  • If you can specify a max depth, another simple glob approach could be to take (or generate) a pattern like `glob("../../{,*/,*/*/,*/*/*/}*Controller*.java", GLOB_BRACE);` – Pinke Helga Jan 23 '19 at 09:51
  • I've added this as an alternative answer to the duplicate. – Pinke Helga Jan 23 '19 at 10:04

2 Answers2

0

Use RecursiveDirectoryIterator

<?php
function rsearch($folder, $pattern) {
    $dir = new RecursiveDirectoryIterator($folder);
    $ite = new RecursiveIteratorIterator($dir);
    $files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
    $fileList = array();
    foreach($files as $file) {
        $fileList = array_merge($fileList, $file);
    }
    return $fileList;
}
?>
Laurens
  • 2,596
  • 11
  • 21
  • You should flag a question as duplicate instead of just copying other's answer 1:1. – Pinke Helga Jan 23 '19 at 09:09
  • Also, note that behavior can vary between windows and linux, when using this class. Would definitely check docs: "On Windows, you will get the files ordered by name. On Linux they are not ordered." – amurrell Jan 23 '19 at 09:13
0

Try following code. It will find the files with "Controller.java"

foreach (glob("*Controller.java") as $filename) 
{
    echo $filename;
}
  • 1
    Not any difference from my first attempt. The point is, all the file patterns may be deep inside the directory. Thats why i need to recursively iterate through. – metzelder Jan 23 '19 at 09:20