Skip to content

Instantly share code, notes, and snippets.

@yuya-takeyama
Created November 9, 2012 11:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuya-takeyama/4045286 to your computer and use it in GitHub Desktop.
Save yuya-takeyama/4045286 to your computer and use it in GitHub Desktop.
難解な PHP プログラムと戦うために Xdebug でコードパスを解析する例
<?php
// 最初に実行しておく
xdebug_start_code_coverage();
if (false) {
// hoge
$foo = "bar";
} else {
foreach (range(1, 100) as $i) {
switch ($i % 3) {
case 0:
case 1:
foo();
break;
case 2:
$foo = "hoga";
break;
case 3:
case 4:
$bar = "baz";
case 5:
$baz = "foobar";
break;
default:
$foo;
}
}
$foo = "bar";
}
// プログラム終了のなるべく直前で実行する
generateCodepath('codepath.txt');
exit;
function foo() {
bar();
return true;
"hoge";
}
function bar() {
$foo = true;
return;
}
// 自ファイルのコードパスに印をつけて出力する関数
function generateCodepath($file) {
$fp = fopen($file, 'w');
$coverage = xdebug_get_code_coverage();
foreach ($coverage as $file => $info) {
if ($file === __FILE__) {
$lines = file(__FILE__);
foreach ($lines as $i => $line) {
$lineNum = $i + 1;
if (isset($info[$lineNum])) {
$data = '+ ';
} else {
$data = ' ';
}
fputs($fp, $data . $line);
}
}
}
fclose($fp);
}
<?php
// 最初に実行しておく
xdebug_start_code_coverage();
+ if (false) {
// hoge
$foo = "bar";
} else {
+ foreach (range(1, 100) as $i) {
+ switch ($i % 3) {
+ case 0:
+ case 1:
+ foo();
+ break;
+ case 2:
+ $foo = "hoga";
+ break;
case 3:
case 4:
$bar = "baz";
case 5:
$baz = "foobar";
break;
default:
$foo;
+ }
+ }
+ $foo = "bar";
}
// プログラム終了のなるべく直前で実行する
+ generateCodepath('codepath.txt');
exit;
function foo() {
+ bar();
+ return true;
"hoge";
}
function bar() {
+ $foo = true;
+ return;
}
// 自ファイルのコードパスに印をつけて出力する関数
function generateCodepath($file) {
+ $fp = fopen($file, 'w');
+ $coverage = xdebug_get_code_coverage();
foreach ($coverage as $file => $info) {
if ($file === __FILE__) {
$lines = file(__FILE__);
foreach ($lines as $i => $line) {
$lineNum = $i + 1;
if (isset($info[$lineNum])) {
$data = '+ ';
} else {
$data = ' ';
}
fputs($fp, $data . $line);
}
}
}
fclose($fp);
}
@yuya-takeyama
Copy link
Author

ライブラリ化してブログに紹介記事を書きました。
https://github.com/yuya-takeyama/code_path_analyzer
http://blog.yuyat.jp/archives/2055

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment