Created
January 18, 2012 01:29
-
-
Save mikeschinkel/1630212 to your computer and use it in GitHub Desktop.
Proposing an add_autohook_support() function for WordPress.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Simplifies addition of WordPress hooks to a class. | |
* | |
* Simplifies addition of WordPress hooks to a class by adding any method and using WordPress-specific PHPDoc tags | |
* including @wp-autohook, @wp-nohook, @wp-action, @wp-filter and @wp-priority. | |
* | |
* Props Ryan McCue (https://gist.github.com/rmccue) for suggestion to use $method->getDocComment() instead of | |
* passing in method properties via array arguments. | |
* | |
* @see: Initial inspiration: http://kovshenin.com/2012/01/hey-wordpress-how-about-a-wp_plugin-class-3797/ | |
* | |
* @example: https://gist.github.com/1630788 | |
* | |
* @author: Mike Schinkel - http://about.me/mikeschinkel/ | |
*/ | |
/** | |
* @param string|object $target - Class name or instance of class | |
*/ | |
function add_autohook_support( $target ) { | |
$class_reflector = new ReflectionClass( $target ); | |
/** | |
* Look for @wp-autohook to be implicit or explicit, default to explicit. | |
*/ | |
if ( preg_match( '#@wp-autohook\s*(implicit|explicit)#', $class_reflector->getDocComment(), $match ) ) | |
$autohook = trim( $match[1] ); | |
else | |
$autohook = 'explicit'; | |
/** | |
* @var ReflectionMethod $method | |
*/ | |
foreach ( $class_reflector->getMethods( ReflectionMethod::IS_PUBLIC ) as $method ) { | |
$doc_comment = $method->getDocComment(); | |
if ( empty( $doc_comment ) ) { | |
if ( 'implicit' == $autohook ) { | |
$hooks = array( $method->name ); | |
$default_priority = 10; | |
} | |
} else { | |
if ( preg_match( '#@wp-nohook#', $doc_comment ) ) | |
continue; | |
if ( preg_match( '#@wp-filter\s*(.+)#', $doc_comment, $match ) ) | |
$hooks = array_map( 'trim', explode( ',', $match[1] ) ); | |
else if ( preg_match( '#@wp-action\s*(.+)#', $doc_comment, $match ) ) | |
$hooks = array_map( 'trim', explode( ',', $match[1] ) ); | |
else if ( 'implicit' == $autohook ) | |
$hooks = array( $method->name ); | |
else | |
continue; | |
$default_priority = 10; | |
if ( preg_match( '#@wp-priority\s*([1-9][0-9]*)#', $doc_comment, $match ) ) | |
$default_priority = intval( $match[1] ); | |
} | |
$accepted_args = $method->getNumberOfParameters(); | |
for( $i = 0; $i < count( $hooks ); $i++ ) { | |
list( $hookname, $priority ) = explode( ' ', "{$hooks[$i]} {$default_priority}" ); | |
add_filter( $hookname, array( $target, $method->name ), $priority, $accepted_args ); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment