123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace App\Services\File;
- use App\Models\File;
- use DOMDocument;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Str;
- class ImageUrlService
- {
- public function interceptImageUrl(?string $comment): bool|string|null
- {
- if (! $comment) {
- return null;
- }
- $newComment = null;
- $dom = new DOMDocument();
- libxml_use_internal_errors(true);
- $dom->loadHTML($comment, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
- libxml_clear_errors();
-
- $imgTags = $dom->getElementsByTagName('img');
- if($imgTags->length>0){
-
- foreach ($imgTags as $imgTag) {
- $src = $imgTag->getAttribute('src');
-
- $fildPos = strpos($src, 'fild_');
-
- if ($fildPos !== false) {
- $src = substr($src, $fildPos);
- } else {
-
- $src = '';
- }
-
- $imgTag->setAttribute('src', $src);
- }
- $newComment = $dom->saveHTML();
- }
- return $newComment??$comment;
- }
- public function getImageUrl(string $comment){
- if (! $comment) {
- return $comment;
- }
- $newComment = null;
- preg_match_all('/<img\s+[^>]*src=[\'"]([^\'"]*)[\'"][^>]*>/i', $comment, $matches);
- $ids = [];
-
- foreach ($matches[1] as $src) {
-
- if (preg_match('/fild_(\d+)/', $src, $idMatch)) {
- $ids[] = $idMatch[1];
- }
- }
- if(!empty($ids)){
- $files=File::query()->whereIn('id',$ids)->get();
- $search = [];
- $replace = [];
- foreach ($files as $file){
- $url=Storage::url($file->pathname);
- $placeholder = "fild_" . $file->id;
- $search[] = $placeholder;
- $replace[] = $url."&fild_".$file->id;
- }
- $newComment=Str::replace($search, $replace, $comment);
- }
- return $newComment??$comment;
- }
- }
|