FilesystemAdapter.php 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. <?php
  2. namespace Illuminate\Filesystem;
  3. use Closure;
  4. use Illuminate\Container\Container;
  5. use Illuminate\Contracts\Debug\ExceptionHandler;
  6. use Illuminate\Contracts\Filesystem\Cloud as CloudFilesystemContract;
  7. use Illuminate\Contracts\Filesystem\Filesystem as FilesystemContract;
  8. use Illuminate\Http\File;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Http\UploadedFile;
  11. use Illuminate\Support\Arr;
  12. use Illuminate\Support\Str;
  13. use Illuminate\Support\Traits\Conditionable;
  14. use Illuminate\Support\Traits\Macroable;
  15. use InvalidArgumentException;
  16. use League\Flysystem\FilesystemAdapter as FlysystemAdapter;
  17. use League\Flysystem\FilesystemOperator;
  18. use League\Flysystem\Ftp\FtpAdapter;
  19. use League\Flysystem\Local\LocalFilesystemAdapter as LocalAdapter;
  20. use League\Flysystem\PathPrefixer;
  21. use League\Flysystem\PhpseclibV3\SftpAdapter;
  22. use League\Flysystem\StorageAttributes;
  23. use League\Flysystem\UnableToCopyFile;
  24. use League\Flysystem\UnableToCreateDirectory;
  25. use League\Flysystem\UnableToDeleteDirectory;
  26. use League\Flysystem\UnableToDeleteFile;
  27. use League\Flysystem\UnableToMoveFile;
  28. use League\Flysystem\UnableToProvideChecksum;
  29. use League\Flysystem\UnableToReadFile;
  30. use League\Flysystem\UnableToRetrieveMetadata;
  31. use League\Flysystem\UnableToSetVisibility;
  32. use League\Flysystem\UnableToWriteFile;
  33. use League\Flysystem\Visibility;
  34. use PHPUnit\Framework\Assert as PHPUnit;
  35. use Psr\Http\Message\StreamInterface;
  36. use RuntimeException;
  37. use Symfony\Component\HttpFoundation\StreamedResponse;
  38. /**
  39. * @mixin \League\Flysystem\FilesystemOperator
  40. */
  41. class FilesystemAdapter implements CloudFilesystemContract
  42. {
  43. use Conditionable;
  44. use Macroable {
  45. __call as macroCall;
  46. }
  47. /**
  48. * The Flysystem filesystem implementation.
  49. *
  50. * @var \League\Flysystem\FilesystemOperator
  51. */
  52. protected $driver;
  53. /**
  54. * The Flysystem adapter implementation.
  55. *
  56. * @var \League\Flysystem\FilesystemAdapter
  57. */
  58. protected $adapter;
  59. /**
  60. * The filesystem configuration.
  61. *
  62. * @var array
  63. */
  64. protected $config;
  65. /**
  66. * The Flysystem PathPrefixer instance.
  67. *
  68. * @var \League\Flysystem\PathPrefixer
  69. */
  70. protected $prefixer;
  71. /**
  72. * The file server callback.
  73. *
  74. * @var \Closure|null
  75. */
  76. protected $serveCallback;
  77. /**
  78. * The temporary URL builder callback.
  79. *
  80. * @var \Closure|null
  81. */
  82. protected $temporaryUrlCallback;
  83. /**
  84. * The temporary upload URL builder callback.
  85. *
  86. * @var \Closure|null
  87. */
  88. protected $temporaryUploadUrlCallback;
  89. /**
  90. * Create a new filesystem adapter instance.
  91. *
  92. * @param \League\Flysystem\FilesystemOperator $driver
  93. * @param \League\Flysystem\FilesystemAdapter $adapter
  94. * @param array $config
  95. */
  96. public function __construct(FilesystemOperator $driver, FlysystemAdapter $adapter, array $config = [])
  97. {
  98. $this->driver = $driver;
  99. $this->adapter = $adapter;
  100. $this->config = $config;
  101. $separator = $config['directory_separator'] ?? DIRECTORY_SEPARATOR;
  102. $this->prefixer = new PathPrefixer($config['root'] ?? '', $separator);
  103. if (isset($config['prefix'])) {
  104. $this->prefixer = new PathPrefixer($this->prefixer->prefixPath($config['prefix']), $separator);
  105. }
  106. }
  107. /**
  108. * Assert that the given file or directory exists.
  109. *
  110. * @param string|array $path
  111. * @param string|null $content
  112. * @return $this
  113. */
  114. public function assertExists($path, $content = null)
  115. {
  116. clearstatcache();
  117. $paths = Arr::wrap($path);
  118. foreach ($paths as $path) {
  119. PHPUnit::assertTrue(
  120. $this->exists($path), "Unable to find a file or directory at path [{$path}]."
  121. );
  122. if (! is_null($content)) {
  123. $actual = $this->get($path);
  124. PHPUnit::assertSame(
  125. $content,
  126. $actual,
  127. "File or directory [{$path}] was found, but content [{$actual}] does not match [{$content}]."
  128. );
  129. }
  130. }
  131. return $this;
  132. }
  133. /**
  134. * Assert that the number of files in path equals the expected count.
  135. *
  136. * @param string $path
  137. * @param int $count
  138. * @param bool $recursive
  139. * @return $this
  140. */
  141. public function assertCount($path, $count, $recursive = false)
  142. {
  143. clearstatcache();
  144. $actual = count($this->files($path, $recursive));
  145. PHPUnit::assertEquals(
  146. $count, $actual, "Expected [{$count}] files at [{$path}], but found [{$actual}]."
  147. );
  148. return $this;
  149. }
  150. /**
  151. * Assert that the given file or directory does not exist.
  152. *
  153. * @param string|array $path
  154. * @return $this
  155. */
  156. public function assertMissing($path)
  157. {
  158. clearstatcache();
  159. $paths = Arr::wrap($path);
  160. foreach ($paths as $path) {
  161. PHPUnit::assertFalse(
  162. $this->exists($path), "Found unexpected file or directory at path [{$path}]."
  163. );
  164. }
  165. return $this;
  166. }
  167. /**
  168. * Assert that the given directory is empty.
  169. *
  170. * @param string $path
  171. * @return $this
  172. */
  173. public function assertDirectoryEmpty($path)
  174. {
  175. PHPUnit::assertEmpty(
  176. $this->allFiles($path), "Directory [{$path}] is not empty."
  177. );
  178. return $this;
  179. }
  180. /**
  181. * Determine if a file or directory exists.
  182. *
  183. * @param string $path
  184. * @return bool
  185. */
  186. public function exists($path)
  187. {
  188. return $this->driver->has($path);
  189. }
  190. /**
  191. * Determine if a file or directory is missing.
  192. *
  193. * @param string $path
  194. * @return bool
  195. */
  196. public function missing($path)
  197. {
  198. return ! $this->exists($path);
  199. }
  200. /**
  201. * Determine if a file exists.
  202. *
  203. * @param string $path
  204. * @return bool
  205. */
  206. public function fileExists($path)
  207. {
  208. return $this->driver->fileExists($path);
  209. }
  210. /**
  211. * Determine if a file is missing.
  212. *
  213. * @param string $path
  214. * @return bool
  215. */
  216. public function fileMissing($path)
  217. {
  218. return ! $this->fileExists($path);
  219. }
  220. /**
  221. * Determine if a directory exists.
  222. *
  223. * @param string $path
  224. * @return bool
  225. */
  226. public function directoryExists($path)
  227. {
  228. return $this->driver->directoryExists($path);
  229. }
  230. /**
  231. * Determine if a directory is missing.
  232. *
  233. * @param string $path
  234. * @return bool
  235. */
  236. public function directoryMissing($path)
  237. {
  238. return ! $this->directoryExists($path);
  239. }
  240. /**
  241. * Get the full path to the file that exists at the given relative path.
  242. *
  243. * @param string $path
  244. * @return string
  245. */
  246. public function path($path)
  247. {
  248. return $this->prefixer->prefixPath($path);
  249. }
  250. /**
  251. * Get the contents of a file.
  252. *
  253. * @param string $path
  254. * @return string|null
  255. */
  256. public function get($path)
  257. {
  258. try {
  259. return $this->driver->read($path);
  260. } catch (UnableToReadFile $e) {
  261. throw_if($this->throwsExceptions(), $e);
  262. $this->report($e);
  263. }
  264. }
  265. /**
  266. * Get the contents of a file as decoded JSON.
  267. *
  268. * @param string $path
  269. * @param int $flags
  270. * @return array|null
  271. */
  272. public function json($path, $flags = 0)
  273. {
  274. $content = $this->get($path);
  275. return is_null($content) ? null : json_decode($content, true, 512, $flags);
  276. }
  277. /**
  278. * Create a streamed response for a given file.
  279. *
  280. * @param string $path
  281. * @param string|null $name
  282. * @param array $headers
  283. * @param string|null $disposition
  284. * @return \Symfony\Component\HttpFoundation\StreamedResponse
  285. *
  286. * @throws UnableToRetrieveMetadata
  287. */
  288. public function response($path, $name = null, array $headers = [], $disposition = 'inline')
  289. {
  290. $response = new StreamedResponse;
  291. $headers['Content-Type'] ??= $this->mimeType($path);
  292. $headers['Content-Length'] ??= $this->size($path);
  293. if (! array_key_exists('Content-Disposition', $headers)) {
  294. $filename = $name ?? basename($path);
  295. $disposition = $response->headers->makeDisposition(
  296. $disposition, $filename, $this->fallbackName($filename)
  297. );
  298. $headers['Content-Disposition'] = $disposition;
  299. }
  300. $response->headers->replace($headers);
  301. $response->setCallback(function () use ($path) {
  302. $stream = $this->readStream($path);
  303. fpassthru($stream);
  304. fclose($stream);
  305. });
  306. return $response;
  307. }
  308. /**
  309. * Create a streamed download response for a given file.
  310. *
  311. * @param \Illuminate\Http\Request $request
  312. * @param string $path
  313. * @param string|null $name
  314. * @param array $headers
  315. * @return \Symfony\Component\HttpFoundation\StreamedResponse
  316. *
  317. * @throws UnableToRetrieveMetadata
  318. */
  319. public function serve(Request $request, $path, $name = null, array $headers = [])
  320. {
  321. return isset($this->serveCallback)
  322. ? call_user_func($this->serveCallback, $request, $path, $headers)
  323. : $this->response($path, $name, $headers);
  324. }
  325. /**
  326. * Create a streamed download response for a given file.
  327. *
  328. * @param string $path
  329. * @param string|null $name
  330. * @param array $headers
  331. * @return \Symfony\Component\HttpFoundation\StreamedResponse
  332. *
  333. * @throws UnableToRetrieveMetadata
  334. */
  335. public function download($path, $name = null, array $headers = [])
  336. {
  337. return $this->response($path, $name, $headers, 'attachment');
  338. }
  339. /**
  340. * Convert the string to ASCII characters that are equivalent to the given name.
  341. *
  342. * @param string $name
  343. * @return string
  344. */
  345. protected function fallbackName($name)
  346. {
  347. return str_replace('%', '', Str::ascii($name));
  348. }
  349. /**
  350. * Write the contents of a file.
  351. *
  352. * @param string $path
  353. * @param \Psr\Http\Message\StreamInterface|\Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|resource $contents
  354. * @param mixed $options
  355. * @return string|bool
  356. */
  357. public function put($path, $contents, $options = [])
  358. {
  359. $options = is_string($options)
  360. ? ['visibility' => $options]
  361. : (array) $options;
  362. // If the given contents is actually a file or uploaded file instance than we will
  363. // automatically store the file using a stream. This provides a convenient path
  364. // for the developer to store streams without managing them manually in code.
  365. if ($contents instanceof File ||
  366. $contents instanceof UploadedFile) {
  367. return $this->putFile($path, $contents, $options);
  368. }
  369. try {
  370. if ($contents instanceof StreamInterface) {
  371. $this->driver->writeStream($path, $contents->detach(), $options);
  372. return true;
  373. }
  374. is_resource($contents)
  375. ? $this->driver->writeStream($path, $contents, $options)
  376. : $this->driver->write($path, $contents, $options);
  377. } catch (UnableToWriteFile|UnableToSetVisibility $e) {
  378. throw_if($this->throwsExceptions(), $e);
  379. $this->report($e);
  380. return false;
  381. }
  382. return true;
  383. }
  384. /**
  385. * Store the uploaded file on the disk.
  386. *
  387. * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $path
  388. * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|array|null $file
  389. * @param mixed $options
  390. * @return string|false
  391. */
  392. public function putFile($path, $file = null, $options = [])
  393. {
  394. if (is_null($file) || is_array($file)) {
  395. [$path, $file, $options] = ['', $path, $file ?? []];
  396. }
  397. $file = is_string($file) ? new File($file) : $file;
  398. return $this->putFileAs($path, $file, $file->hashName(), $options);
  399. }
  400. /**
  401. * Store the uploaded file on the disk with a given name.
  402. *
  403. * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $path
  404. * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|array|null $file
  405. * @param string|array|null $name
  406. * @param mixed $options
  407. * @return string|false
  408. */
  409. public function putFileAs($path, $file, $name = null, $options = [])
  410. {
  411. if (is_null($name) || is_array($name)) {
  412. [$path, $file, $name, $options] = ['', $path, $file, $name ?? []];
  413. }
  414. $stream = fopen(is_string($file) ? $file : $file->getRealPath(), 'r');
  415. // Next, we will format the path of the file and store the file using a stream since
  416. // they provide better performance than alternatives. Once we write the file this
  417. // stream will get closed automatically by us so the developer doesn't have to.
  418. $result = $this->put(
  419. $path = trim($path.'/'.$name, '/'), $stream, $options
  420. );
  421. if (is_resource($stream)) {
  422. fclose($stream);
  423. }
  424. return $result ? $path : false;
  425. }
  426. /**
  427. * Get the visibility for the given path.
  428. *
  429. * @param string $path
  430. * @return string
  431. */
  432. public function getVisibility($path)
  433. {
  434. if ($this->driver->visibility($path) == Visibility::PUBLIC) {
  435. return FilesystemContract::VISIBILITY_PUBLIC;
  436. }
  437. return FilesystemContract::VISIBILITY_PRIVATE;
  438. }
  439. /**
  440. * Set the visibility for the given path.
  441. *
  442. * @param string $path
  443. * @param string $visibility
  444. * @return bool
  445. */
  446. public function setVisibility($path, $visibility)
  447. {
  448. try {
  449. $this->driver->setVisibility($path, $this->parseVisibility($visibility));
  450. } catch (UnableToSetVisibility $e) {
  451. throw_if($this->throwsExceptions(), $e);
  452. $this->report($e);
  453. return false;
  454. }
  455. return true;
  456. }
  457. /**
  458. * Prepend to a file.
  459. *
  460. * @param string $path
  461. * @param string $data
  462. * @param string $separator
  463. * @return bool
  464. */
  465. public function prepend($path, $data, $separator = PHP_EOL)
  466. {
  467. if ($this->fileExists($path)) {
  468. return $this->put($path, $data.$separator.$this->get($path));
  469. }
  470. return $this->put($path, $data);
  471. }
  472. /**
  473. * Append to a file.
  474. *
  475. * @param string $path
  476. * @param string $data
  477. * @param string $separator
  478. * @return bool
  479. */
  480. public function append($path, $data, $separator = PHP_EOL)
  481. {
  482. if ($this->fileExists($path)) {
  483. return $this->put($path, $this->get($path).$separator.$data);
  484. }
  485. return $this->put($path, $data);
  486. }
  487. /**
  488. * Delete the file at a given path.
  489. *
  490. * @param string|array $paths
  491. * @return bool
  492. */
  493. public function delete($paths)
  494. {
  495. $paths = is_array($paths) ? $paths : func_get_args();
  496. $success = true;
  497. foreach ($paths as $path) {
  498. try {
  499. $this->driver->delete($path);
  500. } catch (UnableToDeleteFile $e) {
  501. throw_if($this->throwsExceptions(), $e);
  502. $this->report($e);
  503. $success = false;
  504. }
  505. }
  506. return $success;
  507. }
  508. /**
  509. * Copy a file to a new location.
  510. *
  511. * @param string $from
  512. * @param string $to
  513. * @return bool
  514. */
  515. public function copy($from, $to)
  516. {
  517. try {
  518. $this->driver->copy($from, $to);
  519. } catch (UnableToCopyFile $e) {
  520. throw_if($this->throwsExceptions(), $e);
  521. $this->report($e);
  522. return false;
  523. }
  524. return true;
  525. }
  526. /**
  527. * Move a file to a new location.
  528. *
  529. * @param string $from
  530. * @param string $to
  531. * @return bool
  532. */
  533. public function move($from, $to)
  534. {
  535. try {
  536. $this->driver->move($from, $to);
  537. } catch (UnableToMoveFile $e) {
  538. throw_if($this->throwsExceptions(), $e);
  539. $this->report($e);
  540. return false;
  541. }
  542. return true;
  543. }
  544. /**
  545. * Get the file size of a given file.
  546. *
  547. * @param string $path
  548. * @return int
  549. */
  550. public function size($path)
  551. {
  552. return $this->driver->fileSize($path);
  553. }
  554. /**
  555. * Get the checksum for a file.
  556. *
  557. * @return string|false
  558. *
  559. * @throws UnableToProvideChecksum
  560. */
  561. public function checksum(string $path, array $options = [])
  562. {
  563. try {
  564. return $this->driver->checksum($path, $options);
  565. } catch (UnableToProvideChecksum $e) {
  566. throw_if($this->throwsExceptions(), $e);
  567. $this->report($e);
  568. return false;
  569. }
  570. }
  571. /**
  572. * Get the mime-type of a given file.
  573. *
  574. * @param string $path
  575. * @return string|false
  576. *
  577. * @throws UnableToRetrieveMetadata
  578. */
  579. public function mimeType($path)
  580. {
  581. try {
  582. return $this->driver->mimeType($path);
  583. } catch (UnableToRetrieveMetadata $e) {
  584. throw_if($this->throwsExceptions(), $e);
  585. $this->report($e);
  586. }
  587. return false;
  588. }
  589. /**
  590. * Get the file's last modification time.
  591. *
  592. * @param string $path
  593. * @return int
  594. */
  595. public function lastModified($path)
  596. {
  597. return $this->driver->lastModified($path);
  598. }
  599. /**
  600. * {@inheritdoc}
  601. */
  602. public function readStream($path)
  603. {
  604. try {
  605. return $this->driver->readStream($path);
  606. } catch (UnableToReadFile $e) {
  607. throw_if($this->throwsExceptions(), $e);
  608. $this->report($e);
  609. }
  610. }
  611. /**
  612. * {@inheritdoc}
  613. */
  614. public function writeStream($path, $resource, array $options = [])
  615. {
  616. try {
  617. $this->driver->writeStream($path, $resource, $options);
  618. } catch (UnableToWriteFile|UnableToSetVisibility $e) {
  619. throw_if($this->throwsExceptions(), $e);
  620. $this->report($e);
  621. return false;
  622. }
  623. return true;
  624. }
  625. /**
  626. * Get the URL for the file at the given path.
  627. *
  628. * @param string $path
  629. * @return string
  630. *
  631. * @throws \RuntimeException
  632. */
  633. public function url($path)
  634. {
  635. if (isset($this->config['prefix'])) {
  636. $path = $this->concatPathToUrl($this->config['prefix'], $path);
  637. }
  638. $adapter = $this->adapter;
  639. if (method_exists($adapter, 'getUrl')) {
  640. return $adapter->getUrl($path);
  641. } elseif (method_exists($this->driver, 'getUrl')) {
  642. return $this->driver->getUrl($path);
  643. } elseif ($adapter instanceof FtpAdapter || $adapter instanceof SftpAdapter) {
  644. return $this->getFtpUrl($path);
  645. } elseif ($adapter instanceof LocalAdapter) {
  646. return $this->getLocalUrl($path);
  647. } else {
  648. throw new RuntimeException('This driver does not support retrieving URLs.');
  649. }
  650. }
  651. /**
  652. * Get the URL for the file at the given path.
  653. *
  654. * @param string $path
  655. * @return string
  656. */
  657. protected function getFtpUrl($path)
  658. {
  659. return isset($this->config['url'])
  660. ? $this->concatPathToUrl($this->config['url'], $path)
  661. : $path;
  662. }
  663. /**
  664. * Get the URL for the file at the given path.
  665. *
  666. * @param string $path
  667. * @return string
  668. */
  669. protected function getLocalUrl($path)
  670. {
  671. // If an explicit base URL has been set on the disk configuration then we will use
  672. // it as the base URL instead of the default path. This allows the developer to
  673. // have full control over the base path for this filesystem's generated URLs.
  674. if (isset($this->config['url'])) {
  675. return $this->concatPathToUrl($this->config['url'], $path);
  676. }
  677. $path = '/storage/'.$path;
  678. // If the path contains "storage/public", it probably means the developer is using
  679. // the default disk to generate the path instead of the "public" disk like they
  680. // are really supposed to use. We will remove the public from this path here.
  681. if (str_contains($path, '/storage/public/')) {
  682. return Str::replaceFirst('/public/', '/', $path);
  683. }
  684. return $path;
  685. }
  686. /**
  687. * Determine if temporary URLs can be generated.
  688. *
  689. * @return bool
  690. */
  691. public function providesTemporaryUrls()
  692. {
  693. return method_exists($this->adapter, 'getTemporaryUrl') || isset($this->temporaryUrlCallback);
  694. }
  695. /**
  696. * Determine if temporary upload URLs can be generated.
  697. *
  698. * @return bool
  699. */
  700. public function providesTemporaryUploadUrls()
  701. {
  702. return method_exists($this->adapter, 'temporaryUploadUrl') || isset($this->temporaryUploadUrlCallback);
  703. }
  704. /**
  705. * Get a temporary URL for the file at the given path.
  706. *
  707. * @param string $path
  708. * @param \DateTimeInterface $expiration
  709. * @param array $options
  710. * @return string
  711. *
  712. * @throws \RuntimeException
  713. */
  714. public function temporaryUrl($path, $expiration, array $options = [])
  715. {
  716. if (method_exists($this->adapter, 'getTemporaryUrl')) {
  717. return $this->adapter->getTemporaryUrl($path, $expiration, $options);
  718. }
  719. if ($this->temporaryUrlCallback) {
  720. return $this->temporaryUrlCallback->bindTo($this, static::class)(
  721. $path, $expiration, $options
  722. );
  723. }
  724. throw new RuntimeException('This driver does not support creating temporary URLs.');
  725. }
  726. /**
  727. * Get a temporary upload URL for the file at the given path.
  728. *
  729. * @param string $path
  730. * @param \DateTimeInterface $expiration
  731. * @param array $options
  732. * @return array
  733. *
  734. * @throws \RuntimeException
  735. */
  736. public function temporaryUploadUrl($path, $expiration, array $options = [])
  737. {
  738. if (method_exists($this->adapter, 'temporaryUploadUrl')) {
  739. return $this->adapter->temporaryUploadUrl($path, $expiration, $options);
  740. }
  741. if ($this->temporaryUploadUrlCallback) {
  742. return $this->temporaryUploadUrlCallback->bindTo($this, static::class)(
  743. $path, $expiration, $options
  744. );
  745. }
  746. throw new RuntimeException('This driver does not support creating temporary upload URLs.');
  747. }
  748. /**
  749. * Concatenate a path to a URL.
  750. *
  751. * @param string $url
  752. * @param string $path
  753. * @return string
  754. */
  755. protected function concatPathToUrl($url, $path)
  756. {
  757. return rtrim($url, '/').'/'.ltrim($path, '/');
  758. }
  759. /**
  760. * Replace the scheme, host and port of the given UriInterface with values from the given URL.
  761. *
  762. * @param \Psr\Http\Message\UriInterface $uri
  763. * @param string $url
  764. * @return \Psr\Http\Message\UriInterface
  765. */
  766. protected function replaceBaseUrl($uri, $url)
  767. {
  768. $parsed = parse_url($url);
  769. return $uri
  770. ->withScheme($parsed['scheme'])
  771. ->withHost($parsed['host'])
  772. ->withPort($parsed['port'] ?? null);
  773. }
  774. /**
  775. * Get an array of all files in a directory.
  776. *
  777. * @param string|null $directory
  778. * @param bool $recursive
  779. * @return array
  780. */
  781. public function files($directory = null, $recursive = false)
  782. {
  783. return $this->driver->listContents($directory ?? '', $recursive)
  784. ->filter(function (StorageAttributes $attributes) {
  785. return $attributes->isFile();
  786. })
  787. ->sortByPath()
  788. ->map(function (StorageAttributes $attributes) {
  789. return $attributes->path();
  790. })
  791. ->toArray();
  792. }
  793. /**
  794. * Get all of the files from the given directory (recursive).
  795. *
  796. * @param string|null $directory
  797. * @return array
  798. */
  799. public function allFiles($directory = null)
  800. {
  801. return $this->files($directory, true);
  802. }
  803. /**
  804. * Get all of the directories within a given directory.
  805. *
  806. * @param string|null $directory
  807. * @param bool $recursive
  808. * @return array
  809. */
  810. public function directories($directory = null, $recursive = false)
  811. {
  812. return $this->driver->listContents($directory ?? '', $recursive)
  813. ->filter(function (StorageAttributes $attributes) {
  814. return $attributes->isDir();
  815. })
  816. ->map(function (StorageAttributes $attributes) {
  817. return $attributes->path();
  818. })
  819. ->toArray();
  820. }
  821. /**
  822. * Get all the directories within a given directory (recursive).
  823. *
  824. * @param string|null $directory
  825. * @return array
  826. */
  827. public function allDirectories($directory = null)
  828. {
  829. return $this->directories($directory, true);
  830. }
  831. /**
  832. * Create a directory.
  833. *
  834. * @param string $path
  835. * @return bool
  836. */
  837. public function makeDirectory($path)
  838. {
  839. try {
  840. $this->driver->createDirectory($path);
  841. } catch (UnableToCreateDirectory|UnableToSetVisibility $e) {
  842. throw_if($this->throwsExceptions(), $e);
  843. $this->report($e);
  844. return false;
  845. }
  846. return true;
  847. }
  848. /**
  849. * Recursively delete a directory.
  850. *
  851. * @param string $directory
  852. * @return bool
  853. */
  854. public function deleteDirectory($directory)
  855. {
  856. try {
  857. $this->driver->deleteDirectory($directory);
  858. } catch (UnableToDeleteDirectory $e) {
  859. throw_if($this->throwsExceptions(), $e);
  860. $this->report($e);
  861. return false;
  862. }
  863. return true;
  864. }
  865. /**
  866. * Get the Flysystem driver.
  867. *
  868. * @return \League\Flysystem\FilesystemOperator
  869. */
  870. public function getDriver()
  871. {
  872. return $this->driver;
  873. }
  874. /**
  875. * Get the Flysystem adapter.
  876. *
  877. * @return \League\Flysystem\FilesystemAdapter
  878. */
  879. public function getAdapter()
  880. {
  881. return $this->adapter;
  882. }
  883. /**
  884. * Get the configuration values.
  885. *
  886. * @return array
  887. */
  888. public function getConfig()
  889. {
  890. return $this->config;
  891. }
  892. /**
  893. * Parse the given visibility value.
  894. *
  895. * @param string|null $visibility
  896. * @return string|null
  897. *
  898. * @throws \InvalidArgumentException
  899. */
  900. protected function parseVisibility($visibility)
  901. {
  902. if (is_null($visibility)) {
  903. return;
  904. }
  905. return match ($visibility) {
  906. FilesystemContract::VISIBILITY_PUBLIC => Visibility::PUBLIC,
  907. FilesystemContract::VISIBILITY_PRIVATE => Visibility::PRIVATE,
  908. default => throw new InvalidArgumentException("Unknown visibility: {$visibility}."),
  909. };
  910. }
  911. /**
  912. * Define a custom callback that generates file download responses.
  913. *
  914. * @param \Closure $callback
  915. * @return void
  916. */
  917. public function serveUsing(Closure $callback)
  918. {
  919. $this->serveCallback = $callback;
  920. }
  921. /**
  922. * Define a custom temporary URL builder callback.
  923. *
  924. * @param \Closure $callback
  925. * @return void
  926. */
  927. public function buildTemporaryUrlsUsing(Closure $callback)
  928. {
  929. $this->temporaryUrlCallback = $callback;
  930. }
  931. /**
  932. * Define a custom temporary upload URL builder callback.
  933. *
  934. * @param \Closure $callback
  935. * @return void
  936. */
  937. public function buildTemporaryUploadUrlsUsing(Closure $callback)
  938. {
  939. $this->temporaryUploadUrlCallback = $callback;
  940. }
  941. /**
  942. * Determine if Flysystem exceptions should be thrown.
  943. *
  944. * @return bool
  945. */
  946. protected function throwsExceptions(): bool
  947. {
  948. return (bool) ($this->config['throw'] ?? false);
  949. }
  950. /**
  951. * Report the exception.
  952. *
  953. * @param \Throwable $exception
  954. * @return void
  955. *
  956. * @throws \Throwable
  957. */
  958. protected function report($exception)
  959. {
  960. if ($this->shouldReport() && Container::getInstance()->bound(ExceptionHandler::class)) {
  961. Container::getInstance()->make(ExceptionHandler::class)->report($exception);
  962. }
  963. }
  964. /**
  965. * Determine if Flysystem exceptions should be reported.
  966. *
  967. * @return bool
  968. */
  969. protected function shouldReport(): bool
  970. {
  971. return (bool) ($this->config['report'] ?? false);
  972. }
  973. /**
  974. * Pass dynamic methods call onto Flysystem.
  975. *
  976. * @param string $method
  977. * @param array $parameters
  978. * @return mixed
  979. *
  980. * @throws \BadMethodCallException
  981. */
  982. public function __call($method, $parameters)
  983. {
  984. if (static::hasMacro($method)) {
  985. return $this->macroCall($method, $parameters);
  986. }
  987. return $this->driver->{$method}(...$parameters);
  988. }
  989. }