Giter Site home page Giter Site logo

generator's Introduction

WP Hooks Generator

Generates a JSON representation of the WordPress actions and filters in your code. Can be used with WordPress plugins, themes, and core.

Note: If you just want the hook files without generating them yourself, use the following packages instead:

Installation

composer require wp-hooks/generator

Generating the Hook Files

./bin/wp-hooks-generator --input=src --output=hooks

Usage of the Generated Hook Files in PHP

// Get hooks as JSON:
$actions_json = file_get_contents( 'hooks/actions.json' );
$filters_json = file_get_contents( 'hooks/filters.json' );

// Convert hooks to PHP:
$actions = json_decode( $actions_json, true )['hooks'];
$filters = json_decode( $filters_json, true )['hooks'];

// Search for filters matching a string:
$search = 'permalink';
$results = array_filter( $filters, function( array $hook ) use ( $search ) {
    return ( false !== strpos( $hook['name'], $search ) );
} );

var_dump( $results );

Usage of the Generated Hook Files in JavaScript

// Get hooks as array of objects:
const actions = require('hooks/actions.json').hooks;
const filters = require('hooks/filters.json').hooks;

// Search for actions matching a string:
const search = 'menu';
const results = actions.filter( hook => ( null !== hook.name.match( search ) ) );

console.log(results);

Ignoring Files or Directories

You can ignore files or directories in two ways:

On the Command Line

./vendor/bin/wp-hooks-generator --input=src --output=hooks --ignore-files="ignore/this,ignore/that"

In composer.json

"extra": {
    "wp-hooks": {
        "ignore-files": [
            "ignore/this",
            "ignore/that"
        ]
    }
}

Ignoring Hooks

You can ignore hooks in two ways:

On the Command Line

./vendor/bin/wp-hooks-generator --input=src --output=hooks --ignore-hooks="this_hook,that_hook"

In composer.json

"extra": {
    "wp-hooks": {
        "ignore-hooks": [
            "this_hook",
            "that_hook"
        ]
    }
}

TypeScript Interfaces for the Hook Files

The TypeScript interfaces for the hook files can be found in interface/index.d.ts. Usage:

import { Hooks, Hook, Doc, Tags, Tag } from 'hooks/index.d.ts';

JSON Schema for the Hook Files

The JSON schema for the hook files can be found in schema.json.

generator's People

Contributors

johnbillion avatar kkmuffme avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

generator's Issues

Function call inside a WC action hook

On woocommerce this action calls a function on the dynamic portion of the hook:

do_action( 'woocommerce_settings_' . sanitize_title( $value['id'] ) . '_end' );

class-wc-admin-settings.php#L304

generating this wrong output:

        {
            "name": "{$value['id'])}_end",
            "file": "plugins\\woocommerce\\includes\\admin\\class-wc-admin-settings.php",
            "type": "action",
            "doc": {
                "description": "",
                "long_description": "",
                "tags": [],
                "long_description_html": ""
            },
            "args": 0
        }

it is related to this code in the WP Parser Lib ?:

		if ( preg_match(
			'/(?:[\'"]([^\'"]*)[\'"]\s*\.\s*)?' . // First filter name string (optional)
			'(\$[^\s]*)' .                        // Dynamic variable
			'(?:\s*\.\s*[\'"]([^\'"]*)[\'"])?/',  // Second filter name string (optional)
			$name, $matches ) ) {

			if ( isset( $matches[3] ) ) {
				return $matches[1] . '{' . $matches[2] . '}' . $matches[3];
			} else {
				return $matches[1] . '{' . $matches[2] . '}';
			}
		}

https://github.com/wp-hooks/parser/blob/293f33ce3705a4d131acc7062b9de8d8b30df2e1/lib/class-hook-reflector.php#L35

thanks

add deprecated field

would be nice if filters/action that are called with do_action_deprecated or apply_filters_deprecated had a field deprecated: true or something

Or action_deprecated/filter_deprecated type would maybe even make more sense

Happy to provide a PR

Issues with array notation

e.g.

* @param array<string, array{name: string, class: string, placeholder?: string, type: string, label: string, required: bool}> $form_fields array of form fields and attributes
* @param array<string, string>|false                                                                                          $saved_form saved form values

isn't parsed correctly and ends up completely garbled in the .json

Multiline filter parse error

Parse Error: Syntax error, unexpected ')' on line ...

when doing this:

/**
 * Get packages details
 *
 * @param array
 * @param int $order_id
 */
$hello = apply_filters(
	'hello_world',
	array(),
	$order_id,
);

Reimplement the validator

The validator script in src/validate.php needs to be updated to handle the new structure of the repo.

Provide long descriptions in their raw markdown

The WP Parser library converts long descriptions for hooks into HTML from their source markdown. A consumer may want the raw markdown so it can convert it itself instead of having to deal with HTML.

Unable to parse files that contain namespaces and variables passed by reference

If I place a single use statement at the top of a file, none of the actions or filters get parsed.

This wouldn't find the example filter:

<?php // Just an example
use GV\Utils;

apply_filters( 'example', 'just an' );

But this would:

<?php // Just an example

apply_filters( 'example', 'just an' );

This also applies to namespaces inside _deprecated_function() calls. This blocks all filters for the file:

_deprecated_function( __METHOD__, '2.0', '\GV\Widget::registered()' );

but removing the namespace fixes it:

_deprecated_function( __METHOD__, '2.0', 'Widget::registered()' );

Same with variables passed by reference. This blocks all parsing for a file:

foreach( $examples as &$example ) {

and this works:

foreach( $examples as $example ) {

When running the command (./vendor/bin/wp-hooks-generator --input ./ --output docs), I get many errors like this:

Warning: Undefined array key 265 in [path]/wp-content/plugins/GravityView/vendor/nikic/php-parser/lib/PhpParser/Lexer.php on line 195

Warning: Undefined array key "" in [path]/wp-content/plugins/GravityView/vendor/nikic/php-parser/lib/PhpParser/ParserAbstract.php on line 173

Warning: Undefined array key "" in [path]/wp-content/plugins/GravityView/vendor/nikic/php-parser/lib/PhpParser/ParserAbstract.php on line 335
Parse Error: Syntax error, unexpected , expecting T_STRING or T_NS_SEPARATOR or '{' on line 10

Here's my composer.json and composer.lock file. Hopefully that helps. Please let me know if I'm able to help figure out what's going on here.

Output file that contains a parse error

Parse Error: Syntax error, unexpected '?', expecting T_VARIABLE on line 14Parse Error: Syntax error, unexpected '?', expecting T_VARIABLE on line 138Parse Error: Syntax error, unexpected '?', expecting T_VARIABLE on line 14Done

No idea in which files the tool encountered a parse error. Would it be possible to include the file name in the error message?

Update dependences versions

As now install this create conflicts with Psalm as example because of php-parser package.

Maybe they are old (2 years~) in the composer.json and just need a bump.

Error on executing the binary

@johnbillion

I'm including this library in my plugin via composer and then tried executing "php ./vendor/bin/wp-hooks-generator " from plugin's root folder in the command line (Ubuntu server) but got the following error:

`dir=$(cd "${0%[/\]*}" > /dev/null; cd ../johnbillion/wp-hooks-generator/bin && pwd)

if [ -d /proc/cygdrive ]; then
case $(which php) in
$(readlink -n /proc/cygdrive)/*)
# We are in Cygwin using Windows php, so the path must be translated
dir=$(cygpath -m "$dir");
;;
esac
fi

"${dir}/wp-hooks-generator" "$@"`

Any idea what went wrong? ...or further examples on how to use this library properly?

My intention is to use the generator to list all hooks from all the WordPress plugins installed. So, gussing I should put the plugins root folder in the --src= parameter, but can not proceed to that step just yet.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.