What is PHPUnit

Unit test is a test to check the operation in units such as classes and functions that are the constituent elements of the program. By using PHPUnit, it is possible to create a unit test procedure as a PHP program and execute it as a batch process from a command line or the like.

Speaking of PHP program testing, it is common to manually check the screen transition by manipulating the browser manually, enter values in the form and check the result with the eyes. However, it is quite tedious task to open the page many times during development, enter the test data in the same way, and manually do all the results correctly.

The advantage of using PHPUnit that can automate and repetitively execute troublesome test procedures manually.

Since you can run the test as many times as you like with a single command, you can improve test efficiency and eliminate manual errors as well. In addition, the created test program replaces the specifications, confirming that existing process works correctly in the process of continually improving the program, so-called “degrate” it can also be used to prevent. It can lead to maintenance and improvement of program quality.

class Hello
{
	public function getMessage()
	{
		return "Hello world";
	}
}

It assumes that composer is already installed.
[vagrant@localhost app]$ php composer.phar require phpunit/phpunit:7.1.4
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 29 installs, 0 updates, 0 removals
– Installing sebastian/version (2.0.1): Loading from cache
– Installing sebastian/resource-operations (1.0.0): Loading from cache
– Installing sebastian/recursion-context (3.0.0): Loading from cache
– Installing sebastian/object-reflector (1.1.1): Loading from cache
– Installing sebastian/object-enumerator (3.0.3): Loading from cache
– Installing sebastian/global-state (2.0.0): Loading from cache
– Installing sebastian/exporter (3.1.0): Loading from cache
– Installing sebastian/environment (3.1.0): Loading from cache
– Installing sebastian/diff (3.0.1): Loading from cache
– Installing sebastian/comparator (3.0.2): Loading from cache
– Installing doctrine/instantiator (1.1.0): Loading from cache
– Installing phpunit/php-text-template (1.2.1): Loading from cache
– Installing phpunit/phpunit-mock-objects (6.1.2): Downloading (100%)
– Installing phpunit/php-timer (2.0.0): Loading from cache
– Installing phpunit/php-file-iterator (1.4.5): Downloading (100%)
– Installing theseer/tokenizer (1.1.0): Loading from cache
– Installing sebastian/code-unit-reverse-lookup (1.0.1): Loading from cache
– Installing phpunit/php-token-stream (3.0.1): Downloading (100%)
– Installing phpunit/php-code-coverage (6.0.5): Downloading (100%)
– Installing symfony/polyfill-ctype (v1.10.0): Loading from cache
– Installing webmozart/assert (1.4.0): Downloading (100%)
– Installing phpdocumentor/reflection-common (1.0.1): Loading from cache
– Installing phpdocumentor/type-resolver (0.4.0): Loading from cache
– Installing phpdocumentor/reflection-docblock (4.3.0): Loading from cache
– Installing phpspec/prophecy (1.8.0): Loading from cache
– Installing phar-io/version (1.0.1): Downloading (100%)
– Installing phar-io/manifest (1.0.1): Downloading (100%)
– Installing myclabs/deep-copy (1.8.1): Loading from cache
– Installing phpunit/phpunit (7.1.4): Downloading (100%)
sebastian/global-state suggests installing ext-uopz (*)
phpunit/phpunit-mock-objects suggests installing ext-soap (*)
phpunit/php-code-coverage suggests installing ext-xdebug (^2.6.0)
phpunit/phpunit suggests installing phpunit/php-invoker (^2.0)
phpunit/phpunit suggests installing ext-xdebug (*)
Writing lock file
Generating autoload files

[vagrant@localhost app]$ vendor/bin/phpunit –version
PHPUnit 7.1.4 by Sebastian Bergmann and contributors.

What!?

Nest step, the path to use the phpunit command.

Pass data of URL argument in PHP

Extract arguments by specify URL. In the $_GET array, the value specified by the URL is substituted. In the first argument, argument names in the URL are enclosed in single quotation marks.

if(isset($_GET['preview_date'])){
	$date = $_GET['preview_date'];
	echo $date . "<br>";
}
if(isset($_GET['preview_time'])){
	$time = $_GET['preview_time'];
	echo $time;
}

PHP Paging algorithm

Make variable number of items displayed on one page.
Prepare a number of array.

$coin = ["Bitcoin", "Ethereum", "Ripple", "Litecoin", "Ethereum Classic", "DASH", "Bitshares", "Monero", "NEM", "Zcash", "Bitcoin Cash", "Bitcoin Gold", "Monacoin", "Lisk", "Factom"];

$array_num = count($coin);
$page = 2;
$number = 4;

$i = 0;
foreach($coin as $value){
	if(($number * ($page - 1) - 1 < $i) && ($i < $number * $page)){
		echo $value . "<br>";
	}
	$i++;
}

-> Ethereum Classic
DASH
Bitshares
Monero

It’s ok to change the variables, page and page_number with button.
It was easier than I thought♪

php date_format function and for use

The date_format function formats date and time values in a specified format.

$date = date_create('2019-01-17');

echo date_format($date, 'y/m/d') . "<br>";
echo date_format($date, 'y/m/d h:i:s') . "<br>";
echo date_format($date, 'g:i A') . "<br>";
echo date_format($date, 'G:i a') . "<br>";

-> 19/01/17
19/01/17 12:00:00
12:00 AM
0:00 am

php function reference
http://php.net/manual/en/function.date.php
It was said “date — Format a local time/date”

In laravel, if you want to set yyyy/mm/dd and hh:mm to validation, the specification of the format is the following code.

$validator = Validator::make($request->all(),[
     'date' => 'date_format:Y/m/d',
     'time' => 'date_format:H:i',
    ]);

Sample of PHP substr and mb_substr

“substr” is a function that can acquire a part of a specified character string.

here comes sample.

$char = "come on baby America";
echo substr($char, 1);

-> ome on baby America

If 1 is specified, character strings for the number of characters specified from o can be acquired.

$char = "502 bad gateway";
echo substr($char, 2, 7);

-> 2 bad g
From start position 2 to 7 characters.

mb_substr is also a function to retrieve a part of the specified character string, but what is the difference with substr?
mb_string can specify the character code of the character string in addition to specifying the starting position and the number of characters.

$char = "仮想通貨でおススメの通貨はありますか?";
echo substr($char, 2, 7, "utf-8");

-> Warning: substr() expects at most 3 parameters, 4 given in Standard input code on line 5

$char = "仮想通貨でおススメの通貨はありますか?";
echo mb_substr($char, 2, 7, "utf-8");

->通貨でおススメ

When using non-English, it’s easy to use, isn’t it?

Upload an image from a form with php

Move the uploaded image with move_uploaded_file to the specified fold.
Then let the image be displayed again in the view.

if(file_exists($_FILES['upfile']['tmp_name'])){
	$ext = substr($_FILES['upfile']['name'], strrpos($_FILES['upfile']['name'],'.') + 1);
	echo $ext."<br>";
	if(strtolower($ext) !== 'png' && strtolower($ext) !== 'jpg' && strtolower($ext) !== 'jpeg' && strtolower($ext) !== 'gif'){
		echo '画像以外のファイルが指定されています。画像ファイル(png/jpg/jpeg/gif)を指定して下さい';
		exit();
	}
	$image = "img/".basename($_FILES['upfile']['tmp_name']).".".$ext;
	if(move_uploaded_file($_FILES['upfile']['tmp_name'], $image)){
		echo "アップロード成功!!";
	} else {
		echo "失敗";
	}
	// insert $image into mysql
}


?>
<div id="content">
<h2>画像管理</h2>
<hr>
<form action="#" method="POST" enctype="multipart/form-data">
<div id="drag-drop-area">
 <div class="drag-drop-inside">
  <p class="drag-drop-info">ここにファイルをアップロード</p>
  <p>または</p>
  <!-- <input type="file" value="ファイルを選択" name="image"> -->
  <p class="drag-drop-buttons"><input id="fileInput" type="file" value="ファイルを選択" name="upfile"></p>
      <input type="submit" value="送信">
   </div>
  </div>
  <img src="<?php echo $image; ?>">
</form>

Before

After

Will implement this in laravel.
Or, in the case of laravel, is there a form to upload images?

Upload the image from the php form to s3

It is necessary to make access right to s3 bucket beforehand with IAM.
Use php library to upload to s3. Here is code.

require 'vendor/autoload.php';

if(file_exists($_FILES['upfile']['tmp_name'])){
	$ext = substr($_FILES['upfile']['name'], strrpos($_FILES['upfile']['name'],'.') + 1);
	echo $ext."<br>";
	if(strtolower($ext) !== 'png' && strtolower($ext) !== 'jpg' && strtolower($ext) !== 'jpeg' && strtolower($ext) !== 'gif'){
		echo '画像以外のファイルが指定されています。画像ファイル(png/jpg/jpeg/gif)を指定して下さい';
		exit();
	}

	$tmpname = str_replace('/tmp/', '', $_FILES['upfile']['tmp_name']);
	echo $tmpname;
	$s3client = new Aws\S3\S3Client([
			'credentials' => [
					'key' => '',
					'secret' => ''
			],
			'region' => 'ap-northeast-1',
			'version' => 'latest',
	]);

	$result = $s3client->putObject([
			'Bucket' => 'zeus-image',
			'Key' => 'test.png',
			'SourceFile' => $_FILES['upfile']['tmp_name'],
			'Content-Type' => mime_content_type($_FILES['upfile']['tmp_name']),
	]);

}


?>
<div id="content">
<h2>画像管理</h2>
<hr>
<form action="#" method="POST" enctype="multipart/form-data">
<div id="drag-drop-area">
 <div class="drag-drop-inside">
  <p class="drag-drop-info">ここにファイルをアップロード</p>
  <p>または</p>
  <!-- <input type="file" value="ファイルを選択" name="image"> -->
  <p class="drag-drop-buttons"><input id="fileInput" type="file" value="ファイルを選択" name="upfile"></p>
      <input type="submit" value="送信">
   </div>
  </div>
</form>

HTML form view

s3

You can confirm that it is being uploaded properly.

fixing a word of fgets regular expression

There is a trouble that it is not goes well at reading one line regular expression.
I would like to code if only one dot contained in a line, issue an alert.

$file = fopen("test.txt", "r");

if($file){
	while($line = fgets($file)){

		if(preg_match('/^.$/', $line)){
			echo "please write again.<br>";
		} else {
			echo "OK<br>";
		}

	}
}
fclose($file);

Regular expression does not work well in this code.

add half-width dot in the regular expression

if($file){
	while($line = fgets($file)){

		if(preg_match('/^..$/', $line)){
			echo "please write again.<br>";
		} else {
			echo "OK<br>";
		}

	}
}

A half-size dot in a regular expression means an arbitrary one character.

Starting and ending regular expression

I want to issue an alert when only a dot in a line.
It needs check for starting and ending regular expression.

Is it a character string starting with 〇〇?

preg_match("/^xx/", $char);

Is it a character string ending with 〇〇?

preg_match("/xx$/", $char);

Here is the main theme. When judging whether it is a character string of only dots, combine the above.

$char = '.';

if(preg_match('/^.$/', $char)){
	echo "please write again.";
} else {
	echo "OK";
}

-> please write again.

Yes, it is as expected.
I would like to apply next. Read the file and if there is a line with only dots, it will issue an error.

this is a popular Hamlet.
test.txt

To be, or not to be: that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
And by opposing end them? To die: to sleep;
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to, 'tis a consummation
Devoutly to be wish'd. To die, to sleep;

app.php

$file = fopen("text.txt", "r");

if($file){
	while($line = fgets($file)){

		if(preg_match('/^.$/', $char)){
			echo "please write again.<br>";
		} else {
			echo "OK<br>";
		}

	}
}


It is looks like it is going well😂

Count the number of characters, bytes, width in PHP

How to count the number of characters, number of bytes, character width (apparent length) of a character string in PHP?

1. strlen
function strlen
Generally, to know the number of bytes, use strlen.

mb_internal_encoding('UTF-8');
$char = 'To die: to sleep No more; and by a sleep to say we end. The heart-ache and the thousand natural shocks. That flesh is heir to, tis a consummation Devoutly to be wishd. ';
echo strlen($char);

168

2. mb_strlen
function mb_strlen
Also, use mb_strlen to distinguish between full-width and half-width characters and count the number of characters.

mb_internal_encoding('UTF-8');
$char = '名前(カタカナ)';

echo mb_strlen($char);

3. mb_strwidth
function mb_strwidth
Use mb_strwidth to count character width(apparent length).

mb_internal_encoding('UTF-8');
$char = 'おはようございます。';

echo mb_strwidth($char);

Let’s put emoji and count it.

mb_internal_encoding('UTF-8');
$char = 'こんにちは😀';

echo strlen($char);

-> 19
it is as expected.

Then, let’s display an alert if it is more than 10 bytes.

mb_internal_encoding('UTF-8');
$char = 'こんにちは😀';

// echo strlen($char);
if(strlen($char) > 10){
	echo "this is more than 10 byte, please write again";
} else {
	echo "confirmed.";
}

-> this is more than 10 byte, please write again

Perfect job, am I.