<?php
Class MyParser{
function __construct(){
$this->regxp = '/(^\d+.\d+.\d+.\d+)\s*- -\s*([[]\d+\/\S+\s*[-|+]\d+])\s*"((POST|GET) \S+\s*\S+)"\s(\d+)\s*(\d+|-)\s*(\d+ \d+)?\s*"(http:\/\/\S+)"\s*"(\S+)\s*\(((compatible;\s*\S+ \d+.\d;))?(\s*\S+\s*\S+\s*\d+.\d+; \S+\s*\S+)\s*(\(\S+\s*\S+\s*\S+)?(\s*\D+)?/';
$this->path = 'http_access.log';
}
// Читаем файл и достаем строки из $this->path
function read_file()
{
if($handle = fopen($this->path, "r")){
while(!feof($handle)) {
yield trim(fgets($handle));
}
fclose($handle);
}
}
// Получаем интересующие нас значения файла с помощью регулярки
function get_log_array()
{
$iterator = $this->read_file();
foreach ($iterator as $v => $k) {
if(preg_match($this->regxp, $k, $m)){
$ips[] = $m[1];
$traffic[] = $m[6];
$statusCode[] = $m[5];
$urls[] = $m[12];
$main = array(
'ips' => $ips,
'traffic' => $traffic,
'statusCode' => $statusCode,
'urls' => $urls,
);
}
}
return $main;
}
// Получаем кол-во ip
function get_views()
{
return count($this->get_log_array()['ips']);
}
// Получаем трафик
function get_traffic()
{
$traffic_arr = $this->get_log_array()['traffic'];
for ($i = 0; $i < $this->get_views(); $i++) {
$traffic += (int)$traffic_arr[$i];
}
return $traffic;
}
// Получаем кол-во уникальных url
function get_urls(){
$urls = $this->get_log_array()['urls'];
for ($i = 0; $i < $this->get_views(); $i++) {
$urls[] .= $urls[$i];
}
return count(array_unique($urls));
}
// получаем статус-код
function get_status_codes(){
$status_codes = $this->get_log_array()['statusCode'];
$a = $b = 0;
for ($i = 0; $i < count($status_codes); $i++) {
if($status_codes[$i] == '200'){
$a++;
}
elseif($status_codes[$i] == '301'){
$b++;
}
}
$sc = array(
'200' => $a,
'301' => $b,
);
return $sc;
}
// Формируем массив и json файл с этим массивом
function create_json(){
$file = file_get_contents('result.json');
$log = json_encode($file, TRUE);
unset($file);
$log = array(
'views' => $this->get_views(),
'urls' => $this->get_urls(),
'traffic' => $this->get_traffic(),
'crawlers' => [
'Google' => 2,
'Bing' => 0,
'Baidu' => 0,
'Yandex' => 0,
],
'statusCodes' => $this->get_status_codes('http_access.log'),
);
file_put_contents('result.json', json_encode($log, JSON_PRETTY_PRINT));
unset($log);
}
}
$obj = new MyParser();
$obj->create_json();
Суть в том что мне дали задание распарсить файл в котором такие строки:
84.242.208.111- - [11/May/2013:06:31:00 +0200] "POST /chat.php HTTP/1.1" 200 354 "
bim-bom.ru" "Mozilla/5.0 (Windows NT 6.1; rv:20.0) Gecko/20100101 Firefox/20.0"
это одна строка.
Нужно было достать из строки интересующую информацию и отправить ее в json файл.
{
"views": 16,
"urls": 4,
"traffic": 187990,
"crawlers": {
"Google": 2,
"Bing": 0,
"Baidu": 0,
"Yandex": 0
},
"statusCodes": {
"200": 14,
"301": 2
}
}
Я сделал как просили, все работает. Но мне почему-то отказали с этим решением. Очень хотелось бы узнать почему.
Вообщем нужна критика кода и ооп)