Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Transforms HAR file format to Blackfire file format
<?php
// Transforms a HAR (HTTP Archive) file into a BK file to analyze it using
// Blackfire Profiler (https://blackfire.io/)
//
// USAGE:
// $ php har2blackfire.php name-of-the-HAR-file.har
$harFile = $argv[1];
$harData = json_decode(file_get_contents($harFile), true);
// group requests by host
$groupedRequests = array();
$totalRequestTime = 0; // miliseconds * 1000
$totalResponseSize = 0; // bytes
foreach ($harData['log']['entries'] as $entry) {
$urlParts = parse_url($entry['request']['url']);
$requestHost = $urlParts['host'];
$groupedRequests[$requestHost]['entries'][] = $entry;
if (!array_key_exists('total_group_time', $groupedRequests[$requestHost])) {
$groupedRequests[$requestHost]['total_group_time'] = 0;
}
$groupedRequests[$requestHost]['total_group_time'] += (1000 * $entry['time']);
$totalRequestTime += (1000 * $entry['time']);
if (!array_key_exists('total_group_size', $groupedRequests[$requestHost])) {
$groupedRequests[$requestHost]['total_group_size'] = 0;
}
$responseBodySize = max(0, $entry['response']['bodySize']);
$groupedRequests[$requestHost]['total_group_size'] += $responseBodySize;
$totalResponseSize += $responseBodySize;
}
$dumpNodes = '';
// dump first-level nodes (hosts)
foreach ($groupedRequests as $host => $data) {
$dumpNodes .= sprintf("main()==>%s//%d %d %d\n", $host, count($data['entries']), $data['total_group_time'], $data['total_group_size']);
}
// dump second-level nodes (requests)
foreach ($groupedRequests as $host => $data) {
foreach ($data['entries'] as $entry) {
$urlParts = parse_url($entry['request']['url']);
$requestPath = $urlParts['path'];
$dumpNodes .= sprintf("%s==>%s::%s//%d %d %d\n", $host, $requestPath, $host, 1, 1000 * $entry['time'], max(0, $entry['response']['bodySize']));
}
}
$harFileTitle = $harData['log']['pages'][0]['title'];
$harFileDate = (new DateTime($harData['log']['pages'][0]['startedDateTime']))->format('d/m/Y H:i');
$dumpContents =
"file-format: BlackfireProbe\n"
."cost-dimensions: wt mu\n"
.sprintf("profile-title: %s (%s)\n", $harFileTitle, $harFileDate)
."\n"
.sprintf("main()//1 %d %d\n", $totalRequestTime, $totalResponseSize)
.$dumpNodes
;
$blackfireDumpFilepath = __DIR__.'/profile.bk';
file_put_contents($blackfireDumpFilepath, $dumpContents);
echo sprintf("The Blackfire profile file has been successfully generated in\n%s\n", $blackfireDumpFilepath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment