33namespace Flectar \Fancybox ;
44
55use s9e \TextFormatter \Renderer ;
6- use s9e \TextFormatter \Utils ;
76
87class WrapImagesInGallery
98{
10- const MATCH_IMG_TAGS = '((?:<UPL-IMAGE-PREVIEW[^>]*>(?:(?!<\/UPL-IMAGE-PREVIEW>).)*<\/UPL-IMAGE-PREVIEW>)|(?:<IMG[^>]*>(?:(?!<\/IMG>).)*<\/IMG>)) ' ;
11- const MATCH_GALLERY_REGEX = '((?: ' .self ::MATCH_IMG_TAGS .'(?:\s*(?:<br\/>|<br>|\n)\s*)?){2,}) ' ;
12-
139 public function __invoke (Renderer $ renderer , $ context , string $ xml ): string
1410 {
15- return preg_replace_callback ('/ ' .self ::MATCH_GALLERY_REGEX .'/m ' , function ($ matches ) {
16- $ images = array_filter (preg_split ('/\s*(?:<br\/>|<br>|\n)\s*/ ' , $ matches [0 ]), function ($ img ) {
17- return !empty ($ img );
18- });
19- $ galleryItems = array_map (function ($ img ) {
20- return '<FANCYBOX-GALLERY-ITEM> ' . trim ($ img ) . '</FANCYBOX-GALLERY-ITEM> ' ;
21- }, $ images );
11+ $ pattern = '/ ' .
12+ '(?:<[IPr]\s[^>]*>)* ' .
13+ '( ' .
14+ '(?: ' .
15+ '(?:<IMG[^>]*>(?:<\/IMG>)?|<UPL-IMAGE-PREVIEW[^>]*>(?:<\/UPL-IMAGE-PREVIEW>)?) ' .
16+ '(?:\s*<[br]\s*\/?>\s*)* ' .
17+ '){2,} ' .
18+ ') ' .
19+ '(?:<\/[IPr]>)* ' .
20+ '/s ' ;
21+
22+ return preg_replace_callback ($ pattern , function ($ matches ) {
23+ $ imagesBlock = $ matches [1 ];
2224
23- return '<FANCYBOX-GALLERY> ' . implode ('' , $ galleryItems ) . '</FANCYBOX-GALLERY> ' ;
25+ $ images = preg_split ('/<[br]\s*\/?>/ ' , $ imagesBlock );
26+ $ images = array_filter (array_map ('trim ' , $ images ));
27+
28+ if (count ($ images ) < 2 ) {
29+ return $ matches [0 ];
30+ }
31+
32+ $ wrappedImages = array_map (function ($ img ) {
33+ return '<FANCYBOX-GALLERY-ITEM> ' . $ img . '</FANCYBOX-GALLERY-ITEM> ' ;
34+ }, $ images );
35+
36+ return '<FANCYBOX-GALLERY> ' . implode ('' , $ wrappedImages ) . '</FANCYBOX-GALLERY> ' ;
2437 }, $ xml );
2538 }
26- }
39+ }
0 commit comments