From 503a0ba25e5eae05e33a9dd90c0ab0d568dd4d35 Mon Sep 17 00:00:00 2001 From: Ryan Leeson Date: Mon, 8 Apr 2024 10:21:22 -0400 Subject: [PATCH] Node Attribute Adjustments (#16) - Switch to correct Attribute retrieval function - Ensure mapped classes are unique, remove empties, and trim the class string - Add flag to control whether to keep original classes in standard block mappings --- src/Blocks/Model/FlowElementTransform.php | 4 +--- src/Blocks/Model/StandardBlock.php | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/Blocks/Model/FlowElementTransform.php b/src/Blocks/Model/FlowElementTransform.php index 0745991..cd4a6d7 100644 --- a/src/Blocks/Model/FlowElementTransform.php +++ b/src/Blocks/Model/FlowElementTransform.php @@ -97,9 +97,7 @@ abstract public function supportedTagName(): string; */ public function verifyClassAttribute( Crawler $_element, array $_expectedClasses ): bool { // Manually split and match instead of HtmlPageCrawler hasClass(), which can only handle one class at a time - $attribute = $_element->matches( '*' ) && method_exists( $_element, 'getAttribute' ) - ? $_element->getAttribute( 'class' ) - : null; + $attribute = $_element->matches( '*' ) ? $_element->attr( 'class' ) : null; $classes = preg_split( '/\s+/', $attribute ?? '' ); $checkSet = false !== $classes ? Arrays::from( $classes ) : Arrays::fresh(); diff --git a/src/Blocks/Model/StandardBlock.php b/src/Blocks/Model/StandardBlock.php index 928990c..32a39bb 100644 --- a/src/Blocks/Model/StandardBlock.php +++ b/src/Blocks/Model/StandardBlock.php @@ -69,6 +69,14 @@ protected function filterNodeAndAttributes( Arrays $_domAttributes ): void {} + /** + * Flag whether to keep the original set of Node classes when mapping + * - Override as false in a consuming class to remove the original class listing + */ + protected function keepOriginalMappedClasses(): bool { + return true; + } + /** * Check the nodes class list and replace select classes @@ -81,7 +89,7 @@ protected function mapClasses( Crawler $_node ): string { $classes = Arrays::fresh(); $nodeClasses = $_node->attr( 'class' ) ?? ''; - $classes->addMaybe( $nodeClasses, ! empty( $nodeClasses ) ); + $classes->addMaybe( $nodeClasses, $this->keepOriginalMappedClasses() && ! empty( $nodeClasses ) ); foreach ( $this->classMapping() as $original => $replacement ) { $nodeHasOriginal = $this->verifyClassAttribute( $_node, [ $original ] ); @@ -89,7 +97,13 @@ protected function mapClasses( Crawler $_node ): string { $classes->addMaybe( $replacement, $nodeHasOriginal ); } - return $classes->join( ' ' ); + return trim( + $classes->filterUnique()->filter( + function ( $_item ) { + return ! empty( $_item ); + } + )->join( ' ' ) + ); } /**