Home >Backend Development >PHP Tutorial >Using PHP CodeSniffer with WordPress: Installing and using PHP CodeSniffer
In the first article of this series, we defined code smells and looked at some examples of what they are and how we can refactor them to improve code quality. Recall:
[A] Code smells, also known as bad smells in computer programming code, are any symptoms in a program's source code that may indicate a deeper problem.
Eventually, we are working on implementing WordPress specific code sniffing rules, but before that, it is important to be familiar with PHP CodeSniffer.
In this article, we will learn what PHP CodeSniffer is, how to install it, how to run it against a sample script, and how to refactor said script. Then we’ll look at how to move on to WordPress-specific code.
If you have a local development environment set up, that's great; if not, that's okay. I'll provide some links to get you up and running quickly.
With that being said, let’s get started.
Before you begin, it is important to have some type of local development environment, even if it only includes a copy of the PHP interpreter.
Please note that if you are running a variant of Linux or OS X, you may already have PHP installed. If you do this, then you don't need to worry about anything else in this section. To determine if PHP is installed, run the following command at the command line:
$ php -v
You should see something similar to the following (although your output may vary depending on the version of PHP you choose to run):
PHP 5.6.10 (cli) (built: Jul 6 2015 14:28:54) Copyright (c) 1997-2015 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
If you are more advanced and have multiple copies of the project installed, you can run:
$ which php
You should see something like this:
/Applications/MAMP/bin/php/php5.6.10/bin/php
Though your output will vary depending on where your copy of PHP is installed.
Although this series is primarily aimed at beginners, there may be some of you willing to download a copy of PHP and install it on your system. If this is you, grab a copy of PHP from the project home page, install it, and return to this tutorial.
On the other hand, if this is new to you, then you may choose to use one of the installers for your operating system on the PHP homepage linked above or one of the utilities provided below.
All these packages have their own installers and will install PHP, MySQL and Apache. As mentioned before, our main concern is having a copy of PHP available on our system.
Once installed, try running the command mentioned in the first part of this section (or the equivalent for your system) and you should see similar output.
If you don't, then you may need to add the path to PHP to your environment variables. This is beyond the scope of this tutorial, so please consult the documentation for the version of the project you have installed.
Now that PHP is installed, we can start catching and cleaning code smells.
You can find the official PHP CodeSniffer software on GitHub.
From the project documentation:
PHP_CodeSniffer is a set of two PHP scripts; the primaryphpcs
script flags PHP, JavaScript and CSS files to detect violations of defined coding standards, and the secondphpcbf
Script to automatically correct coding standards violations. PHP_CodeSniffer is an important development tool that ensures your code remains clean and consistent.
If you've never seen anything like this before, it sounds really good, doesn't it? I mean, it's a tool designed to help ensure your code has a certain level of quality!
While the project mentions languages like CSS and JavaScript, we focus on PHP in this series. But that doesn't mean it's not important to check the quality of these language-specific files in your project.
Although it sounds great, it still raises some questions: How do we install the software, and how do we start inspecting our code?
Now let us answer these two questions.
If you search on Google for how to install PHP CodeSniffer, you'll probably end up with a variety of results, many of which will include using something called Pear.
Pear used to be the de facto package distribution system for PHP libraries, and although many packages are still available through the software, it has also been retired from other popular packages such as PHPUnit.
For this reason, I often recommend using the other available installation methods. This includes using tools like Composer, which is arguably the most popular dependency management software for PHP.
如果您以前从未使用过 Composer,请不要担心。我将提供您所需的所有步骤,以便通过 Composer 并以最少的工作在您的计算机上启动并运行 PHP CodeSniffer。如果您有兴趣了解更多信息,我们有很多有关如何使用 Composer 的教程,请随时查看。
在安装 PHP CodeSniffer 之前,我们需要实际安装 Composer。幸运的是,一旦您在本地计算机上启动并运行了 PHP,就可以很容易地做到这一点。
要安装 Composer,您可以下载此文件,然后从下载 Composer 安装程序的位置在命令行上执行以下命令:
$ php composer-setup.php --install-dir=bin --filename=composer
Composer 安装说明中的注释:
您可以使用--install-dir
选项将 Composer 安装到特定目录,并使用--filename
选项(重新)命名它。
有关更多信息,请随时参阅下载说明或在 GitHub 上查看整个项目。
安装完成后,您现在可以使用 Composer 将第三方依赖项(例如 PHP CodeSniffer)安装到您的项目中。不过,请记下您安装 Composer 副本的位置。运行它时您需要引用它,因为我们将从命令行运行它。
无论如何,让我们继续创建一个目录,我们将在其中运行 PHP 脚本。虽然此目录中还没有任何内容,但我们需要创建一个名为 composer.json
的文件。
我将调用我的目录 tutsplus-demo
,并将我的 Composer 文件包含在该目录中以开始使用。
创建文件后,将以下代码放入 JSON 文件中:
{ "require": { "squizlabs/php_codesniffer": "2.*" } }
简而言之,这告诉 Composer 在您执行正确的命令时安装 PHP CodeSniffer。请注意,require
指令执行以下操作:
列出该包所需的包。除非满足这些要求,否则不会安装该软件包。
您可以在文档中阅读有关 Composer 架构的更多信息。
一旦安装了 Composer,并且您的 composer.json
文件与上面的代码类似,就可以实际安装 PHP CodeSniffer 了。从命令行发出以下命令:
$ composer update
请注意,这是基于 Composer 在您的系统上公开可用的想法。如果没有,您可以通过键入已安装文件的完整路径来执行它,也可以将其添加到环境变量中,然后重新启动终端会话以重新加载变量。
Composer 完成工作后,您应该会看到如下内容:
您的 tutsplus-code
目录现在应如下所示:
特别注意,您有一个供应商目录。这意味着 Composer 正确安装了 PHP CodeSniffer。此时,我们已准备好评估 PHP 代码。
首先,我们来看一个示例脚本。我们要查看的内容可以在 Stack Overflow 上的这个答案中找到。
在 tutsplus-demo
目录中创建一个文件,并将其命名为 sample.php
。然后,确保该文件包含以下内容:
<?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } ?>
保存您的工作。接下来,我们可以从命令行运行 PHP CodeSniffer,并让它使用标准规则集评估上面脚本中的代码。
从您的终端输入以下命令:
$ vendor/bin/phpcs sample.php
这应该生成包含以下内容的输出:
Skyhopper5:tutsplus-demo tommcfarlin$ vendor/bin/phpcs sample.php FILE: /Users/tommcfarlin/Desktop/tutsplus-demo/sample.php ---------------------------------------------------------------------- FOUND 4 ERRORS AFFECTING 4 LINES ---------------------------------------------------------------------- 2 | ERROR | [ ] Missing file doc comment 5 | ERROR | [x] No space found after comma in function call 7 | ERROR | [ ] Expected "if (...) {\n"; found "if(...) {\n" 9 | ERROR | [ ] Expected "if (...) {\n"; found "if(...) {\n" ---------------------------------------------------------------------- PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- Time: 46ms; Memory: 3.5Mb Skyhopper5:tutsplus-demo tommcfarlin$
请注意,它发现了四个错误。第一列告诉您错误发生在哪一行,第二列指出这是一个错误(而不是警告),然后其余的告诉您它期望看到的内容与实际看到的内容。
所以让我们根据这些错误清理文件。一般来说,我们需要做到以下几点:
if
语句后添加空格。最终结果如下所示:
<?php /** * Determines if the file being uploaded is a legitimate image or not. * If so, allows the file to be uploaded. Otherwise, prevents the upload * from occurring. * * PHP Version 5 * * @category Demo * @package TutsPlus_Demo * @author Tom McFarlin <tom@tommcfarlin.com> * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link http://is.gd/dq0DhO * @since 1.0.0 */ $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if (isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if ($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } ?>
接下来,再次运行脚本,您应该不会得到任何输出。也就是说,您应该看到标准命令提示符。有时这意味着某些东西被破坏了,但在这种情况下,这意味着一切都按预期运行
不错吧?
现在想象一下这对于您每天使用的更大的代码库和脚本会有什么作用。
While it’s important to evaluate our code, avoid code smells, and strive for the highest quality possible, tools like PHP CodeSniffer are not meant to be used as a crutch. This means we have no excuse to write bad code because another tool will catch it.
Because it's not always the case.
Instead, it means a second pass. That is, its purpose is to capture things that we may have missed the first, second, or ninth time we wrote code. The nice thing about this particular program is that you can load different rules into PHP CodeSniffer depending on the environment, framework or library you are using.
This is exactly what we will be doing with WordPress in the next article.
As far as introductory material goes, we cover quite a bit in this tutorial. That said, let's consider setting up a basic development environment with PHP on our local machine.
Next, we learned about Composer and how to install it on our system. We've written our first Composer file for retrieving dependencies, the PHP CodeSniffer, and we've even evaluated and corrected the results that the software gave us.
If you are primarily a PHP developer, then I hope the first two articles in this series were helpful, but if you are a WordPress developer, we have a lot more to cover.
In the final article of this series, we will turn our attention to WordPress. Because it has its own set of coding standards, we'll look at how to load those rules into a PHP CodeSniffer and then evaluate plugins, theme code, etc. to see how we can use it in our day-to-day - working on our WordPress projects today .
Before we move on to the next article, take a look at the code above and make sure you have PHP and PHP CodeSniffer installed and are familiar with how it works, as we will be tying it all together.
Finally, you can view all of my courses and tutorials on my profile page and you can follow me on my blog and/or Twitter (@tommcfarlin) where I discuss various software development practices , especially in a WordPress environment.
Please feel free to leave any questions or comments in the feed below and I will do my best to respond to each one.
The above is the detailed content of Using PHP CodeSniffer with WordPress: Installing and using PHP CodeSniffer. For more information, please follow other related articles on the PHP Chinese website!