class = new \ReflectionClass( static::class ); $properties = $class->getProperties( \ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED ); foreach ( $properties as $property ) { $doc_block = $property->getDocComment(); if ( ! stristr( $doc_block, '@defender_property' ) ) { continue; } $this->annotations[ $property->getName() ] = [ 'type' => $this->parse_annotations_var( $doc_block ), 'sanitize' => $this->parse_annotation_sanitize( $doc_block ), 'rule' => $this->parse_annotation_rule( $doc_block ), ]; } } /** * Get the variable type. * * @param $docblock * * @return bool|string */ private function parse_annotations_var( $docblock ) { $pattern = '/@var\s(.+)/'; if ( preg_match( $pattern, $docblock, $matches ) ) { $type = trim( $matches[1] ); // Only allow right type. if ( in_array( $type, [ 'boolean', 'bool', 'integer', 'int', 'float', 'double', 'string', 'array', 'object' ], true ) ) { return $type; } } return false; } /** * Get the sanitize function. * * @param $docblock * * @return bool|string */ private function parse_annotation_sanitize( $docblock ) { $pattern = '/@(sanitize_.+)/'; if ( preg_match( $pattern, $docblock, $matches ) ) { return trim( $matches[1] ); } return false; } /** * Get the validation rule. * * @param $docblock * * @return bool|string */ private function parse_annotation_rule( $docblock ) { $pattern = '/@(rule_.+)/'; if ( preg_match( $pattern, $docblock, $matches ) ) { return trim( $matches[1] ); } return false; } /** * Add a log for internal use, mostly for debug. * * @param string $message * @param string $category * * @return void */ protected function log( $message, $category = '' ): void { if ( ! is_string( $message ) || is_array( $message ) || is_object( $message ) ) { $message = print_r( $message, true ); } $this->internal_logging[] = date( 'Y-m-d H:i:s' ) . ' ' . $message;// phpcs:ignore // Uncomment it for detailed logging on wp cli. // if ( 'cli' === PHP_SAPI ) { // echo $message . PHP_EOL; // } $message = '[' . date( 'c' ) . '] ' . $message . PHP_EOL;// phpcs:ignore if ( $this->has_method( 'get_log_path' ) ) { if ( ! empty( $category ) && 0 === preg_match( '/\.log$/', $category ) ) { $category .= '.log'; } $file_path = $this->get_log_path( $category ); $dir_name = pathinfo( $file_path, PATHINFO_DIRNAME ); if ( ! is_dir( $dir_name ) ) { wp_mkdir_p( $dir_name ); } if ( is_writable( $dir_name ) ) { file_put_contents( $file_path, $message, FILE_APPEND ); } } } }