Categories
PHP Tutorials WordPress

How to install WordPress Coding Standard on Ubuntu

WordPress has a set of coding standards that you can use when you develop either plugins or themes. While it’s not mandatory, I highly recommend using it on your project. It will make your code more user friendly and relatively easy to maintain in the long run.

I was a Windows user for a long time and recently switched to Ubuntu 20. When I tried to install WordPress Coding Standards, I struggled a few times since I’m new to the Linux OS. In this tutorial, I will show you step by step on how I did it on my end and hoping that this will help you out.

First requirement: composer. I’m using this throughout my installation. You can check their documentation on how you install it in your system.

Installation steps:

  1. Install PHP_CodeSniffer – This is the script that is responsible for tokenization of the PHP, CSS and Javascript code on your project that detects any code violation from the defined standard. By using a terminal in Linux, cd to your home directory and install PHP_CodeSniffer.
$ cd ~/
$ composer global require "squizlabs/php_codesniffer=*"
  1. Download WordPress Coding Standard – In my case, I would prefer to install this globally instead of per project. Make sure that you are still in your home directory in your terminal before starting. Executing the code below will clone the repository and rename it wpcs.
$ git clone -b master https://github.com/WordPress/WordPress-Coding-Standards.git wpcs
  1. After you have downloaded the WordPress Coding Standard, we need to set this on your local path. Now this is the part where I have struggled before so make sure you follow exactly to avoid the mistakes I’ve made.
$ sudo phpcs --config-set installed_paths /home/username/wpcs

Noticed the username? That would be the username of your current account. You should see this path when you go to Files -> Home, then press CTRL + L. You can verify if you have working sniffers by using phpcs -i.

PHPCS values

After you have confirmed that WordPress Coding Standard is added to your setup, we can now install the extensions we need for the Visual Studio Code. There are tons of similar extensions that are currently available, but these are the extensions that I am using and proven to be working.

Phpcbf by Per Soderlind and phpcs by Ioannis Kappas

Installations of these extensions are pretty much straightforward. Once you have done that, we are going to configure the settings. I would personally recommend that we set this up globally instead of per workspace. This will save you repetitive configuration, however if you prefer per workspace setup, you can copy the same settings from below as well.

Restart your Visual Code Editor, then go to File -> Preferences -> Settings -> Extensions -> PHP CodeSniffer configuration. Scroll down a bit until you see Edit in settings.json as shown below.

Click that link and add the following:

{
   "phpcs.enable": true,
   "phpcs.executablePath": "/path/to/phpcs",
   "phpcs.standard": "WordPress",
   "phpcbf.enable": true,
   "phpcbf.documentFormattingProvider": true,
   "phpcbf.onsave": true,
   "phpcbf.executablePath": "/path/to/phpcbf",
   "phpcbf.standard": "WordPress",
   "phpcs.showSources": true,
}

Now, open a terminal then go to your home directory then we need to determine the paths for phpcbf and phpcf that we need for the configuration.

$ cd ~/
$ which phpcs
$ which phpcbf

Copy the path of both tools and put them on the executablePath value respectively. Save and restart your Visual Code Editor. By this moment, you should be able to have the tools working. Open a sample PHP file and add your code, then when you click CTRL + S, it will sniff your code by default and phpcbf will auto format your code.

Let me know in the comment section if you find this tutorial useful or if you have any questions.

Happy coding!

Categories
PHP Tutorials

Formatting Multidimensional Array in PHP

Every PHP programmer or definitively all programmers must have encountered array in respective programming languages they’re good at. Either it single or multidimensional, every array is tricky.

If you are a wordpress developer either it’s plugin or theme or simply administrator, you must have known the popular Contact Form 7 and the independent plugin associated along with it, Contact Form 7 to Database. These are two popular plugins in WordPress SVN with multi-million download hits. What Contact Form 7 does is capturing the information and save it in database before Contact Form 7 sent the email and the database design is not somewhat beginners friendly. It uses the Unix formatted timestamp as secondary key to identify the group of columns which the information belongs to.

Now, if you query the table using WPDB global class, you get those in same format as below:

Array
(
    [0] => stdClass Object
        (
            [entry_id] => 6
            [entry_time] => 1369643273
            [entry_key] => last_name
            [entry_value] => Smith
        )

    [1] => stdClass Object
        (
            [entry_id] => 5
            [entry_time] => 1369643273
            [entry_key] => first_name
            [entry_value] => John
        )

    [2] => stdClass Object
        (
            [entry_id] => 7
            [entry_time] => 1369643273
            [entry_key] => age
            [entry_value] => 26
        )

    [3] => stdClass Object
        (
            [entry_id] => 8
            [entry_time] => 1369643273
            [entry_key] => ethnicity
            [entry_value] => Caucasian
        )

    [4] => stdClass Object
        (
            [entry_id] => 9
            [entry_time] => 1369643451
            [entry_key] => first_name
            [entry_value] => Fredirick
        )

    [5] => stdClass Object
        (
            [entry_id] => 10
            [entry_time] => 1369643451
            [entry_key] => last_name
            [entry_value] => Scheidner
        )

    [6] => stdClass Object
        (
            [entry_id] => 11
            [entry_time] => 1369643451
            [entry_key] => age
            [entry_value] => 29
        )

    [7] => stdClass Object
        (
            [entry_id] => 12
            [entry_time] => 1369643451
            [entry_key] => ethnicity
            [entry_value] => European
        )

)

It’s in a form of multidimensional array. Now if you analyze the array above, you can see that these information belong to a single table entry and the entry ID is not supposedly use as information key instead just a unique key that every database required to hold unique values. Only three array key that is useful: entry_time, entry_key and entry_value. The entry_time as I’ve explain earlier is a UNIX formatted time that was stored at the time the user submit the form using either PHP strtotime or MySql NOW().

So how we format this multidimensional array into array that represent the proper information like below?

Array
(
    [1369643451] => Array
        (
            [first_name] => Fredirick
            [last_name] => Scheidner
            [age] => 29
            [ethnicity] => European
        )

)

That’s our tutorial this time. Formatting multidimensional array in PHP using same values as key. Before we start let’s take a look one more time on this reformatted array. This only good on fetching single record but how about if we’re going to fetch more than one and how we arrange those records?

Array
(
    [0] => Array
        (
            [1369643451] => Array
                (
                    [first_name] => Fredirick
                    [last_name] => Scheidner
                    [age] => 29
                    [ethnicity] => European
                )

        )

    [1] => Array
        (
            [1369643273] => Array
                (
                    [last_name] => Smith
                    [first_name] => John
                    [age] => 26
                    [ethnicity] => Caucasian
                )

        )

)

Above is what our final output will look like. We are going to create PHP function that reformat multidimensional PHP array and use the repetitive values ( in our case, entry_time ) as array key. First, create a function and named it reconstruct that accepts 4 instances: the unformatted array, array key to be used, the actual array key from unformatted array and the array values.

function reconstruct( $arrayToReconstruct, $basedKey, $entry_key, $entry_value )
{

}

Create an empty array that will hold the formatted array and we will return it in final output.

$reconstructedArray = array();

Next, determine each array key and corresponding value, then check if that key exist in array key to be used.

if( in_array( $basedKey, $arrayToReconstruct[$key] ) )
{

}

After that, create an array that output as our sample above.

$reconstructedArray[$basedKey][ $arrayToReconstruct[$key][$entry_key] ]=$arrayToReconstruct[$key][$entry_value];

And finally return the reformatted array.

return $reconstructedArray;

Our final function will be look like this:

function reconstruct( $arrayToReconstruct, $basedKey, $entry_key, $entry_value ){

		$reconstructedArray = array();

		foreach( $arrayToReconstruct as $key=>$value ){
			if( in_array( $basedKey, $arrayToReconstruct[$key] ) ){

				$reconstructedArray[$basedKey][ $arrayToReconstruct[$key][$entry_key] ]=$arrayToReconstruct[$key][$entry_value];

			}
		}
		return $reconstructedArray;

	}

It’s that simple. So how do we use this function? First determine what array key that we will use from unformatted array we have which are ” 1369643451” for Fredirick Scheidner and “1369643273” for John Smith. Then use this function while looping the array key.

$key = array( "1369643451", "1369643273" );
$new = array();

foreach( $key as $value ){
	$new[] = reconstruct( $data, $value , "entry_key", "entry_value" );
}

That’s it, that’s how simple it is in formatting multidimensional array in PHP. I hope you can learn from this.