|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\Twig; |
| 6 | + |
| 7 | +use Twig\Extension\AbstractExtension; |
| 8 | +use Twig\TwigFunction; |
| 9 | + |
| 10 | +class FileExtension extends AbstractExtension |
| 11 | +{ |
| 12 | + public function getFunctions(): array |
| 13 | + { |
| 14 | + return [ |
| 15 | + new TwigFunction('file', [$this, 'file'], ['is_safe' => ['html']]), |
| 16 | + ]; |
| 17 | + } |
| 18 | + |
| 19 | + public function file($path, bool $preview, bool $download): string |
| 20 | + { |
| 21 | + if (!is_null($path)) { |
| 22 | + $path = trim($path); |
| 23 | + } |
| 24 | + |
| 25 | + if (is_null($path) || strlen($path) === 0 || !file_exists($path)) { |
| 26 | + $output = '<td'; |
| 27 | + $output .= ' class="text-nowrap"'; |
| 28 | + $output .= ' colspan="2"'; |
| 29 | + $output .= '>'; |
| 30 | + |
| 31 | + if (is_null($path)) { |
| 32 | + $output .= ValueExtension::null(); |
| 33 | + } elseif (strlen($path) === 0) { |
| 34 | + $output .= ''; |
| 35 | + } elseif (!file_exists($path)) { |
| 36 | + $output .= self::notexists($path); |
| 37 | + } |
| 38 | + |
| 39 | + $output .= '</td>'; |
| 40 | + } else { |
| 41 | + $output = ''; |
| 42 | + |
| 43 | + if ($preview === true) { |
| 44 | + $output = '<td '; |
| 45 | + $output .= ' class="text-nowrap"'; |
| 46 | + $output .= $download !== true ? ' colspan="2"' : ''; |
| 47 | + $output .= '>'; |
| 48 | + $output .= self::preview($path, true); |
| 49 | + $output .= '</td>'; |
| 50 | + } |
| 51 | + |
| 52 | + if ($download === true) { |
| 53 | + $output .= '<td '; |
| 54 | + $output .= ' class="text-nowrap"'; |
| 55 | + $output .= $preview !== true ? ' colspan="2"' : ''; |
| 56 | + $output .= '>'; |
| 57 | + $output .= self::download($path, $preview && $download ? false : true); |
| 58 | + $output .= '</td>'; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return $output; |
| 63 | + } |
| 64 | + |
| 65 | + private function notexists($path) : string |
| 66 | + { |
| 67 | + return '<span class="text-muted" title="File does not exists." style="cursor: help; font-style: italic;">' |
| 68 | + .'<i class="fas fa-fw fa-exclamation-circle"></i>' |
| 69 | + .' '.basename($path) |
| 70 | + .'</span>'; |
| 71 | + } |
| 72 | + |
| 73 | + private function preview($path, bool $displayFilename) : string |
| 74 | + { |
| 75 | + return '<a href="#" style="text-decoration: none;">' |
| 76 | + .'<i class="far fa-fw fa-eye"></i> ' |
| 77 | + .($displayFilename ? ' '.basename($path) : '') |
| 78 | + .'</a>'; |
| 79 | + } |
| 80 | + |
| 81 | + private function download($path, bool $displayFilename) : string |
| 82 | + { |
| 83 | + return '<a href="#" style="text-decoration: none;">' |
| 84 | + .'<i class="fas fa-fw fa-file-download"></i> ' |
| 85 | + .($displayFilename ? ' '.basename($path) : '') |
| 86 | + .'</a>'; |
| 87 | + } |
| 88 | +} |
0 commit comments