Skip to content

Commit

Permalink
introduce TransformersRegistry class to use in registration of transf…
Browse files Browse the repository at this point in the history
…ormers
  • Loading branch information
ashfame committed Dec 26, 2024
1 parent 58e893e commit ee855c9
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions src/plugin/class-transformersregistry.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

namespace DotOrg\TryWordPress;

use InvalidArgumentException;

class TransformersRegistry {
private static array $handlers = array();

/**
* Add a handler for a specific subject type
*
* @param string $type The subject type to handle.
* @param array $identifier Array containing unique slug and description.
* @param callable $handler The handler function.
* @return void
* @throws InvalidArgumentException If handler is not callable.
*/
public static function add( string $type, array $identifier, callable $handler ): void {
if ( ! is_callable( $handler ) ) {
throw new InvalidArgumentException( 'Handler must be callable' );
}

if ( ! isset( $identifier['slug'] ) ) {
throw new InvalidArgumentException( 'Identifier slug must be defined' );
}

if ( ! isset( self::$handlers[ $type ] ) ) {
self::$handlers[ $type ] = array();
}

self::$handlers[ $type ][] = $handler;
}

/**
* Check if handlers exist for a type
*
* @param string $type The type to check.
* @return bool True if handlers exist
*/
public static function has( string $type ): bool {
return isset( self::$handlers[ $type ] ) && ! empty( self::$handlers[ $type ] );
}

/**
* Execute all handlers for a type
*
* @TODO: Invoke this function at the right place in code
*
* @param string $type The type to handle.
* @param mixed|null $data Data to pass to handlers.
* @return array Results from all handlers
*/
public static function handle( string $type, mixed $data = null ): array {
if ( ! self::has( $type ) ) {
return array();
}

$results = array();
foreach ( self::$handlers[ $type ] as $handler ) {
$results[] = $handler( $data );
}

return $results;
}

/**
* Remove all handlers for a type
*
* @param string $type The type to clear handlers for.
* @return void
*/
public static function clear( string $type ): void {
if ( isset( self::$handlers[ $type ] ) ) {
unset( self::$handlers[ $type ] );
}
}
}

0 comments on commit ee855c9

Please sign in to comment.