| Total Complexity | 7 |
| Total Lines | 75 |
| Duplicated Lines | 0 % |
| Coverage | 95.24% |
| Changes | 0 | ||
| 1 | <?php |
||
| 18 | class Parser |
||
| 19 | { |
||
| 20 | // https://regex101.com/r/xH7cL3/2 |
||
| 21 | const PATTERN = '^\s*(?:<!--|---|\+\+\+){1}[\n\r\s]*(.*?)[\n\r\s]*(?:-->|---|\+\+\+){1}[\s\n\r]*(.*)$'; |
||
| 22 | /** @var SplFileInfo */ |
||
| 23 | protected $file; |
||
| 24 | /** @var string */ |
||
| 25 | protected $frontmatter; |
||
| 26 | /** @var string */ |
||
| 27 | protected $body; |
||
| 28 | |||
| 29 | /** |
||
| 30 | * @param SplFileInfo $file |
||
| 31 | */ |
||
| 32 | 1 | public function __construct(SplFileInfo $file) |
|
| 33 | { |
||
| 34 | 1 | $this->file = $file; |
|
| 35 | 1 | } |
|
| 36 | |||
| 37 | /** |
||
| 38 | * Parse the contents of the file. |
||
| 39 | * |
||
| 40 | * Example: |
||
| 41 | * --- |
||
| 42 | * title: Title |
||
| 43 | * date: 2016-07-29 |
||
| 44 | * --- |
||
| 45 | * Lorem Ipsum. |
||
| 46 | * |
||
| 47 | * @throws \RuntimeException |
||
| 48 | * |
||
| 49 | * @return self |
||
| 50 | */ |
||
| 51 | 1 | public function parse(): self |
|
| 52 | { |
||
| 53 | 1 | if ($this->file->isFile()) { |
|
| 54 | 1 | if (!$this->file->isReadable()) { |
|
| 55 | throw new \RuntimeException('Cannot read file'); |
||
| 56 | } |
||
| 57 | 1 | preg_match( |
|
| 58 | 1 | '/'.self::PATTERN.'/s', |
|
| 59 | 1 | $this->file->getContents(), |
|
| 60 | 1 | $matches |
|
| 61 | ); |
||
| 62 | // if there is not front matter, set body only |
||
| 63 | 1 | if (empty($matches)) { |
|
| 64 | 1 | $this->body = $this->file->getContents(); |
|
| 65 | |||
| 66 | 1 | return $this; |
|
| 67 | } |
||
| 68 | 1 | $this->frontmatter = trim($matches[1]); |
|
| 69 | 1 | $this->body = trim($matches[2]); |
|
| 70 | } |
||
| 71 | |||
| 72 | 1 | return $this; |
|
| 73 | } |
||
| 74 | |||
| 75 | /** |
||
| 76 | * Get frontmatter. |
||
| 77 | * |
||
| 78 | * @return string|null |
||
| 79 | */ |
||
| 80 | 1 | public function getFrontmatter(): ?string |
|
| 81 | { |
||
| 82 | 1 | return $this->frontmatter; |
|
| 83 | } |
||
| 84 | |||
| 85 | /** |
||
| 86 | * Get body. |
||
| 87 | * |
||
| 88 | * @return string |
||
| 89 | */ |
||
| 90 | 1 | public function getBody(): string |
|
| 93 | } |
||
| 94 | } |
||
| 95 |