photo/app/Traits/Files.php

79 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace App\Traits;
2019-11-09 02:52:04 +00:00
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
trait Files
{
/**
* Get a list of files
*/
2019-11-09 02:52:04 +00:00
public function getFiles(array $option,string $type): Collection
{
2016-07-04 06:00:33 +00:00
// Make sure we got a directory or a file to import
if (is_null($option['file']) AND is_null($option['dir']))
abort(500,'Missing filename, please use --file= OR --dir=');
2016-07-04 06:00:33 +00:00
Log::info(sprintf('%s: Processing: %s',__METHOD__,($option['file'] ? $option['file'] : $option['dir'])));
2019-11-09 02:52:04 +00:00
$files = collect();
2016-07-04 06:00:33 +00:00
$dir = '';
2019-11-09 02:52:04 +00:00
if ($option['dir'] AND is_dir($option['dir'])) {
2016-07-04 06:00:33 +00:00
// Remove our trailing slash from the directory.
$dir = preg_replace('/\/$/','',$option['dir']);
2016-07-04 06:00:33 +00:00
// Exclude . & .. from the path.
2019-11-09 02:52:04 +00:00
$files = $files->merge(array_diff(scandir($dir),array('.','..')));
2019-11-09 02:52:04 +00:00
} elseif ($option['file'] AND ! is_dir($option['file']) AND file_exists($option['file'])) {
2016-07-04 06:00:33 +00:00
$dir = dirname($option['file']);
2019-11-09 02:52:04 +00:00
$files->push(basename($option['file']));
2016-07-04 06:00:33 +00:00
}
2019-11-09 02:52:04 +00:00
// Determine if our dir is relative to where we store data
2016-07-04 06:00:33 +00:00
$dir = static::path($dir,$type);
2016-07-04 06:00:33 +00:00
// Add our path
if ($dir)
2019-11-09 02:52:04 +00:00
$files->transform(function($value) use ($dir) {
return sprintf('%s/%s',$dir,$value);
});
Log::info(sprintf('%s: Processing: %s (%s)',__METHOD__,($option['file'] ? $option['file'] : $option['dir']),count($files)));
return $files;
}
2019-11-09 02:52:04 +00:00
/**
* Recursively make a parent dir to hold files.
*
* @param $dir
* @return bool
*/
public function makeParentDir($dir)
{
if (is_dir($dir))
return TRUE;
if (! file_exists(dirname($dir)) AND ! $this->makeParentDir(dirname($dir)))
return FALSE;
else
return is_writable(dirname($dir)) AND mkdir($dir);
2016-07-04 06:00:33 +00:00
}
2019-11-09 02:52:04 +00:00
/**
* Return if the dir is a sub dir of our config.
*
* @param $path
* @param $type
* @return string
*/
public static function path($path,$type): string
2016-07-04 06:00:33 +00:00
{
return (strpos($path,config($type.'.dir').'/') === 0) ? str_replace(config($type.'.dir').'/','',$path) : $path;
}
2019-11-09 02:52:04 +00:00
}