policy = $policy; $this->htaccess = $htaccess; $this->robots = $robots; } /** * Publishes only when the files have fallen out of step with the settings. * * @return string[] Messages for anything that could not be written. */ public function sync(): array { return $this->is_in_step() ? array() : $this->publish(); } /** * Whether both files already say what the settings say. * * @return bool True when there is nothing to write. */ private function is_in_step(): bool { if ( $this->htaccess->is_available() && $this->htaccess->knows_site_root() ) { $wanted = ! empty( $this->policy->agents_to_enforce() ); if ( $wanted !== $this->htaccess->is_applied() || $this->htaccess->is_stale() ) { return false; } } if ( $this->robots->has_physical_file() ) { if ( ( '' !== $this->robots->build_block() ) !== $this->robots->physical_file_has_block() ) { return false; } } return true; } /** * Brings both files into line with the current policy. * * @return string[] Messages for anything that could not be written. */ public function publish(): array { $errors = array(); $this->publish_htaccess( $errors ); $this->publish_robots( $errors ); return $errors; } /** * Writes, updates or removes the .htaccess block. * * @param string[] $errors Collected failures, appended to. * @return void */ private function publish_htaccess( array &$errors ): void { if ( ! $this->htaccess->is_available() || ! $this->htaccess->knows_site_root() ) { return; } if ( empty( $this->policy->agents_to_enforce() ) ) { if ( $this->htaccess->is_applied() ) { $this->collect( $this->htaccess->revert(), $errors ); } return; } $this->collect( $this->htaccess->apply(), $errors ); } /** * Keeps a robots.txt file on disk in step with the rules. * * @param string[] $errors Collected failures, appended to. * @return void */ private function publish_robots( array &$errors ): void { if ( ! $this->robots->has_physical_file() ) { return; } if ( '' === $this->robots->build_block() ) { if ( $this->robots->physical_file_has_block() ) { $this->collect( $this->robots->revert_physical_file(), $errors ); } return; } $this->collect( $this->robots->merge_into_physical_file(), $errors ); } /** * Records a layer's failure message, if it failed. * * @param mixed $result Return value from an apply or revert. * @param string[] $errors Collected failures, appended to. * @return void */ private function collect( $result, array &$errors ): void { if ( is_wp_error( $result ) ) { $errors[] = $result->get_error_message(); } } }