{"id":231158,"date":"2022-12-16T14:51:00","date_gmt":"2022-12-16T11:51:00","guid":{"rendered":"https:\/\/wordpress.mediadoma.com\/?p=231158"},"modified":"2022-12-16T14:51:41","modified_gmt":"2022-12-16T11:51:41","slug":"widgets-wordpress-refactorisation-partie-2","status":"publish","type":"post","link":"https:\/\/wordpress.mediadoma.com\/fr\/widgets-wordpress-refactorisation-partie-2\/","title":{"rendered":"Widgets WordPress : refactorisation, partie 2"},"content":{"rendered":"\n<p><strong><a href=\"https:\/\/wordpress.mediadoma.com\/fr\/widgets-wordpress-refactorisation-partie-1\/\" title=\"Apr\u00e8s tout le contenu pr\u00e9liminaire\">Apr\u00e8s tout le contenu pr\u00e9liminaire<\/a><\/strong>, nous sommes enfin \u00e0 un endroit o\u00f9 nous sommes pr\u00eats \u00e0 commencer \u00e0 r\u00e9soudre les probl\u00e8mes standard de codage pos\u00e9s par notre IDE et par nos outils de qualit\u00e9 de code.<\/p>\n<p>Ce faisant, je vais d\u00e9composer le contenu en deux articles\u00a0:<\/p>\n<ul>\n<li>le premier article va se concentrer uniquement sur la refactorisation du code existant,<\/li>\n<li>dans le prochain article, nous allons examiner la refactorisation de la structure du plugin pour am\u00e9liorer l&rsquo;organisation et l&rsquo;architecture.<\/li>\n<\/ul>\n<p>Pour l&rsquo;instant, examinons les erreurs g\u00e9n\u00e9r\u00e9es par le renifleur de code et voyons si nous ne pouvons pas l&rsquo;adapter \u00e0 des normes plus modernes.<\/p>\n<h2>Le passe-partout du widget WordPress: refactorisation, partie 2<\/h2>\n<p>Notez que je suis toujours sur la branche <strong>develop car nous ne sommes pas encore pr\u00eats \u00e0 fusionner cela dans master.<\/strong> Et si vos renifleurs de code et autres outils sont correctement configur\u00e9s, vous devriez voir <strong><a href=\"https:\/\/gist.github.com\/tommcfarlin\/dce6bda0d104192a21cb06dc7d3ca23c#file-00-regex-results-txt\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">ce qui suit\u00a0:<\/a><\/strong><\/p>\n<pre><code>Warning: Uncaught ErrorException: require_once(\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/vendor\/autoload.php): failed to open stream: No such file or directory in \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/php-cs-fixer:62\nStack trace:\n#0 \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/php-cs-fixer(62): {closure}(2, 'require_once(\/U...', '\/Users\/tommcfar...', 62, Array)\n#1 \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/php-cs-fixer(62): require_once()\n#2 {main}\n  thrown in \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/php-cs-fixer on line 62\n\nCall Stack:\n    0.0041     365448   1. {main}() \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/php-cs-fixer:0\n\nFatal error: main(): Failed opening required '\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/vendor\/autoload.php' (include_path='.:\/usr\/local\/Cellar\/php@7.1\/7.1.19\/share\/php@7.1\/pear') in \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/php-cs-fixer on line 62\n\nCall Stack:\n    0.0041     365448   1. {main}() \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/php-cs-fixer:0\n\nYou can fix all errors by running following commands:\n'\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/php-cs-fixer' '--allow-risky=yes' '--config=.php_cs.dist' '--using-cache=yes' '--verbose' 'fix'\nERROR: Ruleset \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/phpcs.xml is not valid\n\nRun \"phpcs --help\" for usage information\n\nWarning: require(\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint.php): failed to open stream: No such file or directory in \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint on line 4\n\nCall Stack:\n    0.0035     352864   1. {main}() \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint:0\n\nFatal error: require(): Failed opening required '\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint.php' (include_path='.:\/usr\/local\/Cellar\/php@7.1\/7.1.19\/share\/php@7.1\/pear') in \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint on line 4\n\nCall Stack:\n    0.0035     352864   1. {main}() \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint:0\n\nPHP Warning:  require(\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint.php): failed to open stream: No such file or directory in \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint on line 4\nPHP Stack trace:\nPHP   1. {main}() \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint:0\nPHP Fatal error:  require(): Failed opening required '\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint.php' (include_path='.:\/usr\/local\/Cellar\/php@7.1\/7.1.19\/share\/php@7.1\/pear') in \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint on line 4\nPHP Stack trace:\nPHP   1. {main}() \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/parallel-lint:0\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:33     The class Widget_Name has 12 public methods. Consider refactoring Widget_Name to keep number of public methods under 10.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:33     The class Widget_Name is not named in CamelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:33     The property$widget_slug is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:97     The method get_widget_slug is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:111    The variable$widget_string is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:111    The variable$before_widget is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:111    The variable$widget_string is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:111    The variable$widget_string is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:111    The variable$after_widget is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:111    The variable$widget_string is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:111    The variable$widget_string is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:111    Avoid unusedparameters such as '$instance'.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:131    Avoid unusedlocal variables such as '$before_widget'.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:137    Avoid unusedlocal variables such as '$after_widget'.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:149    The method flush_widget_cache is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:159    The parameter $new_instance is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:159    The parameter $old_instance is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:159    The variable$old_instance is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:159    Avoid unusedparameters such as '$new_instance'.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:195    The method widget_textdomain is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:207    The parameter $network_wide is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:207    Avoid unusedparameters such as '$network_wide'.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:216    The parameter $network_wide is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:216    Avoid unusedparameters such as '$network_wide'.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:223    The method register_admin_styles is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:232    The method register_admin_scripts is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:241    The method register_widget_styles is not named in camelCase.\n\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/src\/Plugin.php:250    The method register_widget_scripts is not named in camelCase.\n[FATAL] \/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/phpcs.xml: Premature end of data in tag ruleset line 2\n (77) on line 28,12<\/code><\/pre>\n<p>Et vous devriez voir au moins tout cela apr\u00e8s avoir ex\u00e9cut\u00e9 :<\/p>\n<pre><code>$ vendor\/bin\/grumphp run<\/code><\/pre>\n<p>Avant d&rsquo;aller de l&rsquo;avant, nous devons apporter quelques modifications mineures \u00e0 l&rsquo;organisation des fichiers. C&rsquo;est-\u00e0-dire que nous devons s\u00e9parer le fichier principal du plugin (que nous avons sous le nom de <strong>Plugin.php<\/strong>) en deux fichiers.<\/p>\n<p>Plus pr\u00e9cis\u00e9ment, nous avons besoin d&rsquo;un fichier d&rsquo;amor\u00e7age de plug-in, puis nous devons maintenir le fichier de plug-in principal. Donc, d&rsquo;abord, cr\u00e9ons un plugin bootstrap.<\/p>\n<h3>Cr\u00e9er le bootstrap<\/h3>\n<p>A la racine du plugin, cr\u00e9ez un fichier nomm\u00e9 <strong>wordpress-widget-boilerplate.php.<\/strong> Ajoutez-y ensuite <strong><a href=\"https:\/\/gist.github.com\/tommcfarlin\/dce6bda0d104192a21cb06dc7d3ca23c#file-01-wordpress-widget-boilerplate-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">ce qui suit<\/a><\/strong> :<\/p>\n<pre><code>&lt;?php\n\/**\n * WordPress Widget Boilerplate\n *\n * The WordPress Widget Boilerplate is an organized, maintainable boilerplate for building widgets using WordPress best practices.\n *\n * @package   Widget_Name\n * @author    Your Name &lt;email@example.com&gt;\n * @license   GPL-2.0+\n * @link      http:\/\/example.com\n * @copyright 2018 Your Name or Company Name\n *\n * @wordpress-plugin\n * Plugin Name:       @TODO\n * Plugin URI:        @TODO\n * Description:       @TODO\n * Version:           1.0.0\n * Author:            @TODO\n * Author URI:        @TODO\n * Text Domain:       widget-name\n * License:           GPL-3.0+\n * License URI:       http:\/\/www.gnu.org\/licenses\/gpl-3.0.txt\n * Domain Path:       \/lang\n * GitHub Plugin URI: https:\/\/github.com\/&lt;owner&gt;\/&lt;repo&gt;\n *\/\n\n\/\/ Prevent this file from being called directly.\ndefined('WPINC') || die;\n\n\/\/ Include the autoloader.\nrequire_once __DIR__. '\/inc\/autoload.php';\n<\/code><\/pre>\n<p>Notez dans le fichier ci-dessus; nous avons l&rsquo;en-t\u00eate du plug-in, la condition pour d\u00e9terminer si le fichier est accessible, puis le chargement du chargeur automatique Composer.<\/p>\n<h3>Modifier le plugin principal<\/h3>\n<p>Une fois cela fait, cela changera le fichier principal <strong>Plugin.php<\/strong> pour qu&rsquo;il ressemble <strong><a href=\"https:\/\/gist.github.com\/tommcfarlin\/dce6bda0d104192a21cb06dc7d3ca23c#file-02-plugin-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">\u00e0 ceci\u00a0:<\/a><\/strong><\/p>\n<pre><code>&lt;?php\n\n\/\/ TODO: change 'Widget_Name' to the name of your plugin\nclass Widget_Name extends WP_Widget {\n\n    \/**\n     * @TODO - Rename \"widget-name\" to the name your your widget\n     *\n     * Unique identifier for your widget.\n     *\n     *\n     * The variable name is used as the text domain when internationalizing strings\n     * of text. Its value should match the Text Domain file header in the main\n     * widget file.\n     *\n     * @since    1.0.0\n     *\n     * @var      string\n     *\/\n    protected $widget_slug = 'widget-name';\n\n    \/*--------------------------------------------------*\/\n    \/* Constructor\n    \/*--------------------------------------------------*\/\n\n    \/**\n     * Specifies the classname and description, instantiates the widget,\n     * loads localization files, and includes necessary stylesheets and JavaScript.\n     *\/\n    public function __construct() {\n\n        \/\/ load plugin text domain\n        add_action( 'init', array( $this, 'widget_textdomain') );\n\n        \/\/ TODO: update description\n        parent::__construct(\n            $this-&gt;get_widget_slug(),\n            __( 'Widget Name', $this-&gt;get_widget_slug() ),\n            array(\n                'classname'  =&gt; $this-&gt;get_widget_slug().'-class',\n                'description' =&gt; __( 'Short description of the widget goes here.', $this-&gt;get_widget_slug())) );\n\n        \/\/ Register admin styles and scripts\n        add_action( 'admin_print_styles', array( $this, 'register_admin_styles') );\n        add_action( 'admin_enqueue_scripts', array( $this, 'register_admin_scripts') );\n\n        \/\/ Register site styles and scripts\n        add_action( 'wp_enqueue_scripts', array( $this, 'register_widget_styles') );\n        add_action( 'wp_enqueue_scripts', array( $this, 'register_widget_scripts') );\n\n        \/\/ Refreshing the widget's cached output with each new post\n        add_action( 'save_post',    array( $this, 'flush_widget_cache') );\n        add_action( 'deleted_post', array( $this, 'flush_widget_cache') );\n        add_action( 'switch_theme', array( $this, 'flush_widget_cache') );\n\n    } \/\/ end constructor\n\n    \/**\n     * Return the widget slug.\n     *\n     * @since    1.0.0\n     *\n     * @return    Plugin slug variable.\n     *\/\n    public function get_widget_slug() {\n        return $this-&gt;widget_slug;\n    }\n\n    \/*--------------------------------------------------*\/\n    \/* Widget API Functions\n    \/*--------------------------------------------------*\/\n\n    \/**\n     * Outputs the content of the widget.\n     *\n     * @param array args  The array of form elements\n     * @param array instance The current instance of the widget\n     *\/\n    public function widget( $args, $instance) {\n\n        \/\/ Check if there is a cached output\n        $cache = wp_cache_get( $this-&gt;get_widget_slug(), 'widget' );\n\n        if (!is_array( $cache)) $cache = array();\n\n        if (! isset ($args['widget_id'])) $args['widget_id'] = $this-&gt;id;\n\n        if (isset ($cache[ $args['widget_id'] ])) return print $cache[ $args['widget_id'] ];\n\n        \/\/ go on with your widget logic, put everything into a string and \u2026\n\n        extract( $args, EXTR_SKIP );\n\n        $widget_string = $before_widget;\n\n        \/\/ TODO: Here is where you manipulate your widget's values based on their input fields\n        ob_start();\n        include( plugin_dir_path( __FILE__ ). 'views\/widget.php' );\n        $widget_string .= ob_get_clean();\n        $widget_string .= $after_widget;\n\n        $cache[ $args['widget_id'] ] = $widget_string;\n\n        wp_cache_set( $this-&gt;get_widget_slug(), $cache, 'widget' );\n\n        print $widget_string;\n\n    } \/\/ end widget\n\n    public function flush_widget_cache()\n    {\n        wp_cache_delete( $this-&gt;get_widget_slug(), 'widget' );\n    }\n    \/**\n     * Processes the widget's options to be saved.\n     *\n     * @param array new_instance The new instance of values to be generated via the update.\n     * @param array old_instance The previous instance of values before the update.\n     *\/\n    public function update( $new_instance, $old_instance) {\n\n        $instance = $old_instance;\n\n        \/\/ TODO: Here is where you update your widget's old values with the new, incoming values\n\n        return $instance;\n\n    } \/\/ end update\n\n    \/**\n     * Generates the administration form for the widget.\n     *\n     * @param array instance The array of keys and values for the widget.\n     *\/\n    public function form( $instance) {\n\n        \/\/ TODO: Define default values for your variables\n        $instance = wp_parse_args(\n            (array) $instance\n        );\n\n        \/\/ TODO: Store the values of the widget in their own variable\n\n        \/\/ Display the admin form\n        include( plugin_dir_path(__FILE__). 'views\/admin.php' );\n\n    } \/\/ end form\n\n    \/*--------------------------------------------------*\/\n    \/* Public Functions\n    \/*--------------------------------------------------*\/\n\n    \/**\n     * Loads the Widget's text domain for localization and translation.\n     *\/\n    public function widget_textdomain() {\n\n        \/\/ TODO be sure to change 'widget-name' to the name of *your* plugin\n        load_plugin_textdomain( $this-&gt;get_widget_slug(), false, dirname( plugin_basename( __FILE__) ). 'lang\/' );\n\n    } \/\/ end widget_textdomain\n\n    \/**\n     * Fired when the plugin is activated.\n     *\n     * @param  boolean $network_wide True if WPMU superadmin uses \"Network Activate\" action, false if WPMU is disabled or plugin is activated on an individual blog.\n     *\/\n    public static function activate( $network_wide) {\n        \/\/ TODO define activation functionality here\n    } \/\/ end activate\n\n    \/**\n     * Fired when the plugin is deactivated.\n     *\n     * @param boolean $network_wide True if WPMU superadmin uses \"Network Activate\" action, false if WPMU is disabled or plugin is activated on an individual blog\n     *\/\n    public static function deactivate( $network_wide) {\n        \/\/ TODO define deactivation functionality here\n    } \/\/ end deactivate\n\n    \/**\n     * Registers and enqueues admin-specific styles.\n     *\/\n    public function register_admin_styles() {\n\n        wp_enqueue_style( $this-&gt;get_widget_slug().'-admin-styles', plugins_url( 'css\/admin.css', __FILE__) );\n\n    } \/\/ end register_admin_styles\n\n    \/**\n     * Registers and enqueues admin-specific JavaScript.\n     *\/\n    public function register_admin_scripts() {\n\n        wp_enqueue_script( $this-&gt;get_widget_slug().'-admin-script', plugins_url( 'js\/admin.js', __FILE__ ), array('jquery') );\n\n    } \/\/ end register_admin_scripts\n\n    \/**\n     * Registers and enqueues widget-specific styles.\n     *\/\n    public function register_widget_styles() {\n\n        wp_enqueue_style( $this-&gt;get_widget_slug().'-widget-styles', plugins_url( 'css\/widget.css', __FILE__) );\n\n    } \/\/ end register_widget_styles\n\n    \/**\n     * Registers and enqueues widget-specific scripts.\n     *\/\n    public function register_widget_scripts() {\n\n        wp_enqueue_script( $this-&gt;get_widget_slug().'-script', plugins_url( 'js\/widget.js', __FILE__ ), array('jquery') );\n\n    } \/\/ end register_widget_scripts\n\n} \/\/ end class\n\n\/\/ TODO: Remember to change 'Widget_Name' to match the class name definition\nadd_action( 'widgets_init', create_function( '', 'register_widget(\"Widget_Name\");') );\n\n\/\/ Hooks fired when the Widget is activated and deactivated\n\/\/ TODO: Remember to change 'Widget_Name' to match the class name definition\nregister_activation_hook( __FILE__, array( 'Widget_Name', 'activate') );\nregister_deactivation_hook( __FILE__, array( 'Widget_Name', 'deactivate') );\n<\/code><\/pre>\n<p>N&rsquo;oubliez pas qu&rsquo;il reste encore beaucoup de travail \u00e0 faire, mais la premi\u00e8re chose \u00e0 faire est de commencer \u00e0 nettoyer la base de code de son \u00e9tat actuel. Finalement, nous allons refactoriser cela d&rsquo;une mani\u00e8re beaucoup plus orient\u00e9e objet, mais nous devons obtenir la version actuelle du plugin dans un \u00e9tat sain.<\/p>\n<p>Maintenant, cependant, nous pouvons retourner notre attention sur la sortie originale de GrumPHP. Si vous regardez \u00e0 travers, la sortie, vous verrez une ligne comme celle-ci\u00a0:<\/p>\n<pre><code>You can fix all errors by running following commands:\n'\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/php-cs-fixer' '--allow-risky=yes' '--config=.php_cs.dist' '--using-cache=yes' '--verbose' 'fix'<\/code><\/pre>\n<p>Donc, \u00e0 ce stade, examinons l&rsquo;ex\u00e9cution de la commande recommand\u00e9e et voyons ce qui se passe. Plus pr\u00e9cis\u00e9ment, entrez ceci dans votre terminal\u00a0:<\/p>\n<pre><code>'\/Users\/tommcfarlin\/Dropbox\/Projects\/trunk\/wp-content\/plugins\/WordPress-Widget-Boilerplate\/vendor\/bin\/php-cs-fixer' '--allow-risky=yes' '--config=.php_cs.dist' '--using-cache=yes' '--verbose' 'fix'<\/code><\/pre>\n<p>En supposant que tout fonctionne correctement, vous devriez voir quelque chose comme ceci :<\/p>\n<h4>Remarque sur les erreurs de sortie<\/h4>\n<p>Si vous recevez une erreur chaque fois que vous faites cela, vous devrez peut-\u00eatre mettre \u00e0 jour le r\u00e9pertoire des <strong>fournisseurs<\/strong> ou m\u00eame mettre \u00e0 jour le r\u00e9pertoire. Si tel est le cas, essayez d&rsquo;abord ceci\u00a0:<\/p>\n<pre><code>$ composer update<\/code><\/pre>\n<p>Et si cela ne r\u00e9sout pas votre probl\u00e8me, essayez :<\/p>\n<pre><code>$ rm -rf vendor\n$ composer update<\/code><\/pre>\n<p>Apr\u00e8s cela, relancez la commande.<\/p>\n<h3>Retour \u00e0 la sortie<\/h3>\n<p>Vous devriez alors voir une sortie comme celle-ci\u00a0:<\/p>\n<p><a href=\"https:\/\/wordpress.mediadoma.com\/wp-content\/uploads\/2022\/01\/post-161324-61e71fbbbfefa.png\" data-rel=\"lightbox\"><img decoding=\"async\" class=\"SDStudio-light-box-enable SDStudio-editor-tools-md-imp\" src=\"https:\/\/wordpress.mediadoma.com\/wp-content\/uploads\/2022\/01\/post-161324-61e71fbbbfefa.png\" alt=\"Widgets WordPress : refactorisation, partie 2\"><\/a><\/p>\n<p>Ensuite, ex\u00e9cutez la commande suivante sur votre terminal\u00a0:<\/p>\n<pre><code>$ vendor\/grumphp\/run<\/code><\/pre>\n<p>Ici, vous devriez maintenant voir des probl\u00e8mes avec les normes de codage. La liste est trop longue pour \u00eatre list\u00e9e ici mais vous devriez voir une option pour faire quelque chose <strong><a href=\"https:\/\/gist.github.com\/tommcfarlin\/dce6bda0d104192a21cb06dc7d3ca23c#file-03-coding-standards-txt\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">comme ceci :<\/a><\/strong><\/p>\n<pre><code>----------------------------------------------------------------------\nFOUND 9 ERRORS AFFECTING 8 LINES\n----------------------------------------------------------------------<\/code><\/pre>\n<p>Et \u00e0 ce stade, il y a beaucoup de changements que nous devons apporter si nous voulons le mettre aux normes PSR2. Alors faisons-le maintenant.<\/p>\n<h3>Refactoriser le Widget Boilerplate<\/h3>\n<p>En supposant que toutes les extensions et plug-ins n\u00e9cessaires soient install\u00e9s dans Visual Studio Code, vous verrez probablement une bonne quantit\u00e9 de rouge dans votre IDE.<\/p>\n<p><a href=\"https:\/\/wordpress.mediadoma.com\/wp-content\/uploads\/2022\/01\/post-161324-61e71fbfb62de.png\" data-rel=\"lightbox\"><img decoding=\"async\" class=\"SDStudio-light-box-enable SDStudio-editor-tools-md-imp\" src=\"https:\/\/wordpress.mediadoma.com\/wp-content\/uploads\/2022\/01\/post-161324-61e71fbfb62de.png\" alt=\"Widgets WordPress : refactorisation, partie 2\"><\/a><\/p>\n<p>Ce sont tous des probl\u00e8mes qui doivent \u00eatre r\u00e9solus. Je vais donc parcourir et mettre \u00e0 jour le code. Ensuite, je partagerai le code ici (sans commentaires pour \u00e9conomiser de l&rsquo;espace).<\/p>\n<p>En supposant que vous avez effectu\u00e9 toutes les modifications appropri\u00e9es, vous devriez avoir quelque chose <strong><a href=\"https:\/\/gist.github.com\/tommcfarlin\/dce6bda0d104192a21cb06dc7d3ca23c#file-04-wordpress-widget-boilerplate-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">comme ceci\u00a0:<\/a><\/strong><\/p>\n<pre><code>&lt;?php\n\nnamespace WordPressWidgetBoilerplate;\n\nclass Plugin extends WP_Widget\n{\n    protected $widgetSlug = 'widget-name';\n\n    public function __construct()\n    {\n        add_action('init', [$this, 'widgetTextdomain']);\n\n        parent::__construct(\n            $this-&gt;getWidgetSlug(),\n            __('Widget Name', $this-&gt;getWidgetSlug()),\n            [\n                'classname' =&gt; $this-&gt;getWidgetSlug().'-class',\n                'description' =&gt; __('Short description of the widget goes here.', $this-&gt;getWidgetSlug()),\n            ]\n        );\n\n        add_action('admin_print_styles', [$this, 'registerAdminStyles']);\n        add_action('admin_enqueue_scripts', [$this, 'registerAdminScripts']);\n\n        add_action('wp_enqueue_scripts', [$this, 'registerWidgetStyles']);\n        add_action('wp_enqueue_scripts', [$this, 'registerWidgetScripts']);\n\n        add_action('save_post', [$this, 'flushWidgetCache']);\n        add_action('deleted_post', [$this, 'flushWidgetCache']);\n        add_action('switch_theme', [$this, 'flushWidgetCache']);\n    }\n\n    public function getWidgetSlug()\n    {\n        return $this-&gt;widgetSlug;\n    }\n\n    public function widget($args, $instance)\n    {\n        \/\/ Check if there is a cached output\n        $cache = wp_cache_get($this-&gt;getWidgetSlug(), 'widget');\n\n        if (!is_array($cache)) {\n            $cache = [];\n        }\n\n        if (!isset($args['widget_id'])) {\n            $args['widget_id'] = $this-&gt;id;\n        }\n\n        if (isset($cache[$args['widget_id']])) {\n            return print $cache[$args['widget_id']];\n        }\n\n        extract($args, EXTR_SKIP);\n\n        $widgetString = $beforeWidget;\n\n        ob_start();\n        include plugin_dir_path(__FILE__).'views\/widget.php';\n        $widgetString .= ob_get_clean();\n        $widgetString .= $afterWidget;\n\n        $cache[$args['widget_id']] = $widgetString;\n\n        wp_cache_set($this-&gt;getWidgetSlug(), $cache, 'widget');\n\n        echo $widgetString;\n    }\n\n    public function flushWidgetCache()\n    {\n        wp_cache_delete($this-&gt;getWidgetSlug(), 'widget');\n    }\n\n    public function update($newInstance, $oldInstance)\n    {\n        $instance = $oldInstance;\n\n        \/\/ TODO: Here is where you update your widget's old values with the new, incoming values\n\n        return $instance;\n    }\n\n    public function form($instance)\n    {\n        \/\/ TODO: Define default values for your variables\n        $instance = wp_parse_args(\n            (array) $instance\n        );\n\n        \/\/ TODO: Store the values of the widget in their own variable\n\n        \/\/ Display the admin form\n        include plugin_dir_path(__FILE__).'views\/admin.php';\n    }\n\n    public function widgetTextdomain()\n    {\n        \/\/ TODO: be sure to change 'widget-name' to the name of *your* plugin\n        load_plugin_textdomain($this-&gt;getWidgetSlug(), false, dirname(plugin_basename(__FILE__)).'lang\/');\n    }\n\n    public static function activate($networkWide)\n    {\n        \/\/ TODO: define activation functionality here\n    }\n\n    public static function deactivate($networkWide)\n    {\n        \/\/ TODO:define deactivation functionality here\n    }\n\n    public function registerAdminStyles()\n    {\n        wp_enqueue_style($this-&gt;getWidgetSlug().'-admin-styles', plugins_url('css\/admin.css', __FILE__));\n    }\n\n    public function registerAdminScripts()\n    {\n        wp_enqueue_script($this-&gt;getWidgetSlug().'-admin-script', plugins_url('js\/admin.js', __FILE__), ['jquery']);\n    }\n\n    public function registerWidgetStyles()\n    {\n        wp_enqueue_style($this-&gt;getWidgetSlug().'-widget-styles', plugins_url('css\/widget.css', __FILE__));\n    }\n\n    public function registerWidgetScripts()\n    {\n        wp_enqueue_script($this-&gt;getWidgetSlug().'-script', plugins_url('js\/widget.js', __FILE__), ['jquery']);\n    }\n}\n<\/code><\/pre>\n<p>Encore une fois, lancez :<\/p>\n<pre><code>$ vendor\/bin\/grumphp run<\/code><\/pre>\n<p>Et voyez quelle sortie vous obtenez. Vous obtiendrez toujours une vari\u00e9t\u00e9 d&rsquo;erreurs, \u00e0 savoir qui disent quelque chose sur le ton de\u00a0:<\/p>\n<blockquote>\n<p>\u00c9vitez les variables locales inutilis\u00e9es telles que \u2026<\/p>\n<\/blockquote>\n<p>C&rsquo;est parce que les r\u00e8gles de reniflage de code ne veulent pas que nous utilisions des variables qui ne sont pas utilis\u00e9es ; cependant, dans un passe-partout, nous allons probablement utiliser ces variables avant la fin du projet.<\/p>\n<p>Donc, \u00e0 cette fin, il n&rsquo;y a pas besoin de s&rsquo;inqui\u00e9ter \u00e0 ce stade. On s&rsquo;en occupera le moment venu.<\/p>\n<h2>Jusqu&rsquo;au PSR<\/h2>\n<p>\u00c0 ce stade, une grande partie du plug-in a \u00e9t\u00e9 achet\u00e9e conform\u00e9ment aux normes PSR et dispose d&rsquo;un ensemble solide d&rsquo;outils que nous pouvons utiliser pour tester syst\u00e9matiquement notre code tout en l&rsquo;\u00e9crivant.<\/p>\n<p>Si vous suivez le r\u00e9f\u00e9rentiel, la branche de <strong><a href=\"https:\/\/github.com\/tommcfarlin\/WordPress-Widget-Boilerplate\/tree\/develop\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">d\u00e9veloppement<\/a><\/strong> a \u00e9t\u00e9 mise \u00e0 jour pour refl\u00e9ter les modifications apport\u00e9es \u00e0 cet article, alors n&rsquo;h\u00e9sitez pas \u00e0 l&rsquo;extraire et \u00e0 revoir le code.<\/p>\n<p>Dans le prochain article, nous commencerons \u00e0 refactoriser le code d&rsquo;une mani\u00e8re beaucoup plus orient\u00e9e objet.<\/p>\n<p><div id=\"PostUnique_PostSource\" style=\"padding-top: 50px\">Source d&rsquo;enregistrement:  <a target=\"_blank\" rel=\"noopener nofollow\" href=\"\/\/tommcfarlin.com\" class=\"external external_icon\">tommcfarlin.com<\/a><\/div><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Jetons un coup d&rsquo;\u0153il aux erreurs que le renifleur de code lance pour le WordPress Widget Boilerplate et voyons si nous ne pouvons pas le mettre \u00e0 des normes plus modernes.<\/p>\n","protected":false},"author":1,"featured_media":236238,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","_wp_rev_ctl_limit":""},"categories":[893,717,801,841,862],"tags":[1167],"class_list":["post-231158","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-code-2","category-developpeur","category-php-3","category-tutoriels","category-wordpress-3","tag-affiai-fr"],"_links":{"self":[{"href":"https:\/\/wordpress.mediadoma.com\/fr\/wp-json\/wp\/v2\/posts\/231158","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wordpress.mediadoma.com\/fr\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wordpress.mediadoma.com\/fr\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/fr\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/fr\/wp-json\/wp\/v2\/comments?post=231158"}],"version-history":[{"count":0,"href":"https:\/\/wordpress.mediadoma.com\/fr\/wp-json\/wp\/v2\/posts\/231158\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/fr\/wp-json\/wp\/v2\/media\/236238"}],"wp:attachment":[{"href":"https:\/\/wordpress.mediadoma.com\/fr\/wp-json\/wp\/v2\/media?parent=231158"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/fr\/wp-json\/wp\/v2\/categories?post=231158"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/fr\/wp-json\/wp\/v2\/tags?post=231158"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}