From 8973f117f87a43b12a0494e48591b07091d0a9c7 Mon Sep 17 00:00:00 2001 From: Maxym Denysenko Date: Sun, 18 Oct 2020 16:49:25 +0300 Subject: [PATCH] Add cache --- src/class-cache.php | 152 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 src/class-cache.php diff --git a/src/class-cache.php b/src/class-cache.php new file mode 100644 index 0000000..cc419d2 --- /dev/null +++ b/src/class-cache.php @@ -0,0 +1,152 @@ +map_file = __DIR__ . '/../cache/classmap.php'; + if ( file_exists( $this->map_file ) ) { + include $this->map_file; + } + $this->map = is_array( $this->map ) ? $this->map : []; + register_shutdown_function( [ $this, 'save' ] ); + } + + /** + * Get path for class + * + * @param string $class Class name. + * + * @return string + */ + public function get( $class ) { + return isset( $this->map[ $class ] ) ? $this->map[ $class ] : ''; + } + + /** + * Update cache + * + * @param string $class Class name. + * @param string $path Path to file. + */ + public function update( $class, $path ) { + $this->has_been_update = true; + $this->map[ $class ] = $path; + } + + /** + * Save cache + */ + public function save() { + if ( ! $this->has_been_update ) { + return; + } + + $this->create_dir(); + + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents + file_put_contents( $this->map_file, 'create_map() . '];', LOCK_EX ); + } + + /** + * Create cache directory. + */ + private function create_dir() { + if ( ! file_exists( dirname( $this->map_file ) ) ) { + mkdir( dirname( $this->map_file ), 0755, true ); + } + } + + /** + * Create class map. + * + * @return string + */ + private function create_map() { + $map = ''; + $last = end( $this->map ); + foreach ( $this->map as $key => $value ) { + $map .= "'$key' => '$value'"; + if ( $value !== $last ) { + $map .= ",\n"; + } + } + + return $map; + } + + /** + * Clear garbage classes + */ + public function clear_garbage() { + foreach ( $this->map as $key => $file ) { + $this->clear_class( $key, $file ); + } + } + + /** + * Clear class + * + * @param string $class_name Class name. + * @param string $path Path to file. + */ + private function clear_class( $class_name, $path ) { + $path = realpath( $path ); + if ( ! file_exists( $path ) ) { + $this->has_been_update = true; + unset( $this->map[ $class_name ] ); + + return; + } + + $this->map[ $class_name ] = $path; + } + +}