| 1 |
<?php |
| 2 |
/** |
| 3 |
* Author: Hoang Ngo |
| 4 |
*/ |
| 5 |
|
| 6 |
namespace Calotes\Base; |
| 7 |
|
| 8 |
/** |
| 9 |
* Every class should extend this class. |
| 10 |
* This contains generic function for checking internal info. |
| 11 |
* |
| 12 |
* Class Base |
| 13 |
* @package Calotes\Base |
| 14 |
*/ |
| 15 |
class Base { |
| 16 |
/** |
| 17 |
* Store internal logging, mostly for debug. |
| 18 |
* |
| 19 |
* @var array |
| 20 |
*/ |
| 21 |
protected $internal_logging = array(); |
| 22 |
|
| 23 |
/** |
| 24 |
* Store event handlers. |
| 25 |
* |
| 26 |
* @var array |
| 27 |
*/ |
| 28 |
protected $events = array(); |
| 29 |
|
| 30 |
/** |
| 31 |
* @param $property |
| 32 |
* |
| 33 |
* @return bool |
| 34 |
* @throws \ReflectionException |
| 35 |
*/ |
| 36 |
public function has_property( $property ) { |
| 37 |
$ref = new \ReflectionClass( $this ); |
| 38 |
|
| 39 |
return $ref->hasProperty( $property ); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* @param $method |
| 44 |
* |
| 45 |
* @return bool |
| 46 |
* @throws \ReflectionException |
| 47 |
*/ |
| 48 |
public function has_method( $method ) { |
| 49 |
$ref = new \ReflectionClass( $this ); |
| 50 |
|
| 51 |
return $ref->hasMethod( $method ); |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Add a log for internal use, mostly for debug. |
| 56 |
* |
| 57 |
* @param string $message |
| 58 |
* @param string $category |
| 59 |
*/ |
| 60 |
protected function log( $message, $category = '' ) { |
| 61 |
if ( ! is_string( $message ) || is_array( $message ) || is_object( $message ) ) { |
| 62 |
$message = print_r( $message, true ); |
| 63 |
} |
| 64 |
|
| 65 |
$this->internal_logging[] = date( 'Y-m-d H:i:s' ) . ' ' . $message; |
| 66 |
//uncomment it for detailed logging on wp cli |
| 67 |
// if ( 'cli' === PHP_SAPI ) { |
| 68 |
// echo $message . PHP_EOL; |
| 69 |
// } |
| 70 |
|
| 71 |
$message = '[' . date( 'c' ) . '] ' . $message . PHP_EOL; |
| 72 |
|
| 73 |
if ( $this->has_method( 'get_log_path' ) ) { |
| 74 |
if ( ! empty( $category ) && 0 === preg_match( '/\.log$/', $category ) ) { |
| 75 |
$category .= '.log'; |
| 76 |
} |
| 77 |
|
| 78 |
$file_path = $this->get_log_path( $category ); |
| 79 |
$dir_name = pathinfo( $file_path, PATHINFO_DIRNAME ); |
| 80 |
|
| 81 |
if ( ! is_dir( $dir_name ) ) { |
| 82 |
wp_mkdir_p( $dir_name ); |
| 83 |
} |
| 84 |
|
| 85 |
if ( is_writable( $dir_name ) ) { |
| 86 |
file_put_contents( $file_path, $message, FILE_APPEND ); |
| 87 |
} |
| 88 |
} |
| 89 |
} |
| 90 |
} |
| 91 |
|