@@ -45,6 +45,10 @@ public function upload_files( string $processed_site_path ) : void {
4545 $ put_data ['CacheControl ' ] = $ cache_control ;
4646 }
4747
48+ $ cf_max_paths = Controller::getValue ( 'cfMaxPathsToInvalidate ' );
49+ $ cf_max_paths = $ cf_max_paths ? intval ( $ cf_max_paths ) : 0 ;
50+ $ cf_stale_paths = [];
51+
4852 foreach ( $ iterator as $ filename => $ file_object ) {
4953 $ base_name = basename ( $ filename );
5054 if ( $ base_name != '. ' && $ base_name != '.. ' ) {
@@ -87,9 +91,29 @@ public function upload_files( string $processed_site_path ) : void {
8791
8892 if ( $ result ['@metadata ' ]['statusCode ' ] === 200 ) {
8993 \WP2Static \DeployCache::addFile ( $ cache_key );
94+
95+ if ( $ cf_max_paths >= count ( $ cf_stale_paths ) ) {
96+ $ cf_key = $ cache_key ;
97+ if ( 0 === substr_compare ( $ cf_key , '/index.html ' , -11 ) ) {
98+ $ cf_key = substr ( $ cf_key , 0 , -10 );
99+ }
100+ array_push ( $ cf_stale_paths , $ cf_key );
101+ }
90102 }
91103 }
92104 }
105+
106+ $ distribution_id = Controller::getValue ( 'cfDistributionID ' );
107+ $ num_stale = count ( $ cf_stale_paths );
108+ if ( $ distribution_id && $ num_stale > 0 ) {
109+ if ( $ num_stale > $ cf_max_paths ) {
110+ self ::cloudfront_invalidate_all_items ();
111+ } else {
112+ $ path_text = ( $ num_stale === 1 ) ? 'path ' : 'paths ' ;
113+ \WP2Static \WsLog::l ( "Invalidating $ num_stale CloudFront $ path_text " );
114+ self ::create_invalidation ( $ distribution_id , $ cf_stale_paths );
115+ }
116+ }
93117 }
94118
95119 public static function s3_client () : \Aws \S3 \S3Client {
@@ -173,8 +197,8 @@ public static function cloudfront_client() : \Aws\CloudFront\CloudFrontClient {
173197 return $ client ;
174198 }
175199
176- public static function create_invalidation ( string $ distribution_id , array $ items,
177- int $ quantity ) : string {
200+ public static function create_invalidation ( string $ distribution_id , array $ items )
201+ : string {
178202 $ client = self ::cloudfront_client ();
179203
180204 return $ client ->createInvalidation (
@@ -184,7 +208,7 @@ public static function create_invalidation( string $distribution_id, array $item
184208 'CallerReference ' => 'WP2Static S3 Add-on ' . time (),
185209 'Paths ' => [
186210 'Items ' => $ items ,
187- 'Quantity ' => $ quantity ,
211+ 'Quantity ' => count ( $ items ) ,
188212 ],
189213 ],
190214 ]
@@ -196,11 +220,11 @@ public static function cloudfront_invalidate_all_items() : void {
196220 return ;
197221 }
198222
199- \WP2Static \WsLog::l ( 'Invalidating all CloudFront items ' );
223+ \WP2Static \WsLog::l ( 'Invalidating all CloudFront paths ' );
200224
201225 try {
202226 self ::create_invalidation ( Controller::getValue ( 'cfDistributionID ' ),
203- [ '/* ' ], 1 );
227+ [ '/* ' ]);
204228 } catch ( AwsException $ e ) {
205229 // output error message if fails
206230 error_log ( $ e ->getMessage () );
0 commit comments