From 02fe8b5e06c632fc92dbbfe3ef90bd6062abea48 Mon Sep 17 00:00:00 2001 From: Josantonius Date: Wed, 8 Nov 2017 23:34:21 +0100 Subject: [PATCH] Updated to 1.0.9 version --- .gitattributes | 15 ++-- .gitignore | 13 ++-- .php_cs.dist | 120 ++++++++++++++++++++++++++++++++ .travis.yml | 9 ++- CHANGELOG.md | 8 +++ CONDUCT.md | 75 ++++++++++++++++---- README-ES.md | 47 ++++++++----- README.md | 32 ++++++--- _config.yml | 1 - composer.json | 27 ++++--- contributors.txt | 1 - phpcs.ruleset.xml => phpcs.xml | 6 +- phpmd.xml | 45 ++++++++++++ phpunit.xml.dist => phpunit.xml | 4 +- src/Hook.php | 42 ++++++----- tests/Example.php | 23 ------ tests/HookTest.php | 94 +++++++++++++------------ 17 files changed, 407 insertions(+), 155 deletions(-) create mode 100644 .php_cs.dist delete mode 100644 _config.yml delete mode 100644 contributors.txt rename phpcs.ruleset.xml => phpcs.xml (53%) create mode 100644 phpmd.xml rename phpunit.xml.dist => phpunit.xml (95%) diff --git a/.gitattributes b/.gitattributes index 506cc19..2b2dd96 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,14 +1,11 @@ /tests export-ignore -.gitattributes export-ignore -.gitignore export-ignore -_config.yml export-ignore -.travis.yml export-ignore CHANGELOG.md export-ignore -phpunit.xml.dist export-ignore -CONDUCT.md export-ignore -contributors.txt export-ignore README.md export-ignore -phpcs.ruleset.xml export-ignore README-ES.md export-ignore +phpcs.xml export-ignore +phpunit.xml export-ignore +phpmd.xml export-ignore +.travis.yml export-ignore .editorconfig export-ignore -composer.lock export-ignore \ No newline at end of file +.gitattributes export-ignore +.gitignore export-ignore \ No newline at end of file diff --git a/.gitignore b/.gitignore index 8653580..b5216cd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,12 @@ -phpunit.xml +.git*/ +vendor/ +docs/*.pyc +docs/_build +build/artifacts/ composer.phar composer.lock composer-test.lock -build/artifacts/ -vendor/ -docs/_build -docs/*.pyc -.git*/ +phpcbf-fixed.diff .idea .DS_STORE +.php_cs.cache \ No newline at end of file diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 0000000..6735b7d --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,120 @@ +setRiskyAllowed(true) + ->setRules(array( + '@PSR2' => true, + 'array_syntax' => ['syntax' => 'short'], + 'binary_operator_spaces' => ['align_equals' => false, 'align_double_arrow' => false], + 'blank_line_after_opening_tag' => true, + 'blank_line_after_namespace' => false, + 'blank_line_before_return' => true, + 'cast_spaces' => true, +// 'class_keyword_remove' => true, + 'combine_consecutive_unsets' => true, + 'concat_space' => ['spacing' => 'one'], + 'declare_equal_normalize' => true, + 'declare_strict_types' => false, + 'dir_constant' => true, + 'ereg_to_preg' => true, + 'function_typehint_space' => true, +// 'general_phpdoc_annotation_remove' => ['author', 'category', 'package', 'copyright', 'version'], + 'hash_to_slash_comment' => true, + 'heredoc_to_nowdoc' => true, + 'include' => true, + 'indentation_type' => true, +// 'is_null' => ['use_yoda_style' => false], + 'linebreak_after_opening_tag' => true, + 'lowercase_cast' => true, +// 'mb_str_functions' => true, + 'method_separation' => true, + 'modernize_types_casting' => true, + 'native_function_casing' => true, +// 'native_function_invocation' => true, + 'new_with_braces' => false, // + 'no_alias_functions' => true, + 'no_blank_lines_after_class_opening' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_blank_lines_before_namespace' => true, + 'no_empty_comment' => true, + 'no_empty_phpdoc' => true, + 'no_empty_statement' => true, + 'no_extra_consecutive_blank_lines' => ['break', 'continue', 'curly_brace_block', 'extra', 'parenthesis_brace_block', 'return', 'square_brace_block', 'throw', 'use', 'useTrait'], + 'no_leading_import_slash' => true, + 'no_leading_namespace_whitespace' => true, + 'no_mixed_echo_print' => ['use' => 'echo'], + 'no_multiline_whitespace_around_double_arrow' => true, + 'no_multiline_whitespace_before_semicolons' => true, + 'no_php4_constructor' => true, + 'no_short_bool_cast' => true, + 'no_short_echo_tag' => false, + 'no_singleline_whitespace_before_semicolons' => true, + 'no_spaces_around_offset' => true, + 'no_trailing_comma_in_list_call' => true, + 'no_trailing_comma_in_singleline_array' => true, + 'no_trailing_whitespace' => true, + 'no_trailing_whitespace_in_comment' => true, + 'no_unneeded_control_parentheses' => true, + 'no_unreachable_default_argument_value' => true, + 'no_unused_imports' => true, + 'no_useless_else' => true, + 'no_useless_return' => true, + 'no_whitespace_before_comma_in_array' => true, + 'no_whitespace_in_blank_line' => true, + 'normalize_index_brace' => true, + 'not_operator_with_space' => false, + 'not_operator_with_successor_space' => true, + 'object_operator_without_whitespace' => true, + 'ordered_class_elements' => true, + 'ordered_imports' => true, + 'php_unit_construct' => true, + 'php_unit_dedicate_assert' => true, + 'php_unit_fqcn_annotation' => true, + 'php_unit_strict' => true, +// 'phpdoc_add_missing_param_annotation' => true, + 'phpdoc_align' => true, + 'phpdoc_annotation_without_dot' => true, + 'phpdoc_indent' => true, + 'phpdoc_inline_tag' => true, + 'phpdoc_no_access' => true, + 'phpdoc_no_alias_tag' => ['property-read' => 'property', 'property-write' => 'property', 'type' => 'var'], + 'phpdoc_no_empty_return' => true, + 'phpdoc_no_package' => true, +// 'phpdoc_no_useless_inheritdoc' => true, + 'phpdoc_order' => true, + 'phpdoc_return_self_reference' => true, + 'phpdoc_scalar' => true, + 'phpdoc_separation' => false, + 'phpdoc_single_line_var_spacing' => true, +// 'phpdoc_summary' => true, + 'phpdoc_to_comment' => true, + 'phpdoc_trim' => true, + 'phpdoc_types' => true, + 'phpdoc_var_without_name' => true, + 'pow_to_exponentiation' => true, +// 'pre_increment' => true, + 'protected_to_private' => true, + 'psr0' => true, + 'psr4' => true, + 'random_api_migration' => true, + 'return_type_declaration' => ['space_before' => 'one'], + 'self_accessor' => true, + 'short_scalar_cast' => true, +// 'silenced_deprecation_error' => true, +// 'simplified_null_return' => true, + 'single_blank_line_before_namespace' => false, + 'single_quote' => true, + 'space_after_semicolon' => true, + 'standardize_not_equals' => true, +// 'strict_comparison' => true, + 'ternary_operator_spaces' => true, + 'strict_param' => true, + 'ternary_to_null_coalescing' => false, +// 'trailing_comma_in_multiline_array' => true, + 'trim_array_spaces' => true, + 'unary_operator_spaces' => true, + 'whitespace_after_comma_in_array' => true + )) + ->setFinder( + PhpCsFixer\Finder::create() + ->in(__DIR__) + )->setLineEnding("\n"); diff --git a/.travis.yml b/.travis.yml index 71306ca..8b88f00 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,10 @@ language: php sudo: false +cache: + directories: + - $HOME/.composer/cache + dist: trusty branches: @@ -18,7 +22,7 @@ php: - 7.2 - hhvm - nightly - + matrix: fast_finish: true include: @@ -37,7 +41,8 @@ script: - phpunit - | if [[ "$PHPCS" ]] ; then - phpcs --standard=phpcs.ruleset.xml $(find . -name '*.php') + phpcs --standard=phpcs.xml $(find . -name '*.php') + phpmd src,tests text ./phpmd.xml fi phpunit --coverage-clover=coverage.xml diff --git a/CHANGELOG.md b/CHANGELOG.md index 31c49f9..21604dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # CHANGELOG +## 1.0.9 - 2017-11-08 + +* Implemented `PHP Mess Detector` to detect inconsistencies in code styles. + +* Implemented `PHP Code Beautifier and Fixer` to fixing errors automatically. + +* Implemented `PHP Coding Standards Fixer` to organize PHP code automatically according to PSR standards. + ## 1.0.8 - 2017-10-30 * Implemented `PSR-4 autoloader standard` from all library files. diff --git a/CONDUCT.md b/CONDUCT.md index 6ff94ca..30f74c5 100644 --- a/CONDUCT.md +++ b/CONDUCT.md @@ -1,22 +1,73 @@ -# Contributor Code of Conduct +# Contributor Covenant Code of Conduct -As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. +## Our Pledge -We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members Examples of unacceptable behavior by participants include: -* The use of sexualized language or imagery -* Personal attacks -* Trolling or insulting/derogatory comments +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment -* Publishing other's private information, such as physical or electronic addresses, without explicit permission -* Other unethical or unprofessional conduct. +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at [INSERT EMAIL ADDRESS]. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. -This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community in a direct capacity. Personal views, beliefs and values of individuals do not necessarily reflect those of the organisation or affiliated individuals and organisations. +## Attribution -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html -This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) +[homepage]: https://www.contributor-covenant.org diff --git a/README-ES.md b/README-ES.md index 9f9bb25..01eb77f 100644 --- a/README-ES.md +++ b/README-ES.md @@ -48,7 +48,7 @@ O **instalarlo manualmente**: $ wget https://raw.githubusercontent.com/Josantonius/PHP-Hook/master/src/Hook.php -### Métodos disponibles +## Métodos disponibles Métodos disponibles en esta biblioteca: @@ -139,7 +139,7 @@ Hook::isAction($tag); **# Return** (boolean) -### Cómo empezar +## Cómo empezar Para utilizar esta biblioteca, simplemente: @@ -159,7 +159,7 @@ require_once __DIR__ . '/Hook.php'; use Josantonius\Hook\Hook; ``` -### Uso +## Uso ### - Agregar gancho de acción: @@ -244,7 +244,7 @@ Hook::doAction('meta', 'The title'); Hook::doAction('form', ['input', 'select']); ``` -### Tests +## Tests Para ejecutar las [pruebas](tests) necesitarás [Composer](http://getcomposer.org/download/) y seguir los siguientes pasos: @@ -262,34 +262,45 @@ Ejecutar pruebas de estándares de código [PSR2](http://www.php-fig.org/psr/psr $ composer phpcs +Ejecutar pruebas con [PHP Mess Detector](https://phpmd.org/) para detectar inconsistencias en el estilo de codificación: + + $ composer phpmd + Ejecutar todas las pruebas anteriores: $ composer tests -### ☑ Tareas pendientes +## ☑ Tareas pendientes + +- [ ] Añadir nueva funcionalidad +- [ ] Mejorar pruebas +- [ ] Mejorar documentación +- [ ] Refactorizar código -- [x] Completar tests -- [x] Mejorar la documentación +## Contribuir -### Contribuir +Si deseas colaborar, puedes echar un vistazo a la lista de +[issues](https://github.com/Josantonius/PHP-Hook/issues) o [tareas pendientes](#-tareas-pendientes). -1. Comprobar si hay incidencias abiertas o abrir una nueva para iniciar una discusión en torno a un fallo o función. -1. Bifurca la rama del repositorio en GitHub para iniciar la operación de ajuste. -1. Escribe una o más pruebas para la nueva característica o expón el error. -1. Haz cambios en el código para implementar la característica o reparar el fallo. -1. Envía pull request para fusionar los cambios y que sean publicados. +**Pull requests** -Esto está pensado para proyectos grandes y de larga duración. +* [Fork and clone](https://help.github.com/articles/fork-a-repo). +* Ejecuta el comando `composer install` para instalar dependencias. + Esto también instalará las [dependencias de desarrollo](https://getcomposer.org/doc/03-cli.md#install). +* Ejecuta el comando `composer fix` para estandarizar el código. +* Ejecuta las [pruebas](#tests). +* Crea una nueva rama (**branch**), **commit**, **push** y envíame un + [pull request](https://help.github.com/articles/using-pull-requests). -### Repositorio +## Repositorio -Los archivos de este repositorio se crearon y subieron automáticamente con [Reposgit Creator](https://github.com/Josantonius/BASH-Reposgit). +La estructura de archivos de este repositorio se creó con [PHP-Skeleton](https://github.com/Josantonius/PHP-Skeleton). -### Licencia +## Licencia Este proyecto está licenciado bajo **licencia MIT**. Consulta el archivo [LICENSE](LICENSE) para más información. -### Copyright +## Copyright 2017 Josantonius, [josantonius.com](https://josantonius.com/) diff --git a/README.md b/README.md index f821633..1d31ebb 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ Hook::doAction('form', ['input', 'select']); ## Tests -To run [tests](tests) you just need [Composer](http://getcomposer.org/download/) and to execute the following: +To run [tests](tests) you just need [composer](http://getcomposer.org/download/) and to execute the following: $ git clone https://github.com/Josantonius/PHP-Hook.git @@ -262,27 +262,39 @@ Run [PSR2](http://www.php-fig.org/psr/psr-2/) code standard tests with [PHPCS](h $ composer phpcs +Run [PHP Mess Detector](https://phpmd.org/) tests to detect inconsistencies in code style: + + $ composer phpmd + Run all previous tests: $ composer tests ## ☑ TODO -- [x] Create tests -- [x] Improve documentation +- [ ] Add new feature +- [ ] Improve tests +- [ ] Improve documentation +- [ ] Refactor code ## Contribute -1. Check for open issues or open a new issue to start a discussion around a bug or feature. -1. Fork the repository on GitHub to start making your changes. -1. Write one or more tests for the new feature or that expose the bug. -1. Make code changes to implement the feature or fix the bug. -1. Send a pull request to get your changes merged and published. -This is intended for large and long-lived objects. +If you would like to help, please take a look at the list of +[issues](https://github.com/Josantonius/PHP-Hook/issues) or the [To Do](#-todo) checklist. + +**Pull requests** + +* [Fork and clone](https://help.github.com/articles/fork-a-repo). +* Run the command `composer install` to install the dependencies. + This will also install the [dev dependencies](https://getcomposer.org/doc/03-cli.md#install). +* Run the command `composer fix` to excute code standard fixers. +* Run the [tests](#tests). +* Create a **branch**, **commit**, **push** and send me a + [pull request](https://help.github.com/articles/using-pull-requests). ## Repository -All files in this repository were created and uploaded automatically with [Reposgit Creator](https://github.com/Josantonius/BASH-Reposgit). +The file structure from this repository was created with [PHP-Skeleton](https://github.com/Josantonius/PHP-Skeleton). ## License diff --git a/_config.yml b/_config.yml deleted file mode 100644 index c419263..0000000 --- a/_config.yml +++ /dev/null @@ -1 +0,0 @@ -theme: jekyll-theme-cayman \ No newline at end of file diff --git a/composer.json b/composer.json index 71a034e..4104148 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,5 @@ { "name": "josantonius/hook", - "version": "1.0.8", "type": "library", "description": "Library for handling hooks.", "keywords": [ @@ -20,9 +19,9 @@ } ], "support": { - "issues": "https://github.com/josantonius/php-asset/issues", - "forum": "http://stackoverflow.com/tags/josantonius/php-asset", - "source": "https://github.com/josantonius/php-asset" + "issues": "https://github.com/josantonius/php-hook/issues", + "forum": "http://stackoverflow.com/tags/josantonius/php-hook", + "source": "https://github.com/josantonius/php-hook" }, "config": { "preferred-install": "dist" @@ -32,8 +31,10 @@ "php": "^5.6 || ^7.0" }, "require-dev": { - "phpunit/phpunit": "5.7.*", - "squizlabs/php_codesniffer": "3.*" + "phpunit/phpunit": "^5.7 || ^6.0", + "squizlabs/php_codesniffer": "^3.0", + "friendsofphp/php-cs-fixer": "^2.3 || ^2.8", + "phpmd/phpmd": "^2.6" }, "autoload": { "psr-4": { @@ -52,7 +53,17 @@ }, "scripts": { "phpunit": "vendor/bin/phpunit --colors=always;", - "phpcs": "vendor/bin/phpcs --standard=phpcs.ruleset.xml $(find . -name '*.php');", - "tests": "clear && vendor/bin/phpcs --standard=phpcs.ruleset.xml $(find . -name '*.php') && vendor/bin/phpunit --colors=always;" + "phpcs": "vendor/bin/phpcs --standard=phpcs.xml $(find . -name '*.php');", + "phpmd": "vendor/bin/phpmd src,tests text ./phpmd.xml", + "fix": [ + "vendor/bin/php-cs-fixer fix -v", + "vendor/bin/phpcbf src,tests" + ], + "tests": [ + "clear", + "@phpmd", + "@phpcs", + "@phpunit" + ] } } diff --git a/contributors.txt b/contributors.txt deleted file mode 100644 index 37e53c5..0000000 --- a/contributors.txt +++ /dev/null @@ -1 +0,0 @@ -Josantonius diff --git a/phpcs.ruleset.xml b/phpcs.xml similarity index 53% rename from phpcs.ruleset.xml rename to phpcs.xml index ce35542..32363c5 100644 --- a/phpcs.ruleset.xml +++ b/phpcs.xml @@ -4,10 +4,14 @@ PHP Coding Standards + + + + node_modules vendor - + \ No newline at end of file diff --git a/phpmd.xml b/phpmd.xml new file mode 100644 index 0000000..005d852 --- /dev/null +++ b/phpmd.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/phpunit.xml.dist b/phpunit.xml similarity index 95% rename from phpunit.xml.dist rename to phpunit.xml index 210966a..8a27461 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml @@ -6,7 +6,6 @@ convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" - strict="true" processIsolation="false" stopOnFailure="false" syntaxCheck="false" @@ -23,4 +22,5 @@ src - \ No newline at end of file + + diff --git a/src/Hook.php b/src/Hook.php index 1c554f3..7dde8bd 100644 --- a/src/Hook.php +++ b/src/Hook.php @@ -8,7 +8,6 @@ * @link https://github.com/Josantonius/PHP-Hook * @since 1.0.0 */ - namespace Josantonius\Hook; /** @@ -87,6 +86,7 @@ public static function getInstance($id = '0') if (isset(self::$instances[self::$id])) { return self::$instances[self::$id]; } + return self::$instances[self::$id] = new self; } @@ -100,16 +100,17 @@ public static function getInstance($id = '0') * @param int $priority → order in which the action is executed * @param int $args → number of arguments accepted * - * @return boolean + * @return bool */ public static function addAction($tag, $func, $priority = 8, $args = 0) { $that = self::getInstance(self::$id); $that->callbacks[$tag][$priority][] = [ - 'function' => $func, + 'function' => $func, 'arguments' => $args, ]; + return true; } @@ -120,13 +121,14 @@ public static function addAction($tag, $func, $priority = 8, $args = 0) * * @param array $actions * - * @return boolean + * @return bool */ public static function addActions($actions) { foreach ($actions as $arguments) { call_user_func_array([__CLASS__, 'addAction'], $arguments); } + return true; } @@ -141,9 +143,9 @@ public static function addActions($actions) * * @since 1.0.3 * - * @param string $tag → action hook name - * @param mixed $args → optional arguments - * @param boolean $remove → delete hook after executing actions + * @param string $tag → action hook name + * @param mixed $args → optional arguments + * @param bool $remove → delete hook after executing actions * * @return returns the output of the last action or false */ @@ -155,7 +157,7 @@ public static function doAction($tag, $args = [], $remove = true) $that->actions['count']++; - if (!array_key_exists($tag, $that->actions)) { + if (! array_key_exists($tag, $that->actions)) { $that->actions[$tag] = 0; } @@ -180,8 +182,6 @@ public static function doAction($tag, $args = [], $remove = true) * @since 1.0.0 * * @param string $method → singleton method name - * - * @return void */ public static function setSingletonName($method) { @@ -209,13 +209,13 @@ public static function current() * * @param string $tag → action hook name * - * @return boolean + * @return bool */ public static function isAction($tag) { $that = self::getInstance(self::$id); - return (isset($that->callbacks[$tag])); + return isset($that->callbacks[$tag]); } /** @@ -223,22 +223,22 @@ public static function isAction($tag) * * @since 1.0.3 * - * @param string $action → action hook - * @param int $args → arguments + * @param string $action → action hook + * @param int $args → arguments * * @return callable|false → returns the calling function */ private function runAction($action, $args) { - $function = $action['function']; + $function = $action['function']; $argsNumber = $action['arguments']; - $class = (isset($function[0])) ? $function[0] : false; + $class = (isset($function[0])) ? $function[0] : false; $method = (isset($function[1])) ? $function[1] : false; $args = $this->getArguments($argsNumber, $args); - if (!($class && $method) && function_exists($function)) { + if (! ($class && $method) && function_exists($function)) { return call_user_func($function, $args); } elseif ($obj = call_user_func([$class, $this->singleton])) { if ($obj !== false) { @@ -246,6 +246,7 @@ private function runAction($action, $args) } } elseif (class_exists($class)) { $instance = new $class; + return call_user_func_array([$instance, $method], $args); } } @@ -255,8 +256,8 @@ private function runAction($action, $args) * * @since 1.0.3 * - * @param string $tag → action hook name - * @param boolean $remove → delete hook after executing actions + * @param string $tag → action hook name + * @param bool $remove → delete hook after executing actions * * @return object|false → returns the calling function */ @@ -268,6 +269,7 @@ private function getActions($tag, $remove) unset($this->callbacks[$tag]); } } + return (isset($actions)) ? $actions : []; } @@ -294,8 +296,10 @@ private function getArguments($argsNumber, $arguments) $args[] = $arguments[$i]; continue; } + return $args; } + return []; } } diff --git a/tests/Example.php b/tests/Example.php index 3bf0154..5851841 100644 --- a/tests/Example.php +++ b/tests/Example.php @@ -8,7 +8,6 @@ * @link https://github.com/Josantonius/PHP-Hook * @since 1.0.8 */ - namespace Josantonius\Hook; /** @@ -22,15 +21,11 @@ class Example * Class instance. * * @since 1.0.8 - * - * @return void */ private static $singleton; /** * @since 1.0.8 - * - * @return void */ public static function getInstance() { @@ -39,8 +34,6 @@ public static function getInstance() /** * @since 1.0.8 - * - * @return void */ public static function singletonMethod() { @@ -49,8 +42,6 @@ public static function singletonMethod() /** * @since 1.0.8 - * - * @return void */ public function meta($title) { @@ -59,8 +50,6 @@ public function meta($title) /** * @since 1.0.8 - * - * @return void */ public function css() { @@ -69,8 +58,6 @@ public function css() /** * @since 1.0.8 - * - * @return void */ public function js() { @@ -79,8 +66,6 @@ public function js() /** * @since 1.0.8 - * - * @return void */ public function afterBody() { @@ -89,8 +74,6 @@ public function afterBody() /** * @since 1.0.8 - * - * @return void */ public function slide() { @@ -99,8 +82,6 @@ public function slide() /** * @since 1.0.8 - * - * @return void */ public function form($input, $select) { @@ -109,8 +90,6 @@ public function form($input, $select) /** * @since 1.0.8 - * - * @return void */ public function article() { @@ -119,8 +98,6 @@ public function article() /** * @since 1.0.8 - * - * @return void */ public function footer() { diff --git a/tests/HookTest.php b/tests/HookTest.php index bc41c8b..fbff80e 100644 --- a/tests/HookTest.php +++ b/tests/HookTest.php @@ -8,7 +8,6 @@ * @link https://github.com/Josantonius/PHP-Hook * @since 1.0.6 */ - namespace Josantonius\Hook; use PHPUnit\Framework\TestCase; @@ -20,17 +19,47 @@ */ final class HookTest extends TestCase { + /** + * Hook instance. + * + * @since 1.1.5 + * + * @var object + */ + protected $Hook; + + /** + * Set up. + * + * @since 1.1.5 + */ + public function setUp() + { + parent::setUp(); + + $this->Hook = new Hook; + } + + /** + * Check if it is an instance of Hook. + * + * @since 1.1.5 + */ + public function testIsInstanceOfHook() + { + $actual = $this->Hook; + $this->assertInstanceOf('Josantonius\Hook\Hook', $actual); + } + /** * Add action hook. * * @since 1.0.6 - * - * @return void */ public function testAddAction() { $this->assertTrue( - Hook::addAction('css', ['Josantonius\Hook\Example', 'css']) + $this->Hook->addAction('css', ['Josantonius\Hook\Example', 'css']) ); } @@ -38,13 +67,11 @@ public function testAddAction() * Add action hook with priority. * * @since 1.0.6 - * - * @return void */ public function testAddActionWithPriority() { $this->assertTrue( - Hook::addAction('js', ['Josantonius\Hook\Example', 'js'], 1) + $this->Hook->addAction('js', ['Josantonius\Hook\Example', 'js'], 1) ); } @@ -52,15 +79,13 @@ public function testAddActionWithPriority() * Add action hook with priority and arguments number. * * @since 1.0.6 - * - * @return void */ public function testAddActionWithPriorityAndArguments() { $instance = new Example; $this->assertTrue( - Hook::addAction('meta', [$instance, 'meta'], 2, 1) + $this->Hook->addAction('meta', [$instance, 'meta'], 2, 1) ); } @@ -68,19 +93,17 @@ public function testAddActionWithPriorityAndArguments() * Add action hook and set singleton method. * * @since 1.0.6 - * - * @return void */ public function testAddActionWithCustomSingletonMethod() { - Hook::setSingletonName('singletonMethod'); + $this->Hook->setSingletonName('singletonMethod'); $instance = call_user_func( 'Josantonius\Hook\Example::singletonMethod' ); $this->assertTrue( - Hook::addAction('article', [$instance, 'article'], 3, 0) + $this->Hook->addAction('article', [$instance, 'article'], 3, 0) ); } @@ -88,15 +111,13 @@ public function testAddActionWithCustomSingletonMethod() * Add multiple action hooks. * * @since 1.0.6 - * - * @return void */ public function testAddMultipleActions() { $instance = new Example; $this->assertTrue( - Hook::addActions([ + $this->Hook->addActions([ ['after-body', [$instance, 'afterBody'], 4, 0], ['footer', [$instance, 'footer'], 5, 0], ]) @@ -107,20 +128,17 @@ public function testAddMultipleActions() * Add multiple action hooks and set singleton method. * * @since 1.0.6 - * - * @return void */ public function testAddMultipleActionsWithCustomSingletonMethod() { - - Hook::setSingletonName('singletonMethod'); + $this->Hook->setSingletonName('singletonMethod'); $instance = call_user_func( 'Josantonius\Hook\Example::singletonMethod' ); $this->assertTrue( - Hook::addActions([ + $this->Hook->addActions([ ['slide', [$instance, 'slide'], 6, 0], ['form', [$instance, 'form'], 7, 2], ]) @@ -131,17 +149,15 @@ public function testAddMultipleActionsWithCustomSingletonMethod() * Check if is action. * * @since 1.0.7 - * - * @return void */ public function testIsAction() { $this->assertTrue( - Hook::isAction('meta') + $this->Hook->isAction('meta') ); $this->assertTrue( - Hook::isAction('form') + $this->Hook->isAction('form') ); } @@ -149,13 +165,11 @@ public function testIsAction() * Check if isn`t action. * * @since 1.0.7 - * - * @return void */ public function testIsNotAction() { $this->assertFalse( - Hook::isAction('unknown') + $this->Hook->isAction('unknown') ); } @@ -163,47 +177,41 @@ public function testIsNotAction() * Execute action hooks. * * @since 1.0.6 - * - * @return void */ public function testDoActions() { - $this->assertContains('css-hook', Hook::doAction('css')); - $this->assertContains('js-hook', Hook::doAction('js')); - $this->assertContains('after-hook', Hook::doAction('after-body')); - $this->assertContains('article-hook', Hook::doAction('article')); - $this->assertContains('footer-hook', Hook::doAction('footer')); + $this->assertContains('css-hook', $this->Hook->doAction('css')); + $this->assertContains('js-hook', $this->Hook->doAction('js')); + $this->assertContains('after-hook', $this->Hook->doAction('after-body')); + $this->assertContains('article-hook', $this->Hook->doAction('article')); + $this->assertContains('footer-hook', $this->Hook->doAction('footer')); } /** * Execute action hooks and get current hook. * * @since 1.0.6 - * - * @return void */ public function testDoActionAndGetCurrentHook() { - $this->assertContains('slide', Hook::doAction('slide')); + $this->assertContains('slide', $this->Hook->doAction('slide')); } /** * Execute action hook with arguments. * * @since 1.0.6 - * - * @return void */ public function testDoActionsWithArguments() { $this->assertContains( 'meta-hook', - Hook::doAction('meta', 'The title') + $this->Hook->doAction('meta', 'The title') ); $this->assertContains( 'form-hook', - Hook::doAction('form', ['input', 'select']) + $this->Hook->doAction('form', ['input', 'select']) ); } }