Skip to content

Commit

Permalink
Node Attribute Adjustments (#16)
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
rleeson authored Apr 8, 2024
1 parent a522460 commit 503a0ba
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
4 changes: 1 addition & 3 deletions src/Blocks/Model/FlowElementTransform.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
18 changes: 16 additions & 2 deletions src/Blocks/Model/StandardBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -81,15 +89,21 @@ 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 ] );

$classes->addMaybe( $replacement, $nodeHasOriginal );
}

return $classes->join( ' ' );
return trim(
$classes->filterUnique()->filter(
function ( $_item ) {
return ! empty( $_item );
}
)->join( ' ' )
);
}

/**
Expand Down

0 comments on commit 503a0ba

Please sign in to comment.