-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFile_System.php
More file actions
97 lines (80 loc) · 2.5 KB
/
Copy pathFile_System.php
File metadata and controls
97 lines (80 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace Tribe\Libs\Generators;
class File_System {
public function create_directory( $directory ) {
clearstatcache();
if ( is_dir( $directory ) ) {
return;
}
if ( ! wp_mkdir_p( $directory ) && ! is_dir( $directory ) ) {
\WP_CLI::error( 'Sorry...something went wrong when we tried to create ' . $directory );
}
}
public function write_file( $file, $contents, $overwrite = false ) {
if ( file_exists( $file ) && ! $overwrite ) {
\WP_CLI::error( 'Sorry... ' . $file . ' already exists.' );
}
if ( ! $handle = fopen( $file, 'w' ) ) {
\WP_CLI::error( 'Sorry...something went wrong when we tried to write to ' . $file );
}
fwrite( $handle, $contents );
return $handle;
}
public function insert_into_existing_file( $file, $new_line, $below_line ) {
if ( ! $handle = fopen( $file, 'r+' ) ) {
\WP_CLI::error( 'Sorry.. ' . $file . ' could not be opened.' );
}
$inserted = false;
$contents = '';
while ( ! feof( $handle ) ) {
$line = fgets( $handle );
$contents .= $line;
if ( ! $inserted && strpos( $line, $below_line ) !== false ) {
$contents .= $new_line;
$inserted = true;
}
}
if ( ! fclose( $handle ) ) {
\WP_CLI::error( 'Sorry.. ' . $file . ' an error has occurred.' );
}
$this->write_file( $file, $contents, true );
}
public function get_file( $path ) {
return file_get_contents( $path );
}
/**
* Thanks stackoverflow.
* gist: https://gist.github.com/stemar/bb7c5cd2614b21b624bf57608f995ac0
*
* @param array $array
* @param int $internal_indent
*
* @return mixed
*/
public function format_array_for_file( $array, $array_indent = 0, $internal_indent = 4 ) {
$object = json_decode( str_replace( [ '(', ')' ], [
'(',
')',
], json_encode( $array ) ), true );
$export = str_replace( [ 'array (', ')', '(', ')' ], [
'[',
']',
'(',
')',
], var_export( $object, true ) );
$export = preg_replace( "/ => \n[^\S\n]*\[/m", ' => [', $export );
$export = preg_replace( "/ => \[\n[^\S\n]*\]/m", ' => []', $export );
$spaces = str_repeat( ' ', $internal_indent );
$export = preg_replace( "/([ ]{2})(?![^ ])/m", $spaces, $export );
$export = preg_replace( "/^([ ]{2})/m", $spaces, $export );
$lines = explode( PHP_EOL, $export );
$export = '';
foreach ( $lines as $line ) {
$export .= str_repeat( ' ', $array_indent ) . $line . PHP_EOL;
}
return $export;
}
public function constant_from_class( $class_name ) {
return strtoupper( str_replace( '_', '', $class_name ) );
}
}