-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathSimpleRewriter.php
More file actions
92 lines (73 loc) · 2.92 KB
/
SimpleRewriter.php
File metadata and controls
92 lines (73 loc) · 2.92 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
<?php
/*
SimpleRewriter
A processed version of a StaticSite, with URLs rewritten, folders renamed
and other modifications made to prepare it for a Deployer
*/
namespace WP2Static;
class SimpleRewriter {
/**
* Rewrite URLs in file to destination_url
*
* @param string $filename file to rewrite URLs in
* @throws WP2StaticException
*/
public static function rewrite( string $filename ) : void {
$file_contents = file_get_contents( $filename );
if ( $file_contents === false ) {
$file_contents = '';
}
$rewritten_contents = self::rewriteFileContents( $file_contents );
file_put_contents( $filename, $rewritten_contents );
}
/**
* Rewrite URLs in a string to destination_url
*
* @param string $file_contents
* @return string
*/
public static function rewriteFileContents( string $file_contents ) : string
{
// TODO: allow empty file saving here? Exception for style.css
if ( ! $file_contents ) {
return '';
}
if ( (int) CoreOptions::getValue( 'skipURLRewrite' ) === 1 ) {
return $file_contents;
}
$destination_url = apply_filters(
'wp2static_set_destination_url',
CoreOptions::getValue( 'deploymentURL' )
);
$wordpress_home_url = apply_filters(
'wp2static_set_wordpress_home_url',
untrailingslashit( SiteInfo::getUrl( 'home' ) )
);
$wordpress_home_url = untrailingslashit( $wordpress_home_url );
$destination_url = untrailingslashit( $destination_url );
$destination_url_rel = URLHelper::getProtocolRelativeURL( $destination_url );
$destination_url_rel_c = addcslashes( $destination_url_rel, '/' );
$replacement_patterns = [
$wordpress_home_url => $destination_url,
URLHelper::getProtocolRelativeURL( $wordpress_home_url ) =>
URLHelper::getProtocolRelativeURL( $destination_url ),
addcslashes( URLHelper::getProtocolRelativeURL( $wordpress_home_url ), '/' ) =>
addcslashes( URLHelper::getProtocolRelativeURL( $destination_url ), '/' ),
];
$hosts = CoreOptions::getLineDelimitedBlobValue( 'hostsToRewrite' );
foreach ( $hosts as $host ) {
if ( $host ) {
$host_rel = URLHelper::getProtocolRelativeURL( 'http://' . $host );
$replacement_patterns[ 'http:' . $host_rel ] = $destination_url;
$replacement_patterns[ 'https:' . $host_rel ] = $destination_url;
$replacement_patterns[ $host_rel ] = $destination_url_rel;
$replacement_patterns[ addcslashes( $host_rel, '/' ) ] = $destination_url_rel_c;
}
}
$rewritten_contents = strtr(
$file_contents,
$replacement_patterns
);
return $rewritten_contents;
}
}