|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Yajra\CMS\Http\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Symfony\Component\Finder\Finder; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class BrowsableTrait |
|
9
|
|
|
* |
|
10
|
|
|
* @package App\Http\Traits |
|
11
|
|
|
*/ |
|
12
|
|
|
trait BrowsableTrait |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* Media public storage. |
|
16
|
|
|
* |
|
17
|
|
|
* @var string |
|
18
|
|
|
*/ |
|
19
|
|
|
public $mediaPath = 'app/public/media'; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Show all directories on media path. |
|
23
|
|
|
* |
|
24
|
|
|
* @return array |
|
25
|
|
|
*/ |
|
26
|
|
|
public function getFileDirectories() |
|
27
|
|
|
{ |
|
28
|
|
|
$mediaFiles['/'] = '/'; |
|
|
|
|
|
|
29
|
|
|
$path = storage_path($this->mediaPath); |
|
30
|
|
|
foreach ($this->getFiles($path)->directories() as $file) { |
|
31
|
|
|
$strFile = str_replace($path, '', $file->getRealPath()); |
|
32
|
|
|
$mediaFiles[$strFile] = $strFile; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
return $mediaFiles; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Show all files on selected path. |
|
40
|
|
|
* |
|
41
|
|
|
* @param string $currentPath |
|
42
|
|
|
* @param array $mediaFiles |
|
43
|
|
|
* @return array |
|
44
|
|
|
*/ |
|
45
|
|
|
public function getMediaFiles($currentPath = null, $mediaFiles = []) |
|
46
|
|
|
{ |
|
47
|
|
|
$path = storage_path('app/public/media' . $currentPath); |
|
48
|
|
|
foreach (Finder::create()->in($path)->sortByType()->depth(0) as $file) { |
|
49
|
|
|
$mediaFiles[] = [ |
|
50
|
|
|
'filename' => $file->getFilename(), |
|
51
|
|
|
'realPath' => $file->getRealPath(), |
|
52
|
|
|
'type' => $file->getType(), |
|
53
|
|
|
'filepath' => str_replace(storage_path('app/public/media'), '', $file->getRealPath()), |
|
54
|
|
|
]; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return $mediaFiles; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Symfony file finder. |
|
62
|
|
|
* Show all files in selected $path directory. |
|
63
|
|
|
* Sort by file type. |
|
64
|
|
|
* |
|
65
|
|
|
* @param string $path |
|
66
|
|
|
* @return \Symfony\Component\Finder\Finder |
|
67
|
|
|
*/ |
|
68
|
|
|
public function getFiles($path) |
|
69
|
|
|
{ |
|
70
|
|
|
return Finder::create()->in($path)->sortByType(); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
|
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArrayis initialized the first time when the foreach loop is entered. You can also see that the value of thebarkey is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.