daily pastebin goal
6%
SHARE
TWEET

Untitled

a guest Dec 19th, 2018 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. namespace App\Services\Utils;
  4.  
  5. use App\Contracts\Utils\FindClassesInNamespaceContract;
  6. use Illuminate\Support\Str;
  7. use Symfony\Component\Finder\Finder;
  8.  
  9. class FindClassesInNamespace implements FindClassesInNamespaceContract
  10. {
  11.     /**
  12.      * @var Finder
  13.      */
  14.     protected $finder;
  15.  
  16.     /**
  17.      * @var array
  18.      */
  19.     protected $namespacePathMap;
  20.  
  21.     /**
  22.      * FindClassesInNamespace constructor.
  23.      * @param Finder $finder
  24.      */
  25.     public function __construct(Finder $finder)
  26.     {
  27.         $this->finder = $finder;
  28.         $this->namespacePathMap = [
  29.             'App' => base_path('app'),
  30.             'Gazelkin' => base_path('src')
  31.         ];
  32.     }
  33.  
  34.     /**
  35.      * @param string $namespace
  36.      * @return \Traversable&string[]
  37.      */
  38.     public function find(string $namespace): \Traversable
  39.     {
  40.         $pathPrefix = $this->getPathPrefix($namespace);
  41.         $path = $this->makePathFromNamespace($pathPrefix, $namespace);
  42.  
  43.         foreach ($this->findFiles($path) as $file) {
  44.             yield Str::after(
  45.                 str_replace(['/', '.php'], ['\\', ''], $file->getPathname()),
  46.                 $pathPrefix . DIRECTORY_SEPARATOR
  47.             );
  48.         }
  49.     }
  50.  
  51.     /**
  52.      * @param string $namespace
  53.      * @return string
  54.      */
  55.     private function getPathPrefix(string $namespace): string
  56.     {
  57.         foreach ($this->namespacePathMap as $prefix => $path) {
  58.             if (Str::startsWith($namespace, $prefix)) {
  59.                 return $path;
  60.             }
  61.         }
  62.  
  63.         throw new \InvalidArgumentException('Unknown namespace');
  64.     }
  65.  
  66.     /**
  67.      * @param string $pathPrefix
  68.      * @param string $namespace
  69.      * @return string
  70.      */
  71.     private function makePathFromNamespace(string $pathPrefix, string $namespace): string
  72.     {
  73.         $path = str_replace('\\', '/', $namespace);
  74.  
  75.         return $pathPrefix . '/' . $path;
  76.     }
  77.  
  78.     /**
  79.      * @param $path
  80.      * @return \Traversable&\SplFileInfo[]
  81.      */
  82.     private function findFiles($path): \Traversable
  83.     {
  84.         return $this->finder->files()->in($path)->name('*.php');
  85.     }
  86. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top