public function parse($path, $filename) { $file = file($path . DIRECTORY_SEPARATOR . $filename); $current = $this; if ($this->isRoot()) { $path .= DIRECTORY_SEPARATOR . basename($filename, '.txt'); } foreach ($file as $lineNum => $line) { // Checks if the line is a heading if (preg_match('/^(\+{1,6}) (.*)/', trim($line), $matches)) { $level = strlen($matches[1]); $heading = $matches[2]; if (($level > $this->getLevel()) && ($level <= $current->getLevel() + 1)) { // The current section did not have any text in this file. // Let's assume that the text is defined in another file. if ( ! $current->isRoot() && $current->_text === '') { $otherFilename = $current->getPath(false, DIRECTORY_SEPARATOR) . '.txt'; if (($filename !== $otherFilename) && (file_exists($path . DIRECTORY_SEPARATOR . $otherFilename))) { $current->parse($path, $otherFilename); } } $parent = $current; while ($parent->getLevel() >= $level) { $parent = $parent->_parent; } $current = new Sensei_Doc_Section($heading, $parent); } else { $format = 'Section has no direct parent, or level of the ' . 'heading is not greater than the level of the ' . 'file in "%s" on line %d'; $message = sprintf($format, $filename, $lineNum); throw new Sensei_Exception($message); } } else { if ($current->_text === '') { if (trim($line) !== '') { $current->_text = $line; } } else { $current->_text .= $line; } } } // The last section did not have any text in this file. // Let's assume that the text is defined in another file. if ( ! $current->isRoot() && $current->_text === '') { $otherFilename = $current->getPath(false, DIRECTORY_SEPARATOR) . '.txt'; if (($filename !== $otherFilename) && (file_exists($path . DIRECTORY_SEPARATOR . $otherFilename))) { $current->parse($path, $otherFilename); } } }
/** * Constructs a new table of contents from a file * * @param string $filename Name of the file that contains the section * structure. */ public function __construct($filename) { $this->_toc = new Sensei_Doc_Section(); $this->_toc->parse(dirname($filename), basename($filename)); }