#171 Redo the configuration layer to add a ConfigBuilder and group configuration parts

This commit is contained in:
Stéphane Goetz 2019-12-05 21:25:58 +01:00
parent 688de1d5b9
commit b5633e93c7
47 changed files with 1177 additions and 710 deletions

View File

@ -36,4 +36,19 @@ class BaseConfig extends ArrayObject
} }
} }
} }
public function hasValue($key)
{
return array_key_exists($key, $this);
}
public function getValue($key)
{
return $this[$key];
}
public function setValue($key, $value)
{
$this[$key] = $value;
}
} }

View File

@ -2,91 +2,96 @@
use Todaymade\Daux\Tree\Content; use Todaymade\Daux\Tree\Content;
use Todaymade\Daux\Format\HTML\Config as HTMLConfig; use Todaymade\Daux\Format\HTML\Config as HTMLConfig;
use Todaymade\Daux\Format\HTML\Theme as Theme;
use Todaymade\Daux\Format\Confluence\Config as ConfluenceConfig;
class Config extends BaseConfig class Config extends BaseConfig
{ {
public function getTitle() public function getTitle() {
{ return $this->getValue('title');
return $this['title'];
} }
public function getCurrentPage() public function hasAuthor(): bool {
{ return $this->hasValue('author');
return $this['current_page'];
} }
public function setCurrentPage(Content $entry) public function getAuthor() {
{ return $this->getValue('author');
$this['current_page'] = $entry;
} }
public function getDocumentationDirectory() public function hasTagline(): bool {
{ return $this->hasValue('tagline');
return $this['docs_directory'];
} }
public function setDocumentationDirectory($documentationPath) public function getTagline() {
{ return $this->getValue('tagline');
$this['docs_directory'] = $documentationPath;
} }
public function getThemesDirectory() public function getCurrentPage() {
{ return $this->getValue('current_page');
return $this['themes_directory'];
} }
public function setThemesDirectory($directory) public function setCurrentPage(Content $entry) {
{ $this->setValue('current_page', $entry);
$this['themes_directory'] = $directory;
} }
public function setThemesPath($themePath) public function getDocumentationDirectory() {
{ return $this->getValue('docs_directory');
$this['themes_path'] = $themePath;
} }
public function getThemesPath() public function getThemesDirectory() {
{ return $this->getValue('themes_directory');
return $this['themes_path'];
} }
public function setFormat($format) public function getThemesPath() {
{ return $this->getValue('themes_path');
$this['format'] = $format;
} }
public function getFormat() public function getFormat() {
{ return $this->getValue('format');
return $this['format'];
} }
public function hasTimezone() public function hasTimezone(): bool {
{
return isset($this['timezone']); return isset($this['timezone']);
} }
public function getTimezone() public function getTimezone() {
{ return $this->getValue('timezone');
return $this['timezone'];
} }
public function isMultilanguage() public function getTree() {
{ return $this->getValue('tree');
return array_key_exists('languages', $this) && !empty($this['languages']);
} }
public function isLive() public function setTree($tree) {
{ $this->setValue('tree', $tree);
return $this['mode'] == Daux::LIVE_MODE;
} }
public function isStatic() public function isMultilanguage(): bool {
{ return $this->hasValue('languages') && !empty($this->getValue('languages'));
return $this['mode'] == Daux::STATIC_MODE;
} }
public function shouldInheritIndex() public function getLanguages(): array {
{ return $this->getValue('languages');
}
public function getLanguage(): string {
return $this->getValue('language');
}
public function getMode() {
return $this->getValue('mode');
}
public function isLive() {
return $this->getValue('mode') == Daux::LIVE_MODE;
}
public function isStatic() {
return $this->getValue('mode') == Daux::STATIC_MODE;
}
public function shouldInheritIndex() {
// As the global configuration is always present, we // As the global configuration is always present, we
// need to test for the existence of the legacy value // need to test for the existence of the legacy value
// first. Then use the current value. // first. Then use the current value.
@ -97,41 +102,43 @@ class Config extends BaseConfig
return $this['html']['inherit_index']; return $this['html']['inherit_index'];
} }
public function setConfigurationOverrideFile($override_file) public function getIndexKey() {
{ return $this->getValue('mode') == Daux::STATIC_MODE ? 'index.html' : 'index';
$this['override_file'] = $override_file;
} }
public function getConfigurationOverrideFile() public function getProcessor() {
{ return $this->getValue('processor');
if (array_key_exists('override_file', $this)) {
return $this['override_file'];
}
return null;
} }
public function getConfluenceConfiguration() public function getConfluenceConfiguration(): ConfluenceConfig {
{ return new ConfluenceConfig($this->hasValue('confluence') ? $this->getValue('confluence') : []);
return $this['confluence'];
} }
public function getHTML() public function getHTML(): HTMLConfig {
{ return new HTMLConfig($this->hasValue('html') ? $this->getValue('html') : []);
return new HTMLConfig($this['html']);
} }
public function canCache() public function getTheme(): ?Theme {
{ return $this->hasValue('theme') ? new Theme($this->getValue('theme')) : null;
if (array_key_exists('cache', $this)) { }
return $this['cache'];
public function getValidContentExtensions() {
return $this->getValue('valid_content_extensions');
}
public function setValidContentExtensions(array $value) {
$this->setValue('valid_content_extensions', $value);
}
public function canCache() {
if ($this->hasValue('cache')) {
return $this->getValue('cache');
} }
return false; return false;
} }
public function getCacheKey() public function getCacheKey() {
{
$cloned = []; $cloned = [];
foreach ($this as $key => $value) { foreach ($this as $key => $value) {
$cloned[$key] = ($value instanceof Entry) ? $value->dump() : $value; $cloned[$key] = ($value instanceof Entry) ? $value->dump() : $value;
@ -139,4 +146,105 @@ class Config extends BaseConfig
return sha1(json_encode($cloned)); return sha1(json_encode($cloned));
} }
public function hasTranslationKey($language, $key): bool {
return array_key_exists($language, $this['strings']) && array_key_exists($key, $this['strings'][$language]);
}
public function getTranslationKey($language, $key) {
return $this['strings'][$language][$key];
}
public function hasImage(): bool {
return $this->hasValue('image');
}
public function getImage() {
return $this->getValue('image');
}
public function setImage($value) {
return $this->setValue('image', $value);
}
public function getLocalBase() {
return $this->getValue('local_base');
}
public function getTemplates() {
return $this->getValue('templates');
}
public function getBaseUrl() {
return $this->getValue('base_url');
}
public function getBasePage() {
if ($this->isLive()) {
$value = '//' . $this->getBaseUrl();
if (!$this['live']['clean_urls']) {
$value .= 'index.php/';
}
return $value;
}
return $this->getBaseUrl();
}
public function hasEntryPage(): bool {
return $this->hasValue('entry_page') && !empty($this->getValue('entry_page'));
}
public function getEntryPage() {
return $this->getValue('entry_page');
}
public function setEntryPage($value) {
return $this->setValue('entry_page', $value);
}
public function hasRequest(): bool {
return $this->hasValue('request') && !empty($this->getValue('request'));
}
public function getRequest() {
return $this->getValue('request');
}
public function setRequest($value) {
return $this->setValue('request', $value);
}
public function getIndex() {
return $this->getValue('index');
}
public function setIndex($value) {
return $this->setValue('index', $value);
}
public function hasProcessorInstance() {
return $this->hasValue('processor_instance');
}
public function getProcessorInstance() {
return $this->getValue('processor_instance');
}
public function setProcessorInstance($value) {
return $this->setValue('processor_instance', $value);
}
public function getIgnore() {
return $this->getValue('ignore');
}
public function hasHost() {
return $this->hasValue('host');
}
public function getHost() {
return $this->getValue('host');
}
} }

288
libs/ConfigBuilder.php Normal file
View File

@ -0,0 +1,288 @@
<?php namespace Todaymade\Daux;
class ConfigBuilder
{
/** @var Config */
private $config;
private $configuration_override_file = null;
private function __construct(string $mode) {
$this->config = new Config();
$this->config['mode'] = $mode;
$this->config['local_base'] = dirname(__DIR__);
}
static function fromFile($file): Config {
return unserialize(file_get_contents($file));
}
static function withMode($mode = Daux::STATIC_MODE): ConfigBuilder {
$builder = new ConfigBuilder($mode);
$builder->loadBaseConfiguration();
return $builder;
}
public function with(array $values): ConfigBuilder {
$this->config->merge($values);
return $this;
}
private function setValue(&$array, $key, $value) {
if (is_null($key)) {
return $array = $value;
}
$keys = explode('.', $key);
while (count($keys) > 1) {
$key = array_shift($keys);
if (!isset($array[$key]) || !is_array($array[$key])) {
$array[$key] = [];
}
$array = &$array[$key];
}
$array[array_shift($keys)] = $value;
return $array;
}
public function withValues(array $values): ConfigBuilder {
foreach ($values as $value) {
$this->setValue($this->config, $value[0], $value[1]);
}
return $this;
}
public function withDocumentationDirectory($dir): ConfigBuilder {
$this->config['docs_directory'] = $dir;
return $this;
}
public function withValidContentExtensions(array $value): ConfigBuilder {
$this->config['valid_content_extensions'] = $value;
return $this;
}
public function withThemesPath($themePath): ConfigBuilder {
$this->config['themes_path'] = $themePath;
return $this;
}
public function withThemesDirectory($directory): ConfigBuilder {
$this->config['themes_directory'] = $directory;
return $this;
}
public function withCache(bool $value): ConfigBuilder {
$this->config['cache'] = $value;
return $this;
}
public function withFormat($format): ConfigBuilder {
$this->config['format'] = $format;
return $this;
}
public function withConfigurationOverride($file): ConfigBuilder {
$this->configuration_override_file = $file;
return $this;
}
public function withProcessor($value): ConfigBuilder {
$this->config['processor'] = $value;
return $this;
}
public function withSearch($value): ConfigBuilder {
$this->config['html']['search'] = $value;
return $this;
}
public function withConfluenceDelete($value): ConfigBuilder {
$this->config['confluence']['delete'] = $value;
return $this;
}
function build(): Config {
$this->initializeConfiguration();
return $this->config;
}
private function resolveThemeVariant() {
$theme = $this->config->getHTML()->getTheme();
$themesPath = $this->config->getThemesPath() . DIRECTORY_SEPARATOR;
// If theme directory exists, we're good with that
if (is_dir(realpath(($themesPath . $theme)))) {
return [$theme, ''];
}
$themePieces = explode('-', $theme);
$variant = '';
// Do we have a variant or only a theme ?
if (count($themePieces) > 1) {
$variant = array_pop($themePieces);
$theme = implode('-', $themePieces);
}
if (!is_dir(realpath($themesPath . $theme))) {
throw new \RuntimeException("Theme '{$theme}' not found");
}
return [$theme, $variant];
}
/**
* @param string $override_file
* @throws Exception
*/
private function initializeConfiguration() {
// Validate and set theme path
$docs_path = $this->normalizeDocumentationPath($this->config->getDocumentationDirectory());
$this->config['docs_directory'] = $docs_path;
// Read documentation overrides
$this->loadConfiguration($docs_path . DIRECTORY_SEPARATOR . 'config.json');
// Read command line overrides
$override_file = $this->getConfigurationOverride($this->configuration_override_file);
if ($override_file !== null) {
$this->loadConfiguration($override_file);
}
// Validate and set theme path
$this->withThemesPath($this->normalizeThemePath($this->config->getThemesDirectory()));
// Resolve variant once
$theme = $this->resolveThemeVariant();
$this->config['html']['theme'] = $theme[0];
$this->config['html']['theme-variant'] = $theme[1];
// Set a valid default timezone
if ($this->config->hasTimezone()) {
date_default_timezone_set($this->config->getTimezone());
} elseif (!ini_get('date.timezone')) {
date_default_timezone_set('GMT');
}
// Text search would be too slow on live server
if ($this->config->isLive()) {
$this->config['html']['search'] = false;
}
}
private function normalizeThemePath($path) {
$validPath = $this->findLocation($path, $this->config->getLocalBase(), 'dir');
if (!$validPath) {
throw new Exception('The Themes directory does not exist. Check the path again : ' . $path);
}
return $validPath;
}
private function normalizeDocumentationPath($path) {
$validPath = $this->findLocation($path, $this->config->getLocalBase(), 'dir');
if (!$validPath) {
throw new Exception('The Docs directory does not exist. Check the path again : ' . $path);
}
return $validPath;
}
/**
* Load and validate the global configuration
*
* @throws Exception
*/
private function loadBaseConfiguration() {
// Set the default configuration
$this->config->merge([
'docs_directory' => 'docs',
'valid_content_extensions' => ['md', 'markdown'],
//Paths and tree
'templates' => 'templates',
'base_url' => '',
]);
// Load the global configuration
$this->loadConfiguration($this->config->getLocalBase() . DIRECTORY_SEPARATOR . 'global.json', false);
}
/**
* @param string $config_file
* @param bool $optional
* @throws Exception
*/
private function loadConfiguration($config_file, $optional = true) {
if (!file_exists($config_file)) {
if ($optional) {
return;
}
throw new Exception('The configuration file is missing. Check path : ' . $config_file);
}
$config = json_decode(file_get_contents($config_file), true);
if (!isset($config)) {
throw new Exception('The configuration file "' . $config_file . '" is corrupt. Is your JSON well-formed ?');
}
$this->config->merge($config);
}
/**
* Get the file requested for configuration overrides
*
* @param string|null $path
* @return string|null the path to a file to load for configuration overrides
* @throws Exception
*/
private function getConfigurationOverride($path) {
$validPath = $this->findLocation($path, $this->config->getLocalBase(), 'file');
if ($validPath === null) {
return null;
}
if (!$validPath) {
throw new Exception('The configuration override file does not exist. Check the path again : ' . $path);
}
return $validPath;
}
/**
* @param string|null $path
* @param string $basedir
* @param "dir"|"file" $type
* @return false|null|string
*/
private function findLocation($path, $basedir, $type) {
// If Path is explicitly null, it's useless to go further
if ($path == null) {
return null;
}
// VFS, used only in tests
if (substr($path, 0, 6) == "vfs://") {
return $path;
}
// Check if it's relative to the current directory or an absolute path
if (DauxHelper::is($path, $type)) {
return DauxHelper::getAbsolutePath($path);
}
// Check if it exists relative to Daux's root
$newPath = $basedir . DIRECTORY_SEPARATOR . $path;
if (DauxHelper::is($newPath, $type)) {
return $newPath;
}
return false;
}
}

View File

@ -4,6 +4,7 @@ use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Todaymade\Daux\ConfigBuilder;
use Todaymade\Daux\Daux; use Todaymade\Daux\Daux;
class DauxCommand extends SymfonyCommand class DauxCommand extends SymfonyCommand
@ -12,78 +13,55 @@ class DauxCommand extends SymfonyCommand
{ {
$this $this
->addOption('configuration', 'c', InputOption::VALUE_REQUIRED, 'Configuration file') ->addOption('configuration', 'c', InputOption::VALUE_REQUIRED, 'Configuration file')
->addOption('value', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Set different configuration values')
->addOption('source', 's', InputOption::VALUE_REQUIRED, 'Where to take the documentation from') ->addOption('source', 's', InputOption::VALUE_REQUIRED, 'Where to take the documentation from')
->addOption('processor', 'p', InputOption::VALUE_REQUIRED, 'Manipulations on the tree') ->addOption('processor', 'p', InputOption::VALUE_REQUIRED, 'Manipulations on the tree')
->addOption('no-cache', null, InputOption::VALUE_NONE, 'Disable Cache'); ->addOption('no-cache', null, InputOption::VALUE_NONE, 'Disable Cache')
->addOption('themes', 't', InputOption::VALUE_REQUIRED, 'Set a different themes directory (Used by HTML format only)')
// HTML Format only ->addOption('value', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Set different configuration values');
$this->addOption('themes', 't', InputOption::VALUE_REQUIRED, 'Set a different themes directory');
} }
private function setValue(&$array, $key, $value) protected function prepareConfig($mode, InputInterface $input, OutputInterface $output): ConfigBuilder
{ {
if (is_null($key)) { $builder = ConfigBuilder::withMode($mode);
return $array = $value;
}
$keys = explode('.', $key);
while (count($keys) > 1) {
$key = array_shift($keys);
if (!isset($array[$key]) || !is_array($array[$key])) {
$array[$key] = [];
}
$array = &$array[$key];
}
$array[array_shift($keys)] = $value;
return $array;
}
private function applyConfiguration(array $options, Daux $daux) if ($input->getOption('configuration')) {
{ $builder->withConfigurationOverride($input->getOption('configuration'));
$values = array_map(
function($value) {
return array_map("trim", explode('=', $value));
},
$options
);
foreach ($values as $value) {
$this->setValue($daux->options, $value[0], $value[1]);
}
}
protected function prepareDaux(InputInterface $input, OutputInterface $output)
{
$daux = new Daux(Daux::STATIC_MODE, $output);
// Set the format if requested
if ($input->hasOption('format') && $input->getOption('format')) {
$daux->getParams()->setFormat($input->getOption('format'));
} }
// Set the source directory
if ($input->getOption('source')) { if ($input->getOption('source')) {
$daux->getParams()->setDocumentationDirectory($input->getOption('source')); $builder->withDocumentationDirectory($input->getOption('source'));
} }
if ($input->getOption('themes')) { if ($input->getOption('processor')) {
$daux->getParams()->setThemesDirectory($input->getOption('themes')); $builder->withProcessor($input->getOption('processor'));
}
$daux->initializeConfiguration($input->getOption('configuration'));
if ($input->hasOption('delete') && $input->getOption('delete')) {
$daux->getParams()['confluence']['delete'] = true;
}
if ($input->hasOption('value')) {
$this->applyConfiguration($input->getOption('value'), $daux);
} }
if ($input->getOption('no-cache')) { if ($input->getOption('no-cache')) {
$daux->getParams()['cache'] = false; $builder->withCache(false);
} }
return $daux; if ($input->getOption('themes')) {
$builder->withThemesDirectory($input->getOption('themes'));
}
if ($input->hasOption('value')) {
$values = array_map(
function($value) {
return array_map("trim", explode('=', $value));
},
$input->getOption('value')
);
$builder->withValues($values);
}
return $builder;
}
protected function prepareProcessor(Daux $daux, $width)
{
$class = $daux->getProcessorClass();
if (!empty($class)) {
$daux->setProcessor(new $class($daux, $output, $width));
}
} }
} }

View File

@ -7,6 +7,7 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Terminal; use Symfony\Component\Console\Terminal;
use Todaymade\Daux\Daux; use Todaymade\Daux\Daux;
use Todaymade\Daux\ConfigBuilder;
class Generate extends DauxCommand class Generate extends DauxCommand
{ {
@ -29,6 +30,26 @@ class Generate extends DauxCommand
->addOption('search', null, InputOption::VALUE_NONE, 'Generate full text search'); ->addOption('search', null, InputOption::VALUE_NONE, 'Generate full text search');
} }
protected function prepareConfig($mode, InputInterface $input, OutputInterface $output): ConfigBuilder
{
$builder = parent::prepareConfig($mode, $input, $output);
// Set the format if requested
if ($input->hasOption('format') && $input->getOption('format')) {
$builder->withFormat($input->getOption('format'));
}
if ($input->hasOption('delete') && $input->getOption('delete')) {
$builder->withConfluenceDelete(true);
}
if ($input->hasOption('search')) {
$builder->withSearch($input->getOption('search'));
}
return $builder;
}
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
// When used as a default command, // When used as a default command,
@ -42,12 +63,13 @@ class Generate extends DauxCommand
$input = new ArgvInput($argv, $this->getDefinition()); $input = new ArgvInput($argv, $this->getDefinition());
} }
$daux = $this->prepareDaux($input, $output); $builder = $this->prepareConfig(Daux::STATIC_MODE, $input, $output);
$daux = new Daux($builder->build(), $output);
$width = (new Terminal)->getWidth(); $width = (new Terminal)->getWidth();
// Instiantiate the processor if one is defined // Instiantiate the processor if one is defined
$this->prepareProcessor($daux, $input, $output, $width); $this->prepareProcessor($daux, $width);
// Generate the tree // Generate the tree
$daux->generateTree(); $daux->generateTree();
@ -57,16 +79,4 @@ class Generate extends DauxCommand
return 0; return 0;
} }
protected function prepareProcessor(Daux $daux, InputInterface $input, OutputInterface $output, $width)
{
if ($input->getOption('processor')) {
$daux->getParams()['processor'] = $input->getOption('processor');
}
$class = $daux->getProcessorClass();
if (!empty($class)) {
$daux->setProcessor(new $class($daux, $output, $width));
}
}
} }

View File

@ -6,6 +6,7 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\ProcessUtils; use Symfony\Component\Process\ProcessUtils;
use Symfony\Component\Console\Terminal;
use Todaymade\Daux\Daux; use Todaymade\Daux\Daux;
use Todaymade\Daux\Server\Server; use Todaymade\Daux\Server\Server;
@ -19,8 +20,6 @@ class Serve extends DauxCommand
->setName('serve') ->setName('serve')
->setDescription('Serve documentation') ->setDescription('Serve documentation')
// Serve the current documentation
->addOption('serve', null, InputOption::VALUE_NONE, 'Serve the current directory')
->addOption('host', null, InputOption::VALUE_REQUIRED, 'The host to serve on', 'localhost') ->addOption('host', null, InputOption::VALUE_REQUIRED, 'The host to serve on', 'localhost')
->addOption('port', null, InputOption::VALUE_REQUIRED, 'The port to serve on', 8085); ->addOption('port', null, InputOption::VALUE_REQUIRED, 'The port to serve on', 8085);
} }
@ -30,17 +29,27 @@ class Serve extends DauxCommand
$host = $input->getOption('host'); $host = $input->getOption('host');
$port = $input->getOption('port'); $port = $input->getOption('port');
$daux = $this->prepareDaux($input, $output); $builder = $this->prepareConfig(Daux::LIVE_MODE, $input, $output);
// Daux can only serve HTML // Daux can only serve HTML
$daux->getParams()->setFormat('html'); $builder->withFormat('html');
$daux = new Daux($builder->build(), $output);
$width = (new Terminal)->getWidth();
// Instiantiate the processor if one is defined
$this->prepareProcessor($daux, $width);
// Write the current configuration to a file to read it from the other serving side
$file = tmpfile();
$path = stream_get_meta_data($file)['uri'];
fwrite($file, serialize($daux->getConfig()));
chdir(__DIR__ . '/../../'); chdir(__DIR__ . '/../../');
putenv('DAUX_CONFIG='. $path);
putenv('DAUX_VERBOSITY=' . $output->getVerbosity()); putenv('DAUX_VERBOSITY=' . $output->getVerbosity());
putenv('DAUX_SOURCE=' . $daux->getParams()->getDocumentationDirectory());
putenv('DAUX_THEME=' . $daux->getParams()->getThemesPath());
putenv('DAUX_CONFIGURATION=' . $daux->getParams()->getConfigurationOverrideFile());
putenv('DAUX_EXTENSION=' . DAUX_EXTENSION); putenv('DAUX_EXTENSION=' . DAUX_EXTENSION);
$base = escapeshellarg(__DIR__ . '/../../'); $base = escapeshellarg(__DIR__ . '/../../');
@ -49,6 +58,7 @@ class Serve extends DauxCommand
echo "Daux development server started on http://{$host}:{$port}/\n"; echo "Daux development server started on http://{$host}:{$port}/\n";
passthru("{$binary} -S {$host}:{$port} {$base}/index.php"); passthru("{$binary} -S {$host}:{$port} {$base}/index.php");
fclose($file);
return 0; return 0;
} }

View File

@ -25,8 +25,8 @@ class CommonMarkConverter extends \League\CommonMark\CommonMarkConverter
$this->extendEnvironment($environment, $config['daux']); $this->extendEnvironment($environment, $config['daux']);
if (array_key_exists('processor_instance', $config['daux'])) { if ($config['daux']->hasProcessorInstance()) {
$config['daux']['processor_instance']->extendCommonMarkEnvironment($environment); $config['daux']->getProcessorInstance()->extendCommonMarkEnvironment($environment);
} }
parent::__construct($config, $environment); parent::__construct($config, $environment);

View File

@ -49,20 +49,23 @@ class ContentType implements \Todaymade\Daux\ContentTypes\ContentType
{ {
$this->config->setCurrentPage($node); $this->config->setCurrentPage($node);
if (!$this->config->canCache()) { $can_cache = $this->config->canCache();
return $this->doConversion($raw);
}
// TODO :: add daux version to cache key // TODO :: add daux version to cache key
$cacheKey = $this->config->getCacheKey() . sha1($raw); $cacheKey = $this->config->getCacheKey() . sha1($raw);
$payload = Cache::get($cacheKey); $payload = Cache::get($cacheKey);
if ($payload) { if ($can_cache && $payload) {
Daux::writeln("Using cached version", OutputInterface::VERBOSITY_VERBOSE); Daux::writeln("Using cached version", OutputInterface::VERBOSITY_VERBOSE);
} else { }
Daux::writeln("Not found in the cache, generating...", OutputInterface::VERBOSITY_VERBOSE);
if (!$can_cache || !$payload) {
Daux::writeln($can_cache ? "Not found in the cache, generating..." : "Cache disabled, generating...", OutputInterface::VERBOSITY_VERBOSE);
$payload = $this->doConversion($raw); $payload = $this->doConversion($raw);
}
if ($can_cache) {
Cache::put($cacheKey, $payload); Cache::put($cacheKey, $payload);
} }

View File

@ -15,18 +15,13 @@ class Daux
public static $output; public static $output;
/** @var string */
public $local_base;
/** @var \Todaymade\Daux\Format\Base\Generator */ /** @var \Todaymade\Daux\Format\Base\Generator */
protected $generator; protected $generator;
/** @var ContentTypeHandler */ /** @var ContentTypeHandler */
protected $typeHandler; protected $typeHandler;
/** /** @var string[] */
* @var string[]
*/
protected $validExtensions; protected $validExtensions;
/** @var Processor */ /** @var Processor */
@ -36,155 +31,17 @@ class Daux
public $tree; public $tree;
/** @var Config */ /** @var Config */
public $options; public $config;
/** @var string */
private $mode;
/** @var bool */ /** @var bool */
private $merged_tree = false; private $merged_tree = false;
/** public function __construct(Config $config, OutputInterface $output)
* @param string $mode
*/
public function __construct($mode, OutputInterface $output)
{ {
Daux::$output = $output; Daux::$output = $output;
$this->mode = $mode;
$this->local_base = dirname(__DIR__);
$this->config = $config;
// global.json
$this->loadBaseConfiguration();
}
/**
* @param string $override_file
* @throws Exception
*/
public function initializeConfiguration($override_file = null)
{
$params = $this->getParams();
// Validate and set theme path
$params->setDocumentationDirectory(
$docs_path = $this->normalizeDocumentationPath($this->getParams()->getDocumentationDirectory())
);
// Read documentation overrides
$this->loadConfiguration($docs_path . DIRECTORY_SEPARATOR . 'config.json');
// Read command line overrides
$override_file = $this->getConfigurationOverride($override_file);
if ($override_file !== null) {
$params->setConfigurationOverrideFile($override_file);
$this->loadConfiguration($override_file);
}
// Validate and set theme path
$params->setThemesPath($this->normalizeThemePath($params->getThemesDirectory()));
// Set a valid default timezone
if ($params->hasTimezone()) {
date_default_timezone_set($params->getTimezone());
} elseif (!ini_get('date.timezone')) {
date_default_timezone_set('GMT');
}
}
/**
* Get the file requested for configuration overrides
*
* @param string|null $path
* @return string|null the path to a file to load for configuration overrides
* @throws Exception
*/
public function getConfigurationOverride($path)
{
$validPath = DauxHelper::findLocation($path, $this->local_base, 'DAUX_CONFIGURATION', 'file');
if ($validPath === null) {
return null;
}
if (!$validPath) {
throw new Exception('The configuration override file does not exist. Check the path again : ' . $path);
}
return $validPath;
}
public function normalizeThemePath($path)
{
$validPath = DauxHelper::findLocation($path, $this->local_base, 'DAUX_THEME', 'dir');
if (!$validPath) {
throw new Exception('The Themes directory does not exist. Check the path again : ' . $path);
}
return $validPath;
}
public function normalizeDocumentationPath($path)
{
$validPath = DauxHelper::findLocation($path, $this->local_base, 'DAUX_SOURCE', 'dir');
if (!$validPath) {
throw new Exception('The Docs directory does not exist. Check the path again : ' . $path);
}
return $validPath;
}
/**
* Load and validate the global configuration
*
* @throws Exception
*/
protected function loadBaseConfiguration()
{
$this->options = new Config();
// Set the default configuration
$this->options->merge([
'docs_directory' => 'docs',
'valid_content_extensions' => ['md', 'markdown'],
//Paths and tree
'mode' => $this->mode,
'local_base' => $this->local_base,
'templates' => 'templates',
'index_key' => 'index.html',
'base_page' => '',
'base_url' => '',
]);
// Load the global configuration
$this->loadConfiguration($this->local_base . DIRECTORY_SEPARATOR . 'global.json', false);
}
/**
* @param string $config_file
* @param bool $optional
* @throws Exception
*/
protected function loadConfiguration($config_file, $optional = true)
{
if (!file_exists($config_file)) {
if ($optional) {
return;
}
throw new Exception('The configuration file is missing. Check path : ' . $config_file);
}
$config = json_decode(file_get_contents($config_file), true);
if (!isset($config)) {
throw new Exception('The configuration file "' . $config_file . '" is corrupt. Is your JSON well-formed ?');
}
$this->options->merge($config);
} }
/** /**
@ -192,14 +49,14 @@ class Daux
*/ */
public function generateTree() public function generateTree()
{ {
$this->options['valid_content_extensions'] = $this->getContentExtensions(); $this->config->setValidContentExtensions($this->getContentExtensions());
$this->tree = new Root($this->getParams()); $this->tree = new Root($this->getConfig());
Builder::build($this->tree, $this->options['ignore']); Builder::build($this->tree, $this->config->getIgnore());
// Apply the language name as Section title // Apply the language name as Section title
if ($this->options->isMultilanguage()) { if ($this->config->isMultilanguage()) {
foreach ($this->options['languages'] as $key => $node) { foreach ($this->config->getLanguages() as $key => $node) {
$this->tree->getEntries()[$key]->setTitle($node); $this->tree->getEntries()[$key]->setTitle($node);
} }
} }
@ -216,22 +73,34 @@ class Daux
/** /**
* @return Config * @return Config
*/ */
public function getParams() public function getConfig()
{ {
if ($this->tree && !$this->merged_tree) { if ($this->tree && !$this->merged_tree) {
$this->options['tree'] = $this->tree; $this->config->setTree($this->tree);
$this->options['index'] = $this->tree->getIndexPage() ?: $this->tree->getFirstPage(); $this->config->setIndex($this->tree->getIndexPage() ?: $this->tree->getFirstPage());
if ($this->options->isMultilanguage()) { $entry_page = null;
foreach ($this->options['languages'] as $key => $name) { if ($this->config->isMultilanguage()) {
$this->options['entry_page'][$key] = $this->tree->getEntries()[$key]->getFirstPage(); $entry_page = [];
foreach ($this->config->getLanguages() as $key => $name) {
$entry_page[$key] = $this->tree->getEntries()[$key]->getFirstPage();
} }
} else { } else {
$this->options['entry_page'] = $this->tree->getFirstPage(); $entry_page= $this->tree->getFirstPage();
} }
$this->config->setEntryPage($entry_page);
$this->merged_tree = true; $this->merged_tree = true;
} }
return $this->options; return $this->config;
}
/**
* @return Config
* @deprecated Use getConfig instead
*/
public function getParams()
{
return $this->getConfig();
} }
/** /**
@ -254,9 +123,9 @@ class Daux
$this->processor = $processor; $this->processor = $processor;
// This is not the cleanest but it's // This is not the cleanest but it's
// the best i've found to use the // the best I've found to use the
// processor in very remote places // processor in very remote places
$this->options['processor_instance'] = $processor; $this->config->setProcessorInstance($processor);
} }
public function getGenerators() public function getGenerators()
@ -272,10 +141,9 @@ class Daux
return array_replace($default, $extended); return array_replace($default, $extended);
} }
public function getProcessorClass() public function getProcessorClass()
{ {
$processor = $this->getParams()['processor']; $processor = $this->getConfig()->getProcessor();
if (empty($processor)) { if (empty($processor)) {
return null; return null;
@ -318,7 +186,7 @@ class Daux
$generators = $this->getGenerators(); $generators = $this->getGenerators();
$format = $this->getParams()->getFormat(); $format = $this->getConfig()->getFormat();
if (!array_key_exists($format, $generators)) { if (!array_key_exists($format, $generators)) {
$message = "The format '$format' doesn't exist, did you forget to set your processor ?"; $message = "The format '$format' doesn't exist, did you forget to set your processor ?";

View File

@ -16,52 +16,27 @@ class DauxHelper
public static function rebaseConfiguration(Config $config, $base_url) public static function rebaseConfiguration(Config $config, $base_url)
{ {
// Avoid changing the url if it is already correct // Avoid changing the url if it is already correct
if ($config['base_url'] == $base_url && !empty($config['theme'])) { if ($config->getBaseUrl() == $base_url && !empty($config->getTheme())) {
return; return;
} }
// Change base url for all links on the pages // Change base url for all links on the pages
$config['base_url'] = $config['base_page'] = $base_url; $config['base_url'] = $base_url;
$config['theme'] = static::getTheme($config, $base_url); $config['theme'] = static::getTheme($config, $base_url);
$config['image'] = str_replace('<base_url>', $base_url, $config['image']); $config['image'] = str_replace('<base_url>', $base_url, $config->getImage());
}
protected static function resolveVariant(Config $params)
{
if (array_key_exists('theme-variant', $params['html'])) {
return;
}
if (is_dir(realpath(($params->getThemesPath() . DIRECTORY_SEPARATOR . $params['html']['theme'])))) {
return;
}
$theme = explode('-', $params['html']['theme']);
// do we have a variant or only a theme ?
if (isset($theme[1])) {
$params['html']['theme-variant'] = array_pop($theme);
$params['html']['theme'] = implode('-', $theme);
} else {
$params['html']['theme'] = array_pop($theme);
}
if (!is_dir(realpath($params->getThemesPath() . DIRECTORY_SEPARATOR . $params['html']['theme']))) {
throw new \RuntimeException("Theme '{$params['html']['theme']}' not found");
}
} }
/** /**
* @param Config $params * @param Config $config
* @param string $current_url * @param string $current_url
* @return array * @return array
*/ */
protected static function getTheme(Config $params, $current_url) protected static function getTheme(Config $config, $current_url)
{ {
self::resolveVariant($params); $htmlTheme = $config->getHTML()->getTheme();
$theme_folder = $params->getThemesPath() . DIRECTORY_SEPARATOR . $params['html']['theme']; $theme_folder = $config->getThemesPath() . DIRECTORY_SEPARATOR . $htmlTheme;
$theme_url = $params['base_url'] . 'themes/' . $params['html']['theme'] . '/'; $theme_url = $config->getBaseUrl() . 'themes/' . $htmlTheme . '/';
$theme = []; $theme = [];
if (is_file($theme_folder . DIRECTORY_SEPARATOR . 'config.json')) { if (is_file($theme_folder . DIRECTORY_SEPARATOR . 'config.json')) {
@ -73,7 +48,7 @@ class DauxHelper
//Default parameters for theme //Default parameters for theme
$theme += [ $theme += [
'name' => $params['html']['theme'], 'name' => $htmlTheme,
'css' => [], 'css' => [],
'js' => [], 'js' => [],
'fonts' => [], 'fonts' => [],
@ -82,8 +57,8 @@ class DauxHelper
'variants' => [], 'variants' => [],
]; ];
if (array_key_exists('theme-variant', $params['html'])) { if ($config->getHTML()->hasThemeVariant()) {
$variant = $params['html']['theme-variant']; $variant = $config->getHTML()->getThemeVariant();
if (!array_key_exists($variant, $theme['variants'])) { if (!array_key_exists($variant, $theme['variants'])) {
throw new Exception("Variant '$variant' not found for theme '$theme[name]'"); throw new Exception("Variant '$variant' not found for theme '$theme[name]'");
} }
@ -104,7 +79,7 @@ class DauxHelper
} }
$substitutions = [ $substitutions = [
'<local_base>' => $params['local_base'], '<local_base>' => $config->getLocalBase(),
'<base_url>' => $current_url, '<base_url>' => $current_url,
'<theme_url>' => $theme_url, '<theme_url>' => $theme_url,
]; ];
@ -156,7 +131,7 @@ class DauxHelper
*/ */
public static function getFilenames(Config $config, $part) public static function getFilenames(Config $config, $part)
{ {
$extensions = implode('|', array_map('preg_quote', $config['valid_content_extensions'])) . '|html'; $extensions = implode('|', array_map('preg_quote', $config->getValidContentExtensions())) . '|html';
$raw = preg_replace('/(.*)?\\.(' . $extensions . ')$/', '$1', $part); $raw = preg_replace('/(.*)?\\.(' . $extensions . ')$/', '$1', $part);
$raw = Builder::removeSortingInformations($raw); $raw = Builder::removeSortingInformations($raw);
@ -487,44 +462,6 @@ class DauxHelper
return getcwd() . '/' . $path; return getcwd() . '/' . $path;
} }
/**
* @param string|null $path
* @param string $basedir
* @param string $var The constant name to check
* @param "dir"|"file" $type
* @return false|null|string
*/
public static function findLocation($path, $basedir, $var, $type) {
// VFS, used only in tests
if (substr($path, 0, 6) == "vfs://") {
return $path;
}
// When running through `daux --serve` we set an environment variable to know where we started from
$env = getenv($var);
if ($env && DauxHelper::is($env, $type)) {
return $env;
}
// If Path is explicitly null, it's useless to go further
if ($path == null) {
return null;
}
// Check if it's relative to the current directory or an absolute path
if (DauxHelper::is($path, $type)) {
return DauxHelper::getAbsolutePath($path);
}
// Check if it exists relative to Daux's root
$newPath = $basedir . DIRECTORY_SEPARATOR . $path;
if (DauxHelper::is($newPath, $type)) {
return $newPath;
}
return false;
}
public static function is($path, $type) { public static function is($path, $type) {
return ($type == 'dir') ? is_dir($path) : file_exists($path); return ($type == 'dir') ? is_dir($path) : file_exists($path);
} }
@ -545,7 +482,7 @@ class DauxHelper
if ($url[0] == '!' || $url[0] == '/') { if ($url[0] == '!' || $url[0] == '/') {
$url = ltrim($url, '!/'); $url = ltrim($url, '!/');
if ($file = DauxHelper::getFile($config['tree'], $url)) { if ($file = DauxHelper::getFile($config->getTree(), $url)) {
return $file; return $file;
} }
@ -560,7 +497,7 @@ class DauxHelper
// If we didn't already try it, we'll // If we didn't already try it, we'll
// do a pass starting at the root // do a pass starting at the root
if (!$triedAbsolute && $file = DauxHelper::getFile($config['tree'], $url)) { if (!$triedAbsolute && $file = DauxHelper::getFile($config->getTree(), $url)) {
return $file; return $file;
} }

View File

@ -14,7 +14,7 @@ abstract class ContentPage extends SimplePage
/** /**
* @var Config * @var Config
*/ */
protected $params; protected $config;
/** /**
* @var ContentType * @var ContentType
@ -38,9 +38,17 @@ abstract class ContentPage extends SimplePage
return $this->file; return $this->file;
} }
public function setParams(Config $params) public function setConfig(Config $config)
{ {
$this->params = $params; $this->config = $config;
}
/**
* @deprecated use setConfig instead
*/
public function setParams(Config $config)
{
$this->setConfig($config);
} }
/** /**
@ -65,11 +73,11 @@ abstract class ContentPage extends SimplePage
return $this->getPureContent(); return $this->getPureContent();
} }
public static function fromFile(Content $file, $params, ContentType $contentType) public static function fromFile(Content $file, $config, ContentType $contentType)
{ {
$page = new static($file->getTitle(), $file->getContent()); $page = new static($file->getTitle(), $file->getContent());
$page->setFile($file); $page->setFile($file);
$page->setParams($params); $page->setConfig($config);
$page->setContentType($contentType); $page->setContentType($contentType);
return $page; return $page;

View File

@ -7,8 +7,8 @@ interface LiveGenerator extends Generator
{ {
/** /**
* @param Entry $node * @param Entry $node
* @param Config $params * @param Config $config
* @return \Todaymade\Daux\Format\Base\Page * @return \Todaymade\Daux\Format\Base\Page
*/ */
public function generateOne(Entry $node, Config $params); public function generateOne(Entry $node, Config $config);
} }

View File

@ -0,0 +1,66 @@
<?php namespace Todaymade\Daux\Format\Confluence;
use Todaymade\Daux\BaseConfig;
class Config extends BaseConfig
{
public function shouldAutoDeleteOrphanedPages() {
if (array_key_exists('delete', $this)) {
return $this['delete'];
}
return false;
}
public function getUpdateThreshold() {
return array_key_exists('update_threshold', $this) ? $this['update_threshold'] : 2;
}
public function getPrefix() {
return $this['prefix'];
}
public function getBaseUrl() {
return $this['base_url'];
}
public function getUser() {
return $this['user'];
}
public function getPassword() {
return $this['pass'];
}
public function getSpaceId() {
return $this['space_id'];
}
public function hasAncestorId() {
return array_key_exists('ancestor_id', $this);
}
public function getAncestorId() {
return $this['ancestor_id'];
}
public function setAncestorId($value) {
$this['ancestor_id'] = $value;
}
public function hasRootId() {
return array_key_exists('root_id', $this);
}
public function getRootId() {
return $this['root_id'];
}
public function hasHeader() {
return array_key_exists('header', $this);
}
public function getHeader() {
return $this['header'];
}
}

View File

@ -15,7 +15,7 @@ class ContentPage extends \Todaymade\Daux\Format\Base\ContentPage
//Embed images //Embed images
// We do it after generation so we can catch the images that were in html already // We do it after generation so we can catch the images that were in html already
$content = (new EmbedImages($this->params['tree'])) $content = (new EmbedImages($this->config->getTree()))
->embed( ->embed(
$content, $content,
$this->file, $this->file,
@ -36,10 +36,9 @@ class ContentPage extends \Todaymade\Daux\Format\Base\ContentPage
} }
); );
$intro = ''; $intro = '';
if (array_key_exists('confluence', $this->params) && array_key_exists('header', $this->params['confluence']) && !empty($this->params['confluence']['header'])) { if ($this->config->getConfluenceConfiguration()->hasHeader()) {
$intro = '<ac:structured-macro ac:name="info"><ac:rich-text-body>' . $this->params['confluence']['header'] . '</ac:rich-text-body></ac:structured-macro>'; $intro = '<ac:structured-macro ac:name="info"><ac:rich-text-body>' . $this->config->getConfluenceConfiguration()->getHeader() . '</ac:rich-text-body></ac:structured-macro>';
} }
return $intro . $content; return $intro . $content;

View File

@ -48,12 +48,12 @@ class FencedCodeRenderer extends CodeRenderer
throw new \InvalidArgumentException('Incompatible block type: ' . get_class($block)); throw new \InvalidArgumentException('Incompatible block type: ' . get_class($block));
} }
$language = $this->getLanguage($block->getInfoWords(), $htmlRenderer); $language = $this->getLanguage($block->getInfoWords());
return $this->getHTMLElement($block->getStringContent(), $language); return $this->getHTMLElement($block->getStringContent(), $language);
} }
public function getLanguage($infoWords, ElementRendererInterface $htmlRenderer) public function getLanguage($infoWords)
{ {
if (count($infoWords) === 0 || strlen($infoWords[0]) === 0) { if (count($infoWords) === 0 || strlen($infoWords[0]) === 0) {
return false; return false;

View File

@ -30,7 +30,7 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator
public function checkConfiguration() public function checkConfiguration()
{ {
$config = $this->daux->getParams(); $config = $this->daux->getConfig();
$confluence = $config->getConfluenceConfiguration(); $confluence = $config->getConfluenceConfiguration();
if ($confluence == null) { if ($confluence == null) {
@ -60,7 +60,7 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator
public function getContentTypes() public function getContentTypes()
{ {
return [ return [
new ContentTypes\Markdown\ContentType($this->daux->getParams()), new ContentTypes\Markdown\ContentType($this->daux->getConfig()),
]; ];
} }
@ -69,10 +69,10 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator
*/ */
public function generateAll(InputInterface $input, OutputInterface $output, $width) public function generateAll(InputInterface $input, OutputInterface $output, $width)
{ {
$params = $this->daux->getParams(); $config = $this->daux->getConfig();
$confluence = $params['confluence']; $confluence = $config->getConfluenceConfiguration();
$this->prefix = trim($confluence['prefix']) . ' '; $this->prefix = trim($confluence->getPrefix()) . ' ';
if ($this->prefix == ' ') { if ($this->prefix == ' ') {
$this->prefix = ''; $this->prefix = '';
} }
@ -80,9 +80,9 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator
$tree = $this->runAction( $tree = $this->runAction(
'Generating Tree ...', 'Generating Tree ...',
$width, $width,
function() use ($params) { function() use ($config) {
$tree = $this->generateRecursive($this->daux->tree, $params); $tree = $this->generateRecursive($this->daux->tree, $config);
$tree['title'] = $this->prefix . $params['title']; $tree['title'] = $this->prefix . $config->getTitle();
return $tree; return $tree;
} }
@ -96,31 +96,31 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator
$publisher->publish($tree); $publisher->publish($tree);
} }
private function generateRecursive(Directory $tree, Config $params, $base_url = '') private function generateRecursive(Directory $tree, Config $config, $base_url = '')
{ {
$final = ['title' => $this->prefix . $tree->getTitle()]; $final = ['title' => $this->prefix . $tree->getTitle()];
$params['base_url'] = $params['base_page'] = $base_url; $config['base_url'] = $base_url;
$params['image'] = str_replace('<base_url>', $base_url, $params['image']); $config->setImage(str_replace('<base_url>', $base_url, $config->getImage()));
if ($base_url !== '') { if ($base_url !== '') {
$params['entry_page'] = $tree->getFirstPage(); $config->setEntryPage($tree->getFirstPage());
} }
foreach ($tree->getEntries() as $key => $node) { foreach ($tree->getEntries() as $key => $node) {
if ($node instanceof Directory) { if ($node instanceof Directory) {
$final['children'][$this->prefix . $node->getTitle()] = $this->generateRecursive( $final['children'][$this->prefix . $node->getTitle()] = $this->generateRecursive(
$node, $node,
$params, $config,
'../' . $base_url '../' . $base_url
); );
} elseif ($node instanceof Content) { } elseif ($node instanceof Content) {
$params['request'] = $node->getUrl(); $config->setRequest($node->getUrl());
$contentType = $this->daux->getContentTypeHandler()->getType($node); $contentType = $this->daux->getContentTypeHandler()->getType($node);
$data = [ $data = [
'title' => $this->prefix . $node->getTitle(), 'title' => $this->prefix . $node->getTitle(),
'file' => $node, 'file' => $node,
'page' => ContentPage::fromFile($node, $params, $contentType), 'page' => ContentPage::fromFile($node, $config, $contentType),
]; ];
if ($key == 'index.html') { if ($key == 'index.html') {

View File

@ -13,7 +13,7 @@ class Publisher
protected $client; protected $client;
/** /**
* @var array * @var Config
*/ */
protected $confluence; protected $confluence;
@ -30,12 +30,12 @@ class Publisher
/** /**
* @param $confluence * @param $confluence
*/ */
public function __construct($confluence) public function __construct(Config $confluence)
{ {
$this->confluence = $confluence; $this->confluence = $confluence;
$this->client = new Api($confluence['base_url'], $confluence['user'], $confluence['pass']); $this->client = new Api($confluence->getBaseUrl(), $confluence->getUser(), $confluence->getPassword());
$this->client->setSpace($confluence['space_id']); $this->client->setSpace($confluence->getSpaceId());
} }
public function run($title, $closure) public function run($title, $closure)
@ -64,22 +64,21 @@ class Publisher
$published = $this->run( $published = $this->run(
"Create placeholder pages...", "Create placeholder pages...",
function() use ($tree, $published) { function() use ($tree, $published) {
return $this->createRecursive($this->confluence['ancestor_id'], $tree, $published); return $this->createRecursive($this->confluence->getAncestorId(), $tree, $published);
} }
); );
$this->output->writeLn('Publishing updates...'); $this->output->writeLn('Publishing updates...');
$published = $this->updateRecursive($this->confluence['ancestor_id'], $tree, $published); $published = $this->updateRecursive($this->confluence->getAncestorId(), $tree, $published);
$shouldDelete = array_key_exists('delete', $this->confluence) && $this->confluence['delete']; $delete = new PublisherDelete($this->output, $this->confluence->shouldAutoDeleteOrphanedPages(), $this->client);
$delete = new PublisherDelete($this->output, $shouldDelete, $this->client);
$delete->handle($published); $delete->handle($published);
} }
protected function getRootPage($tree) protected function getRootPage($tree)
{ {
if (array_key_exists('ancestor_id', $this->confluence)) { if ($this->confluence->hasAncestorId()) {
$pages = $this->client->getList($this->confluence['ancestor_id']); $pages = $this->client->getList($this->confluence->getAncestorId());
foreach ($pages as $page) { foreach ($pages as $page) {
if ($page['title'] == $tree['title']) { if ($page['title'] == $tree['title']) {
return $page; return $page;
@ -87,9 +86,9 @@ class Publisher
} }
} }
if (array_key_exists('root_id', $this->confluence)) { if ($this->confluence->hasRootId()) {
$published = $this->client->getPage($this->confluence['root_id']); $published = $this->client->getPage($this->confluence->getRootId());
$this->confluence['ancestor_id'] = $published['ancestor_id']; $this->confluence->setAncestorId($published['ancestor_id']);
return $published; return $published;
} }
@ -178,7 +177,7 @@ class Publisher
protected function updatePage($parent_id, $entry, $published) protected function updatePage($parent_id, $entry, $published)
{ {
$updateThreshold = array_key_exists('update_threshold', $this->confluence) ? $this->confluence['update_threshold'] : 2; $updateThreshold = $this->confluence->getUpdateThreshold();
$this->run( $this->run(
'- ' . PublisherUtilities::niceTitle($entry['file']->getUrl()), '- ' . PublisherUtilities::niceTitle($entry['file']->getUrl()),

View File

@ -22,7 +22,7 @@ class PublisherDelete
*/ */
protected $client; protected $client;
public function __construct($output, $delete, $client) public function __construct($output, bool $delete, $client)
{ {
$this->output = $output; $this->output = $output;
$this->delete = $delete; $this->delete = $delete;
@ -55,7 +55,6 @@ class PublisherDelete
if ($this->delete) { if ($this->delete) {
$this->doDelete(); $this->doDelete();
} else { } else {
$this->displayDeletable(); $this->displayDeletable();
} }

View File

@ -20,7 +20,6 @@ class Config extends BaseConfig
if (is_string($this['edit_on'])) { if (is_string($this['edit_on'])) {
return $this->prepareGithubUrl($this['edit_on']); return $this->prepareGithubUrl($this['edit_on']);
} else { } else {
$this['edit_on']['basepath'] = rtrim($this['edit_on']['basepath'], '/'); $this['edit_on']['basepath'] = rtrim($this['edit_on']['basepath'], '/');
return $this['edit_on']; return $this['edit_on'];
@ -28,9 +27,154 @@ class Config extends BaseConfig
} }
if (array_key_exists('edit_on_github', $this)) { if (array_key_exists('edit_on_github', $this)) {
return $this->prepareGithubUrl($this['edit_on_github']); return $this->prepareGithubUrl($this->getValue('edit_on_github'));
} }
return null; return null;
} }
public function hasSearch() {
return $this->hasValue('search') && $this->getValue('search');
}
public function showDateModified()
{
return $this->hasValue('date_modified') && $this->getValue('date_modified');
}
public function showPreviousNextLinks()
{
if ($this->hasValue('jump_buttons')) {
return $this->getValue('jump_buttons');
}
return true;
}
public function showCodeToggle()
{
if ($this->hasValue('toggle_code')) {
return $this->getValue('toggle_code');
}
return true;
}
public function hasAutomaticTableOfContents(): bool
{
return $this->hasValue('auto_toc') && $this->getValue('auto_toc');
}
public function hasGoogleAnalytics()
{
return $this->hasValue('google_analytics');
}
public function getGoogleAnalyticsId()
{
return $this->getValue('google_analytics');
}
public function hasPiwikAnalytics()
{
return $this->hasValue('piwik_analytics') && $this->hasValue('piwik_analytics_id');
}
public function getPiwikAnalyticsId()
{
return $this->getValue('piwik_analytics_id');
}
public function getPiwikAnalyticsUrl()
{
return $this->getValue('piwik_analytics');
}
public function hasPoweredBy()
{
return $this->hasValue('powered_by') && !empty($this->getValue('powered_by'));
}
public function getPoweredBy()
{
return $this->getValue('powered_by');
}
public function hasTwitterHandles()
{
return $this->hasValue('twitter') && !empty($this->getValue('twitter'));
}
public function getTwitterHandles()
{
return $this->getValue('twitter');
}
public function hasLinks()
{
return $this->hasValue('links') && !empty($this->getValue('links'));
}
public function getLinks()
{
return $this->getValue('links');
}
public function hasRepository()
{
return $this->hasValue('repo') && !empty($this->getValue('repo'));
}
public function getRepository()
{
return $this->getValue('repo');
}
public function hasButtons()
{
return $this->hasValue('buttons') && !empty($this->getValue('buttons'));
}
public function getButtons()
{
return $this->getValue('buttons');
}
public function hasLandingPage()
{
if ($this->hasValue('auto_landing')) {
return $this->getValue('auto_landing');
}
return true;
}
public function hasBreadcrumbs()
{
if ($this->hasValue('breadcrumbs')) {
return $this->getValue('breadcrumbs');
}
return true;
}
public function getBreadcrumbsSeparator()
{
return $this->getValue('breadcrumb_separator');
}
public function getTheme()
{
return $this->getValue('theme');
}
public function hasThemeVariant()
{
return $this->hasValue('theme-variant') && !empty($this->getValue('theme-variant'));
}
public function getThemeVariant()
{
return $this->getValue('theme-variant');
}
} }

View File

@ -4,7 +4,14 @@ use Todaymade\Daux\Tree\Root;
class ContentPage extends \Todaymade\Daux\Format\Base\ContentPage class ContentPage extends \Todaymade\Daux\Format\Base\ContentPage
{ {
/**
* @var string
*/
private $language; private $language;
/**
* @var bool
*/
private $homepage; private $homepage;
/** /**
@ -12,24 +19,19 @@ class ContentPage extends \Todaymade\Daux\Format\Base\ContentPage
*/ */
public $templateRenderer; public $templateRenderer;
private function isHomepage() private function isHomepage(): bool
{ {
// If the current page isn't the index, no chance it is the landing page // If the current page isn't the index, no chance it is the landing page
if ($this->file->getParent()->getIndexPage() != $this->file) { if ($this->file->getParent()->getIndexPage() != $this->file) {
return false; return false;
} }
// If the direct parent is root, this is the homage // If the direct parent is root, this is the homepage
return $this->file->getParent() instanceof Root; return $this->file->getParent() instanceof Root;
} }
private function isLanding() { private function isLanding(): bool {
// If we don't have the auto_landing parameter, we don't want any homepage return $this->config->getHTML()->hasLandingPage() && $this->homepage;
if (array_key_exists('auto_landing', $this->params['html']) && !$this->params['html']['auto_landing']) {
return false;
}
return $this->homepage;
} }
private function initialize() private function initialize()
@ -37,7 +39,7 @@ class ContentPage extends \Todaymade\Daux\Format\Base\ContentPage
$this->homepage = $this->isHomepage(); $this->homepage = $this->isHomepage();
$this->language = ''; $this->language = '';
if ($this->params->isMultilanguage() && count($this->file->getParents())) { if ($this->config->isMultilanguage() && count($this->file->getParents())) {
$language_dir = $this->file->getParents()[0]; $language_dir = $this->file->getParents()[0];
$this->language = $language_dir->getName(); $this->language = $language_dir->getName();
} }
@ -67,16 +69,16 @@ class ContentPage extends \Todaymade\Daux\Format\Base\ContentPage
protected function generatePage() protected function generatePage()
{ {
$this->initialize(); $this->initialize();
$params = $this->params; $config = $this->config;
$entry_page = []; $entry_page = [];
if ($this->homepage) { if ($this->homepage) {
if ($params->isMultilanguage()) { if ($config->isMultilanguage()) {
foreach ($params['languages'] as $key => $name) { foreach ($config->getLanguages() as $key => $name) {
$entry_page[$name] = $params['base_page'] . $params['entry_page'][$key]->getUrl(); $entry_page[$name] = $config->getBasePage() . $config->getEntryPage()[$key]->getUrl();
} }
} else { } else {
$entry_page['__VIEW_DOCUMENTATION__'] = $params['base_page'] . $params['entry_page']->getUrl(); $entry_page['__VIEW_DOCUMENTATION__'] = $config->getBasePage() . $config->getEntryPage()->getUrl();
} }
} }
@ -90,24 +92,24 @@ class ContentPage extends \Todaymade\Daux\Format\Base\ContentPage
'relative_path' => $this->file->getRelativePath(), 'relative_path' => $this->file->getRelativePath(),
'modified_time' => filemtime($this->file->getPath()), 'modified_time' => filemtime($this->file->getPath()),
'markdown' => $this->content, 'markdown' => $this->content,
'request' => $params['request'], 'request' => $config->getRequest(),
'content' => $this->getPureContent(), 'content' => $this->getPureContent(),
'breadcrumbs' => $params['html']['breadcrumbs'], 'breadcrumbs' => $config->getHTML()->hasBreadcrumbs(),
'prev' => $this->file->getPrevious(), 'prev' => $this->file->getPrevious(),
'next' => $this->file->getNext(), 'next' => $this->file->getNext(),
'attributes' => $this->file->getAttribute() 'attributes' => $this->file->getAttribute()
]; ];
if ($page['breadcrumbs']) { if ($page['breadcrumbs']) {
$page['breadcrumb_trail'] = $this->getBreadcrumbTrail($this->file->getParents(), $params->isMultilanguage()); $page['breadcrumb_trail'] = $this->getBreadcrumbTrail($this->file->getParents(), $config->isMultilanguage());
$page['breadcrumb_separator'] = $params['html']['breadcrumb_separator']; $page['breadcrumb_separator'] = $this->config->getHTML()->getBreadcrumbsSeparator();
if ($this->homepage) { if ($this->homepage) {
$page['breadcrumb_trail'] = [['title' => $this->file->getTitle(), 'url' => '']]; $page['breadcrumb_trail'] = [['title' => $this->file->getTitle(), 'url' => '']];
} }
} }
$context = ['page' => $page, 'params' => $params]; $context = ['page' => $page, 'config' => $config];
$template = "theme::content"; $template = "theme::content";
if ($this->isLanding()) { if ($this->isLanding()) {

View File

@ -17,6 +17,9 @@ use Todaymade\Daux\ContentTypes\Markdown\TableOfContents;
class Processor class Processor
{ {
/**
* @var Config
*/
protected $config; protected $config;
public function __construct(Config $config) public function __construct(Config $config)
@ -24,11 +27,6 @@ class Processor
$this->config = $config; $this->config = $config;
} }
public function hasAutoTOC()
{
return array_key_exists('html', $this->config) && array_key_exists('auto_toc', $this->config['html']) && $this->config['html']['auto_toc'];
}
/** /**
* @param DocumentParsedEvent $event * @param DocumentParsedEvent $event
* *
@ -60,7 +58,7 @@ class Processor
$headings[] = new Entry($node); $headings[] = new Entry($node);
} }
if (count($headings) && (count($tocs) || $this->hasAutoTOC())) { if (count($headings) && (count($tocs) || $this->config->getHTML()->hasAutomaticTableOfContents())) {
$generated = $this->generate($headings); $generated = $this->generate($headings);
if (count($tocs)) { if (count($tocs)) {

View File

@ -31,11 +31,11 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator, LiveGenerator
*/ */
public function __construct(Daux $daux) public function __construct(Daux $daux)
{ {
$params = $daux->getParams(); $config = $daux->getConfig();
$this->daux = $daux; $this->daux = $daux;
$this->templateRenderer = new Template($params); $this->templateRenderer = new Template($config);
$params->templateRenderer = $this->templateRenderer; $config->templateRenderer = $this->templateRenderer;
} }
/** /**
@ -44,7 +44,7 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator, LiveGenerator
public function getContentTypes() public function getContentTypes()
{ {
return [ return [
'markdown' => new ContentType($this->daux->getParams()), 'markdown' => new ContentType($this->daux->getConfig()),
]; ];
} }
@ -52,35 +52,31 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator, LiveGenerator
{ {
$destination = $input->getOption('destination'); $destination = $input->getOption('destination');
$params = $this->daux->getParams(); $config = $this->daux->getConfig();
if (is_null($destination)) { if (is_null($destination)) {
$destination = $this->daux->local_base . DIRECTORY_SEPARATOR . 'static'; $destination = $config->getLocalBase() . DIRECTORY_SEPARATOR . 'static';
} }
$this->runAction( $this->runAction(
'Copying Static assets ...', 'Copying Static assets ...',
$width, $width,
function() use ($destination, $params) { function() use ($destination, $config) {
$this->ensureEmptyDestination($destination); $this->ensureEmptyDestination($destination);
$this->copyThemes($destination, $params->getThemesPath()); $this->copyThemes($destination, $config->getThemesPath());
} }
); );
$output->writeLn('Generating ...'); $output->writeLn('Generating ...');
if (!array_key_exists('search', $params['html']) || !$params['html']['search']) { $this->generateRecursive($this->daux->tree, $destination, $config, $output, $width, $config->getHTML()->hasSearch());
$params['html']['search'] = $input->getOption('search');
}
$this->generateRecursive($this->daux->tree, $destination, $params, $output, $width, $params['html']['search']);
GeneratorHelper::copyRecursive( GeneratorHelper::copyRecursive(
$this->daux->local_base . DIRECTORY_SEPARATOR . 'daux_libraries' . DIRECTORY_SEPARATOR, $config->getLocalBase() . DIRECTORY_SEPARATOR . 'daux_libraries' . DIRECTORY_SEPARATOR,
$destination . DIRECTORY_SEPARATOR . 'daux_libraries' $destination . DIRECTORY_SEPARATOR . 'daux_libraries'
); );
if ($params['html']['search']) { if ($config->getHTML()->hasSearch()) {
file_put_contents( file_put_contents(
$destination . DIRECTORY_SEPARATOR . 'daux_search_index.json', $destination . DIRECTORY_SEPARATOR . 'daux_search_index.json',
json_encode(['pages' => $this->indexed_pages]) json_encode(['pages' => $this->indexed_pages])
@ -147,34 +143,34 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator, LiveGenerator
* *
* @param Directory $tree * @param Directory $tree
* @param string $output_dir * @param string $output_dir
* @param \Todaymade\Daux\Config $params * @param \Todaymade\Daux\Config $config
* @param OutputInterface $output * @param OutputInterface $output
* @param int $width * @param int $width
* @param bool $index_pages * @param bool $index_pages
* @param string $base_url * @param string $base_url
* @throws \Exception * @throws \Exception
*/ */
private function generateRecursive(Directory $tree, $output_dir, $params, $output, $width, $index_pages, $base_url = '') private function generateRecursive(Directory $tree, $output_dir, $config, $output, $width, $index_pages, $base_url = '')
{ {
DauxHelper::rebaseConfiguration($params, $base_url); DauxHelper::rebaseConfiguration($config, $base_url);
if ($base_url !== '' && empty($params['entry_page'])) { if ($base_url !== '' && !$config->hasEntryPage()) {
$params['entry_page'] = $tree->getFirstPage(); $config->setEntryPage($tree->getFirstPage());
} }
foreach ($tree->getEntries() as $key => $node) { foreach ($tree->getEntries() as $key => $node) {
if ($node instanceof Directory) { if ($node instanceof Directory) {
$new_output_dir = $output_dir . DIRECTORY_SEPARATOR . $key; $new_output_dir = $output_dir . DIRECTORY_SEPARATOR . $key;
mkdir($new_output_dir); mkdir($new_output_dir);
$this->generateRecursive($node, $new_output_dir, $params, $output, $width, $index_pages, '../' . $base_url); $this->generateRecursive($node, $new_output_dir, $config, $output, $width, $index_pages, '../' . $base_url);
// Rebase configuration again as $params is a shared object // Rebase configuration again as $config is a shared object
DauxHelper::rebaseConfiguration($params, $base_url); DauxHelper::rebaseConfiguration($config, $base_url);
} else { } else {
$this->runAction( $this->runAction(
'- ' . $node->getUrl(), '- ' . $node->getUrl(),
$width, $width,
function() use ($node, $output_dir, $key, $params, $index_pages) { function() use ($node, $output_dir, $key, $config, $index_pages) {
if ($node instanceof Raw) { if ($node instanceof Raw) {
copy($node->getPath(), $output_dir . DIRECTORY_SEPARATOR . $key); copy($node->getPath(), $output_dir . DIRECTORY_SEPARATOR . $key);
@ -183,7 +179,7 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator, LiveGenerator
$this->daux->tree->setActiveNode($node); $this->daux->tree->setActiveNode($node);
$generated = $this->generateOne($node, $params); $generated = $this->generateOne($node, $config);
file_put_contents($output_dir . DIRECTORY_SEPARATOR . $key, $generated->getContent()); file_put_contents($output_dir . DIRECTORY_SEPARATOR . $key, $generated->getContent());
if ($index_pages) { if ($index_pages) {
$this->indexed_pages[] = [ $this->indexed_pages[] = [
@ -201,10 +197,10 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator, LiveGenerator
/** /**
* @param Entry $node * @param Entry $node
* @param Config $params * @param Config $config
* @return \Todaymade\Daux\Format\Base\Page * @return \Todaymade\Daux\Format\Base\Page
*/ */
public function generateOne(Entry $node, Config $params) public function generateOne(Entry $node, Config $config)
{ {
if ($node instanceof Raw) { if ($node instanceof Raw) {
return new RawPage($node->getPath()); return new RawPage($node->getPath());
@ -214,9 +210,9 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator, LiveGenerator
return new ComputedRawPage($node); return new ComputedRawPage($node);
} }
$params['request'] = $node->getUrl(); $config->setRequest($node->getUrl());
$contentPage = ContentPage::fromFile($node, $params, $this->daux->getContentTypeHandler()->getType($node)); $contentPage = ContentPage::fromFile($node, $config, $this->daux->getContentTypeHandler()->getType($node));
$contentPage->templateRenderer = $this->templateRenderer; $contentPage->templateRenderer = $this->templateRenderer;
return $contentPage; return $contentPage;

View File

@ -13,25 +13,25 @@ class Template
{ {
protected $engine; protected $engine;
protected $params; protected $config;
/** /**
* @param string $base * @param string $base
* @param string $theme * @param string $theme
*/ */
public function __construct(Config $params) public function __construct(Config $config)
{ {
$this->params = $params; $this->config = $config;
} }
public function getEngine(Config $params) public function getEngine(Config $config)
{ {
if ($this->engine) { if ($this->engine) {
return $this->engine; return $this->engine;
} }
$base = $params['templates']; $base = $config->getTemplates();
$theme = $params['theme']['templates']; $theme = $config->getTheme()->getTemplates();
// Use internal templates if no templates // Use internal templates if no templates
// dir exists in the working directory // dir exists in the working directory
@ -60,14 +60,15 @@ class Template
*/ */
public function render($name, array $data = []) public function render($name, array $data = [])
{ {
$engine = $this->getEngine($data['params']); $engine = $this->getEngine($data['config']);
$engine->addData([ $engine->addData([
'base_url' => $data['params']['base_url'], 'base_url' => $data['config']->getBaseUrl(),
'base_page' => $data['params']['base_page'], 'base_page' => $data['config']->getBasePage(),
'page' => $data['page'], 'page' => $data['page'],
'params' => $data['params'], 'params' => $data['config'], // legacy name for config
'tree' => $data['params']['tree'], 'config' => $data['config'],
'tree' => $data['config']['tree'],
]); ]);
Daux::writeln("Rendering template '$name'", OutputInterface::VERBOSITY_VERBOSE); Daux::writeln("Rendering template '$name'", OutputInterface::VERBOSITY_VERBOSE);
@ -84,7 +85,7 @@ class Template
}); });
$engine->registerFunction('translate', function($key) { $engine->registerFunction('translate', function($key) {
$language = $this->params['language']; $language = $this->config->getLanguage();
if (isset($this->engine->getData('page')['page'])) { if (isset($this->engine->getData('page')['page'])) {
$page = $this->engine->getData('page'); $page = $this->engine->getData('page');
@ -93,14 +94,12 @@ class Template
} }
} }
if (array_key_exists($language, $this->params['strings'])) { if ($this->config->hasTranslationKey($language, $key)) {
if (array_key_exists($key, $this->params['strings'][$language])) { return $this->config->getTranslationKey($language, $key);
return $this->params['strings'][$language][$key];
}
} }
if (array_key_exists($key, $this->params['strings']['en'])) { if ($this->config->hasTranslationKey('en', $key)) {
return $this->params['strings']['en'][$key]; return $this->config->getTranslationKey('en', $key);
} }
return "Unknown key $key"; return "Unknown key $key";

View File

@ -0,0 +1,26 @@
<?php namespace Todaymade\Daux\Format\HTML;
use Todaymade\Daux\BaseConfig;
class Theme extends BaseConfig
{
public function getFonts() {
return $this->getValue('fonts');
}
public function getCSS() {
return $this->getValue('css');
}
public function getJS() {
return $this->getValue('js');
}
public function getFavicon() {
return $this->getValue('favicon');
}
public function getTemplates() {
return $this->getValue('templates');
}
}

View File

@ -13,7 +13,7 @@ class ContentPage extends \Todaymade\Daux\Format\Base\ContentPage
// Embed images // Embed images
// We do it after generation so we can catch the images that were in html already // We do it after generation so we can catch the images that were in html already
$content = (new EmbedImages($this->params['tree'])) $content = (new EmbedImages($this->config->getTree()))
->embed( ->embed(
$content, $content,
$this->file, $this->file,

View File

@ -23,11 +23,11 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator
*/ */
public function __construct(Daux $daux) public function __construct(Daux $daux)
{ {
$params = $daux->getParams(); $config = $daux->getConfig();
$this->daux = $daux; $this->daux = $daux;
$this->templateRenderer = new Template($params); $this->templateRenderer = new Template($config);
$params->templateRenderer = $this->templateRenderer; $config->templateRenderer = $this->templateRenderer;
} }
/** /**
@ -36,7 +36,7 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator
public function getContentTypes() public function getContentTypes()
{ {
return [ return [
'markdown' => new ContentType($this->daux->getParams()), 'markdown' => new ContentType($this->daux->getConfig()),
]; ];
} }
@ -47,9 +47,9 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator
{ {
$destination = $input->getOption('destination'); $destination = $input->getOption('destination');
$params = $this->daux->getParams(); $config = $this->daux->getConfig();
if (is_null($destination)) { if (is_null($destination)) {
$destination = $this->daux->local_base . DIRECTORY_SEPARATOR . 'static'; $destination = $this->config->getLocalBase() . DIRECTORY_SEPARATOR . 'static';
} }
$this->runAction( $this->runAction(
@ -61,9 +61,9 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator
); );
$data = [ $data = [
'author' => $params['author'], 'author' => $config->getAuthor(),
'title' => $params['title'], 'title' => $config->getTitle(),
'subject' => $params['tagline'] 'subject' => $config->getTagline()
]; ];
$book = new Book($this->daux->tree, $data); $book = new Book($this->daux->tree, $data);
@ -73,9 +73,9 @@ class Generator implements \Todaymade\Daux\Format\Base\Generator
$this->runAction( $this->runAction(
'Generating ' . $current->getTitle(), 'Generating ' . $current->getTitle(),
$width, $width,
function () use ($book, $current, $params) { function () use ($book, $current, $config) {
$contentType = $this->daux->getContentTypeHandler()->getType($current); $contentType = $this->daux->getContentTypeHandler()->getType($current);
$content = ContentPage::fromFile($current, $params, $contentType); $content = ContentPage::fromFile($current, $config, $contentType);
$content->templateRenderer = $this->templateRenderer; $content->templateRenderer = $this->templateRenderer;
$content = $content->getContent(); $content = $content->getContent();
$book->addPage($current, $content); $book->addPage($current, $content);

View File

@ -4,8 +4,8 @@ use IntlDateFormatter;
class FormatDate class FormatDate
{ {
public static function format($params, $date) { public static function format($config, $date) {
$locale = $params['language']; $locale = $config->getLanguage();
$datetype = IntlDateFormatter::LONG; $datetype = IntlDateFormatter::LONG;
$timetype = IntlDateFormatter::SHORT; $timetype = IntlDateFormatter::SHORT;
$timezone = null; $timezone = null;

View File

@ -12,17 +12,17 @@ class ErrorPage extends SimplePage
/** /**
* @var \Todaymade\Daux\Config * @var \Todaymade\Daux\Config
*/ */
private $params; private $config;
/** /**
* @param string $title * @param string $title
* @param string $content * @param string $content
* @param \Todaymade\Daux\Config $params * @param \Todaymade\Daux\Config $config
*/ */
public function __construct($title, $content, $params) public function __construct($title, $content, $config)
{ {
parent::__construct($title, $content); parent::__construct($title, $content);
$this->params = $params; $this->config = $config;
} }
/** /**
@ -30,15 +30,15 @@ class ErrorPage extends SimplePage
*/ */
protected function generatePage() protected function generatePage()
{ {
$params = $this->params; $config = $this->config;
$page = [ $page = [
'title' => $this->title, 'title' => $this->title,
'content' => $this->getPureContent(), 'content' => $this->getPureContent(),
'language' => '', 'language' => '',
]; ];
$template = new Template($params); $template = new Template($config);
return $template->render('error', ['page' => $page, 'params' => $params]); return $template->render('error', ['page' => $page, 'config' => $config]);
} }
} }

View File

@ -6,6 +6,7 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\MimeTypes; use Symfony\Component\Mime\MimeTypes;
use Todaymade\Daux\Daux; use Todaymade\Daux\Daux;
use Todaymade\Daux\ConfigBuilder;
use Todaymade\Daux\DauxHelper; use Todaymade\Daux\DauxHelper;
use Todaymade\Daux\Exception; use Todaymade\Daux\Exception;
use Todaymade\Daux\Format\Base\ComputedRawPage; use Todaymade\Daux\Format\Base\ComputedRawPage;
@ -16,7 +17,7 @@ use Todaymade\Daux\Format\HTML\RawPage;
class Server class Server
{ {
private $daux; private $daux;
private $params; private $config;
private $base_url; private $base_url;
/** /**
@ -34,18 +35,20 @@ class Server
$verbosity = getenv('DAUX_VERBOSITY'); $verbosity = getenv('DAUX_VERBOSITY');
$output = new ConsoleOutput($verbosity); $output = new ConsoleOutput($verbosity);
$daux = new Daux(Daux::LIVE_MODE, $output); $configFile = getenv('DAUX_CONFIG');
$daux->initializeConfiguration(); if ($configFile) {
$config = ConfigBuilder::fromFile($configFile);
} else {
$config = ConfigBuilder::withMode(Daux::LIVE_MODE)->build();
}
$daux = new Daux($config, $output);
$class = $daux->getProcessorClass(); $class = $daux->getProcessorClass();
if (!empty($class)) { if (!empty($class)) {
$daux->setProcessor(new $class($daux, $output, 0)); $daux->setProcessor(new $class($daux, $output, 0));
} }
// Set this critical configuration
// for the tree generation
$daux->getParams()['index_key'] = 'index';
// Improve the tree with a processor // Improve the tree with a processor
$daux->generateTree(); $daux->generateTree();
@ -54,7 +57,7 @@ class Server
try { try {
$page = $server->handle(); $page = $server->handle();
} catch (NotFoundException $e) { } catch (NotFoundException $e) {
$page = new ErrorPage('An error occured', $e->getMessage(), $daux->getParams()); $page = new ErrorPage('An error occured', $e->getMessage(), $daux->getConfig());
} }
$server->createResponse($page)->prepare($server->request)->send(); $server->createResponse($page)->prepare($server->request)->send();
@ -118,20 +121,14 @@ class Server
/** /**
* @return \Todaymade\Daux\Config * @return \Todaymade\Daux\Config
*/ */
public function getParams() public function getConfig()
{ {
$params = $this->daux->getParams(); $config = $this->daux->getConfig();
DauxHelper::rebaseConfiguration($params, '//' . $this->base_url); DauxHelper::rebaseConfiguration($config, '//' . $this->base_url);
$params['base_page'] = '//' . $this->base_url;
if (!$this->daux->options['live']['clean_urls']) {
$params['base_page'] .= 'index.php/';
}
// Text search would be too slow on live server
$params['html']['search'] = false;
return $params; return $config;
} }
/** /**
@ -143,7 +140,7 @@ class Server
*/ */
public function handle() public function handle()
{ {
$this->params = $this->getParams(); $this->config = $this->getConfig();
$request = substr($this->request->getRequestUri(), strlen($this->request->getBaseUrl()) + 1); $request = substr($this->request->getRequestUri(), strlen($this->request->getBaseUrl()) + 1);
@ -167,7 +164,7 @@ class Server
*/ */
public function serveTheme($request) public function serveTheme($request)
{ {
$file = $this->getParams()->getThemesPath() . $request; $file = $this->getConfig()->getThemesPath() . $request;
if (file_exists($file)) { if (file_exists($file)) {
return new RawPage($file); return new RawPage($file);
@ -199,6 +196,6 @@ class Server
); );
} }
return $this->daux->getGenerator()->generateOne($file, $this->params); return $this->daux->getGenerator()->generateOne($file, $this->config);
} }
} }

View File

@ -104,7 +104,7 @@ class Builder
$config = $parent->getConfig(); $config = $parent->getConfig();
if (!in_array($file->getExtension(), $config['valid_content_extensions'])) { if (!in_array($file->getExtension(), $config->getValidContentExtensions())) {
$uri = $file->getFilename(); $uri = $file->getFilename();
$entry = new Raw($parent, $uri, $file); $entry = new Raw($parent, $uri, $file);
@ -122,7 +122,7 @@ class Builder
$entry = new Content($parent, $uri, $file); $entry = new Content($parent, $uri, $file);
if ($entry->getUri() == $config['index_key']) { if ($entry->getUri() == $config->getIndexKey()) {
if ($parent instanceof Root) { if ($parent instanceof Root) {
$entry->setTitle($config->getTitle()); $entry->setTitle($config->getTitle());
} else { } else {
@ -184,7 +184,7 @@ class Builder
$path .= '.md'; $path .= '.md';
} }
$raw = !in_array($extension, $parent->getConfig()['valid_content_extensions']); $raw = !in_array($extension, $parent->getConfig()->getValidContentExtensions());
$title = $uri = $path; $title = $uri = $path;
if (!$raw) { if (!$raw) {

View File

@ -127,7 +127,7 @@ class Directory extends Entry implements \ArrayAccess, \IteratorAggregate
} }
public function getLocalIndexPage() { public function getLocalIndexPage() {
$index_key = $this->getConfig()['index_key']; $index_key = $this->getConfig()->getIndexKey();
if (isset($this->children[$index_key])) { if (isset($this->children[$index_key])) {
return $this->children[$index_key]; return $this->children[$index_key];
@ -141,8 +141,6 @@ class Directory extends Entry implements \ArrayAccess, \IteratorAggregate
*/ */
public function getIndexPage(): ?Content public function getIndexPage(): ?Content
{ {
$index_key = $this->getConfig()['index_key'];
if ($this->getLocalIndexPage()) { if ($this->getLocalIndexPage()) {
return $this->getLocalIndexPage(); return $this->getLocalIndexPage();
} }
@ -161,7 +159,7 @@ class Directory extends Entry implements \ArrayAccess, \IteratorAggregate
public function seekFirstPage(): ?Content public function seekFirstPage(): ?Content
{ {
if ($this instanceof self) { if ($this instanceof self) {
$index_key = $this->getConfig()['index_key']; $index_key = $this->getConfig()->getIndexKey();
if (isset($this->children[$index_key])) { if (isset($this->children[$index_key])) {
return $this->children[$index_key]; return $this->children[$index_key];
} }

View File

@ -16,6 +16,8 @@ function loadApp() {
$loader = loadApp(); $loader = loadApp();
// This will define the path at which to
// find the daux processor extensions
if ($loader) { if ($loader) {
$ext = __DIR__ . '/../daux'; $ext = __DIR__ . '/../daux';
if (is_dir(getcwd() . "/daux")) { if (is_dir(getcwd() . "/daux")) {

View File

@ -3,13 +3,13 @@
<div class="Page__header"> <div class="Page__header">
<h1><?= $page['breadcrumbs'] ? $this->get_breadcrumb_title($page, $base_page) : $page['title'] ?></h1> <h1><?= $page['breadcrumbs'] ? $this->get_breadcrumb_title($page, $base_page) : $page['title'] ?></h1>
<?php if ($params['html']['date_modified']) { ?> <?php if ($config->getHTML()->showDateModified()) { ?>
<span class="ModifiedDate"> <span class="ModifiedDate">
<?= Todaymade\Daux\FormatDate::format($params, $page['modified_time']) ?> <?= Todaymade\Daux\FormatDate::format($config, $page['modified_time']) ?>
</span> </span>
<?php } ?> <?php } ?>
<?php <?php
$edit_on = $params->getHTML()->getEditOn(); $edit_on = $config->getHTML()->getEditOn();
if ($edit_on) { ?> if ($edit_on) { ?>
<span class="EditOn"> <span class="EditOn">
<a href="<?= $edit_on['basepath'] ?>/<?= $page['relative_path'] ?>" target="_blank"> <a href="<?= $edit_on['basepath'] ?>/<?= $page['relative_path'] ?>" target="_blank">
@ -24,9 +24,8 @@
</div> </div>
<?php <?php
$buttons = (!empty($page['prev']) || !empty($page['next'])); $hasPrevNext = (!empty($page['prev']) || !empty($page['next']));
$has_option = array_key_exists('jump_buttons', $params['html']); if ($hasPrevNext && $config->getHTML()->showPreviousNextLinks()) {
if ($buttons && (($has_option && $params['html']['jump_buttons']) || !$has_option)) {
?> ?>
<nav> <nav>
<ul class="Pager"> <ul class="Pager">

View File

@ -4,31 +4,31 @@
<div class="Navbar NoPrint"> <div class="Navbar NoPrint">
<div class="Container"> <div class="Container">
<?php $this->insert('theme::partials/navbar_content', ['params' => $params]); ?> <?php $this->insert('theme::partials/navbar_content'); ?>
</div> </div>
</div> </div>
<div class="Homepage"> <div class="Homepage">
<div class="HomepageTitle Container"> <div class="HomepageTitle Container">
<?= ($params['tagline']) ? '<h2>' . $params['tagline'] . '</h2>' : '' ?> <?= ($config->hasTagline()) ? '<h2>' . $config->getTagline() . '</h2>' : '' ?>
</div> </div>
<div class="HomepageImage Container"> <div class="HomepageImage Container">
<?= ($params['image']) ? '<img class="homepage-image img-responsive" src="' . $params['image'] . '" alt="' . $params['title'] . '">' : '' ?> <?= ($config->hasImage()) ? '<img class="homepage-image img-responsive" src="' . $config->getImage() . '" alt="' . $config->getTitle() . '">' : '' ?>
</div> </div>
<div class="HomepageButtons"> <div class="HomepageButtons">
<div class="Container"> <div class="Container">
<?php <?php
if ($params['html']['repo']) { if ($config->getHTML()->hasRepository()) {
echo '<a href="https://github.com/' . $params['html']['repo'] . '" class="Button Button--secondary Button--hero">' . $this->translate("View_on_github") . '</a>'; echo '<a href="https://github.com/' . $config->getHTML()->getRepository() . '" class="Button Button--secondary Button--hero">' . $this->translate("View_on_github") . '</a>';
} }
$view_doc = $this->translate("View_documentation"); $view_doc = $this->translate("View_documentation");
foreach ($page['entry_page'] as $key => $node) { foreach ($page['entry_page'] as $key => $node) {
echo '<a href="' . $node . '" class="Button Button--primary Button--hero">' . str_replace("__VIEW_DOCUMENTATION__", $view_doc, $key) . '</a>'; echo '<a href="' . $node . '" class="Button Button--primary Button--hero">' . str_replace("__VIEW_DOCUMENTATION__", $view_doc, $key) . '</a>';
} }
if (isset($params['html']['buttons']) && is_array($params['html']['buttons'])) { if ($config->getHTML()->hasButtons()) {
foreach ($params['html']['buttons'] as $name => $link) { foreach ($config->getHTML()->getButtons() as $name => $link) {
echo '<a href="' . $link . '" class="Button Button--secondary Button--hero">' . $name . '</a>'; echo '<a href="' . $link . '" class="Button Button--secondary Button--hero">' . $name . '</a>';
} }
} }
@ -50,18 +50,18 @@
<div class="HomepageFooter"> <div class="HomepageFooter">
<div class="Container"> <div class="Container">
<div class="Container--inner"> <div class="Container--inner">
<?php if (!empty($params['html']['links'])) { ?> <?php if ($config->getHTML()->hasLinks()) { ?>
<ul class="HomepageFooter__links"> <ul class="HomepageFooter__links">
<?php foreach ($params['html']['links'] as $name => $url) { <?php foreach ($config->getHTML()->getLinks() as $name => $url) {
echo '<li><a href="' . $url . '" target="_blank">' . $name . '</a></li>'; echo '<li><a href="' . $url . '" target="_blank">' . $name . '</a></li>';
} ?> } ?>
</ul> </ul>
<?php } ?> <?php } ?>
<?php if (!empty($params['html']['twitter'])) { ?> <?php if ($config->getHTML()->hasTwitterHandles()) { ?>
<div class="HomepageFooter__twitter"> <div class="HomepageFooter__twitter">
<div class="Twitter"> <div class="Twitter">
<?php $this->insert('theme::partials/twitter_buttons', ['params' => $params]); ?> <?php $this->insert('theme::partials/twitter_buttons'); ?>
</div> </div>
</div> </div>
<?php } ?> <?php } ?>

View File

@ -1,26 +1,26 @@
<!DOCTYPE html> <!DOCTYPE html>
<html class="no-js" lang="<?=$params['language'] ?>"> <html class="no-js" lang="<?=$config->getLanguage() ?>">
<head> <head>
<title><?= $page['title']; ?> <?= ($page['title'] != $params['title']) ? '- ' . $params['title'] : "" ?></title> <title><?= $page['title']; ?> <?= ($page['title'] != $config->getTitle()) ? '- ' . $config->getTitle() : "" ?></title>
<?php //SEO meta tags... <?php //SEO meta tags...
if (array_key_exists('attributes', $page) && array_key_exists('description', $page['attributes'])) { if (array_key_exists('attributes', $page) && array_key_exists('description', $page['attributes'])) {
echo " <meta name=\"description\" content=\"{$page['attributes']['description']}\">\n"; echo " <meta name=\"description\" content=\"{$page['attributes']['description']}\">\n";
} elseif (array_key_exists('tagline', $params)) { } elseif ($config->hasTagline()) {
echo " <meta name=\"description\" content=\"{$params['tagline']}\">\n"; echo " <meta name=\"description\" content=\"{$config->getTagline()}\">\n";
} }
if (array_key_exists('attributes', $page) && array_key_exists('keywords', $page['attributes'])) { if (array_key_exists('attributes', $page) && array_key_exists('keywords', $page['attributes'])) {
echo " <meta name=\"keywords\" content=\"{$page['attributes']['keywords']}\">\n"; echo " <meta name=\"keywords\" content=\"{$page['attributes']['keywords']}\">\n";
} }
if (array_key_exists('attributes', $page) && array_key_exists('author', $page['attributes'])) { if (array_key_exists('attributes', $page) && array_key_exists('author', $page['attributes'])) {
echo " <meta name=\"author\" content=\"{$page['attributes']['author']}\">\n"; echo " <meta name=\"author\" content=\"{$page['attributes']['author']}\">\n";
} elseif (array_key_exists('author', $params)) { } elseif ($config->hasAuthor()) {
echo " <meta name=\"author\" content=\"{$params['author']}\">\n"; echo " <meta name=\"author\" content=\"{$config->getAuthor()}\">\n";
} }
?> ?>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="icon" href="<?= $params['theme']['favicon']; ?>" type="image/x-icon"> <link rel="icon" href="<?= $config->getTheme()->getFavicon(); ?>" type="image/x-icon">
<!-- Mobile --> <!-- Mobile -->
<meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-capable" content="yes" />
@ -33,16 +33,16 @@
</script> </script>
<!-- Font --> <!-- Font -->
<?php foreach ($params['theme']['fonts'] as $font) { <?php foreach ($config->getTheme()->getFonts() as $font) {
echo "<link href='$font' rel='stylesheet' type='text/css'>"; echo "<link href='$font' rel='stylesheet' type='text/css'>";
} ?> } ?>
<!-- CSS --> <!-- CSS -->
<?php foreach ($params['theme']['css'] as $css) { <?php foreach ($config->getTheme()->getCSS() as $css) {
echo "<link href='$css' rel='stylesheet' type='text/css'>"; echo "<link href='$css' rel='stylesheet' type='text/css'>";
} ?> } ?>
<?php if ($params['html']['search']) { ?> <?php if ($config->getHTML()->hasSearch()) { ?>
<!-- Search --> <!-- Search -->
<link href="<?= $base_url; ?>daux_libraries/search.css" rel="stylesheet"> <link href="<?= $base_url; ?>daux_libraries/search.css" rel="stylesheet">
<?php } ?> <?php } ?>
@ -51,16 +51,16 @@
<?= $this->section('content'); ?> <?= $this->section('content'); ?>
<?php <?php
if ($params['html']['google_analytics']) { if ($config->getHTML()->hasGoogleAnalytics()) {
$this->insert('theme::partials/google_analytics', ['analytics' => $params['html']['google_analytics'], 'host' => array_key_exists('host', $params) ? $params['host'] : '']); $this->insert('theme::partials/google_analytics', ['analytics' => $config->getHTML()->getGoogleAnalyticsId(), 'host' => $config->hasHost() ? $config->getHost() : '']);
} }
if ($params['html']['piwik_analytics']) { if ($config->getHTML()->hasPiwikAnalytics()) {
$this->insert('theme::partials/piwik_analytics', ['url' => $params['html']['piwik_analytics'], 'id' => $params['html']['piwik_analytics_id']]); $this->insert('theme::partials/piwik_analytics', ['url' => $config->getHTML()->getPiwikAnalyticsUrl(), 'id' => $config->getHTML()->getPiwikAnalyticsId()]);
} }
?> ?>
<!-- JS --> <!-- JS -->
<?php foreach ($params['theme']['js'] as $js) { <?php foreach ($config->getTheme()->getJS() as $js) {
echo '<script src="' . $js . '"></script>'; echo '<script src="' . $js . '"></script>';
} ?> } ?>

View File

@ -7,7 +7,7 @@
<span class="Collapsible__trigger__bar"></span> <span class="Collapsible__trigger__bar"></span>
</button> </button>
<?php $this->insert('theme::partials/navbar_content', ['params' => $params]); ?> <?php $this->insert('theme::partials/navbar_content'); ?>
<div class="Collapsible__content" id="sidebar_content"> <div class="Collapsible__content" id="sidebar_content">
<!-- Navigation --> <!-- Navigation -->
@ -20,21 +20,20 @@
$path = $page['language']; $path = $page['language'];
} }
echo $this->get_navigation($rendertree, $path, isset($params['request']) ? $params['request'] : '', $base_page, $params['mode']); echo $this->get_navigation($rendertree, $path, $config->hasRequest() ? $config->getRequest() : '', $base_page, $config->getMode());
?> ?>
<div class="Links"> <div class="Links">
<?php if (!empty($params['html']['links'])) { ?> <?php if ($config->getHTML()->hasLinks()) { ?>
<hr/> <hr/>
<?php foreach ($params['html']['links'] as $name => $url) { ?> <?php foreach ($config->getHTML()->getLinks() as $name => $url) { ?>
<a href="<?= $url ?>" target="_blank"><?= $name ?></a> <a href="<?= $url ?>" target="_blank"><?= $name ?></a>
<br /> <br />
<?php } ?> <?php } ?>
<?php } ?> <?php } ?>
</div> </div>
<?php if ($params['html']['toggle_code']) { ?> <?php if ($config->getHTML()->showCodeToggle()) { ?>
<div class="CodeToggler"> <div class="CodeToggler">
<hr/> <hr/>
<label class="Checkbox"><?=$this->translate("CodeBlocks_show") ?> <label class="Checkbox"><?=$this->translate("CodeBlocks_show") ?>
@ -44,17 +43,17 @@
</div> </div>
<?php } ?> <?php } ?>
<?php if (!empty($params['html']['twitter'])) { ?> <?php if ($config->getHTML()->hasTwitterHandles()) { ?>
<div class="Twitter"> <div class="Twitter">
<hr/> <hr/>
<?php $this->insert('theme::partials/twitter_buttons', ['params' => $params]); ?> <?php $this->insert('theme::partials/twitter_buttons'); ?>
</div> </div>
<?php } ?> <?php } ?>
<?php if (!empty($params['html']['powered_by'])) { ?> <?php if ($config->getHTML()->hasPoweredBy()) { ?>
<div class="PoweredBy"> <div class="PoweredBy">
<hr/> <hr/>
<?= $params['html']['powered_by'] ?> <?= $config->getHTML()->getPoweredBy()?>
</div> </div>
<?php } ?> <?php } ?>
</div> </div>

View File

@ -1,6 +1,11 @@
<a class="Brand" href="<?= $params['base_page'] . $params['index']->getUri(); ?>"><?= $params['title']; ?></a> <?php
if (!isset($config)) {
$config = $params;
}
?>
<a class="Brand" href="<?= $config->getBasePage() . $config->getIndex()->getUri(); ?>"><?= $config->getTitle(); ?></a>
<?php if ($params['html']['search']) { ?> <?php if ($config->getHTML()->hasSearch()) { ?>
<div class="Search"> <div class="Search">
<svg class="Search__icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 451 451"> <svg class="Search__icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 451 451">
<path d="M447.05 428l-109.6-109.6c29.4-33.8 47.2-77.9 47.2-126.1C384.65 86.2 298.35 0 192.35 0 86.25 0 .05 86.3.05 192.3s86.3 192.3 192.3 192.3c48.2 0 92.3-17.8 126.1-47.2L428.05 447c2.6 2.6 6.1 4 9.5 4s6.9-1.3 9.5-4c5.2-5.2 5.2-13.8 0-19zM26.95 192.3c0-91.2 74.2-165.3 165.3-165.3 91.2 0 165.3 74.2 165.3 165.3s-74.1 165.4-165.3 165.4c-91.1 0-165.3-74.2-165.3-165.4z"/> <path d="M447.05 428l-109.6-109.6c29.4-33.8 47.2-77.9 47.2-126.1C384.65 86.2 298.35 0 192.35 0 86.25 0 .05 86.3.05 192.3s86.3 192.3 192.3 192.3c48.2 0 92.3-17.8 126.1-47.2L428.05 447c2.6 2.6 6.1 4 9.5 4s6.9-1.3 9.5-4c5.2-5.2 5.2-13.8 0-19zM26.95 192.3c0-91.2 74.2-165.3 165.3-165.3 91.2 0 165.3 74.2 165.3 165.3s-74.1 165.4-165.3 165.4c-91.1 0-165.3-74.2-165.3-165.4z"/>

View File

@ -1,4 +1,9 @@
<?php if ($params['html']['search']) { ?> <?php
if (!isset($config)) {
$config = $params;
}
?>
<?php if ($config->getHTML()->hasSearch()) { ?>
<script> <script>
<?php <?php
$search_strings = [ $search_strings = [

View File

@ -1,4 +1,9 @@
<?php foreach ($params['html']['twitter'] as $handle) { ?> <?php
if (!isset($config)) {
$config = $params;
}
?>
<?php foreach ($config->getHTML()->getTwitterHandles() as $handle) { ?>
<a class="Twitter__button" target="_blank" title="Follow @<?= $handle; ?> on Twitter" href="https://twitter.com/intent/follow?screen_name=<?= $handle; ?>"> <a class="Twitter__button" target="_blank" title="Follow @<?= $handle; ?> on Twitter" href="https://twitter.com/intent/follow?screen_name=<?= $handle; ?>">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72"><path fill="none" d="M0 0h72v72H0z"/><path class="icon" fill="#fff" d="M68.812 15.14c-2.348 1.04-4.87 1.744-7.52 2.06 2.704-1.62 4.78-4.186 5.757-7.243-2.53 1.5-5.33 2.592-8.314 3.176C56.35 10.59 52.948 9 49.182 9c-7.23 0-13.092 5.86-13.092 13.093 0 1.026.118 2.02.338 2.98C25.543 24.527 15.9 19.318 9.44 11.396c-1.125 1.936-1.77 4.184-1.77 6.58 0 4.543 2.312 8.552 5.824 10.9-2.146-.07-4.165-.658-5.93-1.64-.002.056-.002.11-.002.163 0 6.345 4.513 11.638 10.504 12.84-1.1.298-2.256.457-3.45.457-.845 0-1.666-.078-2.464-.23 1.667 5.2 6.5 8.985 12.23 9.09-4.482 3.51-10.13 5.605-16.26 5.605-1.055 0-2.096-.06-3.122-.184 5.794 3.717 12.676 5.882 20.067 5.882 24.083 0 37.25-19.95 37.25-37.25 0-.565-.013-1.133-.038-1.693 2.558-1.847 4.778-4.15 6.532-6.774z"/></svg> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72"><path fill="none" d="M0 0h72v72H0z"/><path class="icon" fill="#fff" d="M68.812 15.14c-2.348 1.04-4.87 1.744-7.52 2.06 2.704-1.62 4.78-4.186 5.757-7.243-2.53 1.5-5.33 2.592-8.314 3.176C56.35 10.59 52.948 9 49.182 9c-7.23 0-13.092 5.86-13.092 13.093 0 1.026.118 2.02.338 2.98C25.543 24.527 15.9 19.318 9.44 11.396c-1.125 1.936-1.77 4.184-1.77 6.58 0 4.543 2.312 8.552 5.824 10.9-2.146-.07-4.165-.658-5.93-1.64-.002.056-.002.11-.002.163 0 6.345 4.513 11.638 10.504 12.84-1.1.298-2.256.457-3.45.457-.845 0-1.666-.078-2.464-.23 1.667 5.2 6.5 8.985 12.23 9.09-4.482 3.51-10.13 5.605-16.26 5.605-1.055 0-2.096-.06-3.122-.184 5.794 3.717 12.676 5.882 20.067 5.882 24.083 0 37.25-19.95 37.25-37.25 0-.565-.013-1.133-.038-1.693 2.558-1.847 4.778-4.15 6.532-6.774z"/></svg>
<span class="Twitter__button__label">Follow @<?= $handle; ?></span> <span class="Twitter__button__label">Follow @<?= $handle; ?></span>

View File

@ -3,6 +3,7 @@ namespace Todaymade\Daux\ContentTypes\Markdown;
use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStream;
use Todaymade\Daux\Config; use Todaymade\Daux\Config;
use Todaymade\Daux\ConfigBuilder;
use Todaymade\Daux\Daux; use Todaymade\Daux\Daux;
use Todaymade\Daux\DauxHelper; use Todaymade\Daux\DauxHelper;
use Todaymade\Daux\Tree\Builder; use Todaymade\Daux\Tree\Builder;
@ -13,27 +14,7 @@ class LinkRendererTest extends TestCase
{ {
protected function getTree(Config $config) protected function getTree(Config $config)
{ {
$structure = [
'Content' => [
'Page.md' => 'some text content',
],
'Widgets' => [
'Page.md' => 'another page',
'Button.md' => 'another page',
'Page_with_#_hash.md' => 'page with hash',
],
];
$root = vfsStream::setup('root', null, $structure);
$config->setDocumentationDirectory($root->url());
$config['valid_content_extensions'] = ['md'];
$config['mode'] = Daux::STATIC_MODE;
$config['index_key'] = 'index.html';
$tree = new Root($config);
Builder::build($tree, []);
return $tree;
} }
public function providerRenderLink() public function providerRenderLink()
@ -70,11 +51,33 @@ class LinkRendererTest extends TestCase
*/ */
public function testRenderLink($expected, $string, $current) public function testRenderLink($expected, $string, $current)
{ {
$config = new Config(); $structure = [
$config['base_url'] = ''; 'Content' => [
'Page.md' => 'some text content',
],
'Widgets' => [
'Page.md' => 'another page',
'Button.md' => 'another page',
'Page_with_#_hash.md' => 'page with hash',
],
];
$root = vfsStream::setup('root', null, $structure);
$config['tree'] = $this->getTree($config); $config = ConfigBuilder::withMode()
$config->setCurrentPage(DauxHelper::getFile($config['tree'], $current)); ->withDocumentationDirectory($root->url())
->withValidContentExtensions(['md'])
->with([
'base_url' => ''
])
->build();
$tree = new Root($config);
Builder::build($tree, []);
$config = ConfigBuilder::withMode()->build();
$config->setTree($tree);
$config->setCurrentPage(DauxHelper::getFile($config->getTree(), $current));
$converter = new CommonMarkConverter(['daux' => $config]); $converter = new CommonMarkConverter(['daux' => $config]);

View File

@ -1,7 +1,7 @@
<?php <?php namespace Todaymade\Daux;
namespace Todaymade\Daux;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Todaymade\Daux\ConfigBuilder;
class DauxHelperTest extends TestCase class DauxHelperTest extends TestCase
{ {
@ -20,8 +20,9 @@ class DauxHelperTest extends TestCase
*/ */
public function testGetFilenames($expected, $node) public function testGetFilenames($expected, $node)
{ {
$config = new Config(); $config = ConfigBuilder::withMode()
$config['valid_content_extensions'] = ['md']; ->withValidContentExtensions(['md'])
->build();
$this->assertEquals($expected, DauxHelper::getFilenames($config, $node)); $this->assertEquals($expected, DauxHelper::getFilenames($config, $node));
} }

View File

@ -3,6 +3,7 @@ namespace Todaymade\Daux\Format\Template;
use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStream;
use Todaymade\Daux\Config; use Todaymade\Daux\Config;
use Todaymade\Daux\ConfigBuilder;
use Todaymade\Daux\Daux; use Todaymade\Daux\Daux;
use Todaymade\Daux\DauxHelper; use Todaymade\Daux\DauxHelper;
use Todaymade\Daux\Format\HTML\Template; use Todaymade\Daux\Format\HTML\Template;
@ -30,10 +31,11 @@ class TranslateTest extends TestCase
]; ];
$root = vfsStream::setup('root', null, $structure); $root = vfsStream::setup('root', null, $structure);
$config->setDocumentationDirectory($root->url()); $config = ConfigBuilder::withMode()
$config['valid_content_extensions'] = ['md']; ->withDocumentationDirectory($root->url())
$config['mode'] = Daux::STATIC_MODE; ->withValidContentExtensions(['md'])
$config['index_key'] = 'index.html'; ->build();
$tree = new Root($config); $tree = new Root($config);
Builder::build($tree, []); Builder::build($tree, []);
@ -61,35 +63,36 @@ class TranslateTest extends TestCase
$entry = $this->prophesize(Entry::class); $entry = $this->prophesize(Entry::class);
$config = new Config(); $config = new Config();
$config['tree'] = $this->getTree($config); $config->setTree($this->getTree($config));
$config['title'] = ''; $config->merge([
$config['index'] = $entry->reveal(); 'title' => '',
$config['language'] = $language; 'index' => $entry->reveal(),
$config['base_url'] = ''; 'language' => $language,
$config['base_page'] = ''; 'base_url' => '',
$config['templates'] = ''; 'templates' => '',
$config['page']['language'] = $language; 'page' => [
'language' => $language,
],
'html' => [
'search' => '',
'toggle_code' => false,
'piwik_analytics' => '',
'google_analytics' => '',
],
'theme' => [
'js' => [''],
'css' => [''],
'fonts' => [''],
'favicon' => '',
'templates' => 'name',
],
'strings' => [
'en' => ['Link_previous' => 'Previous',],
'it' => ['Link_previous' => 'Pagina precedente',],
]
]);
$config['html'] = [ $config->setCurrentPage(DauxHelper::getFile($config->getTree(), $current));
'search' => '',
'toggle_code' => false,
'piwik_analytics' => '',
'google_analytics' => '',
];
$config['theme'] = [
'js' => [''],
'css' => [''],
'fonts' => [''],
'favicon' => '',
'templates' => 'name',
];
$config['strings'] = [
'en' => ['Link_previous' => 'Previous',],
'it' => ['Link_previous' => 'Pagina precedente',],
];
$config->setCurrentPage(DauxHelper::getFile($config['tree'], $current));
$template = new Template($config); $template = new Template($config);
$value = $template->getEngine($config)->getFunction('translate')->call(null, ['Link_previous']); $value = $template->getEngine($config)->getFunction('translate')->call(null, ['Link_previous']);

View File

@ -5,6 +5,7 @@ use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Todaymade\Daux\Format\HTML\RawPage; use Todaymade\Daux\Format\HTML\RawPage;
use Todaymade\Daux\Config; use Todaymade\Daux\Config;
use Todaymade\Daux\ConfigBuilder;
use Todaymade\Daux\Daux; use Todaymade\Daux\Daux;
use Todaymade\Daux\Server\Server; use Todaymade\Daux\Server\Server;
use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStream;
@ -21,11 +22,13 @@ class ServerTest extends TestCase
]; ];
$root = vfsStream::setup('root', null, $structure); $root = vfsStream::setup('root', null, $structure);
$daux = new Daux(Daux::LIVE_MODE, new NullOutput());
$daux->getParams()->setDocumentationDirectory($root->url());
$daux->initializeConfiguration(); $config = ConfigBuilder::withMode(Daux::LIVE_MODE)
$daux->getParams()['index_key'] = 'index'; ->withDocumentationDirectory($root->url())
->build();
$daux = new Daux($config, new NullOutput());
$daux->generateTree(); $daux->generateTree();
$page = new RawPage($daux->tree['somefile.css']->getPath()); $page = new RawPage($daux->tree['somefile.css']->getPath());

View File

@ -3,7 +3,7 @@ namespace Todaymade\Daux\Tree;
use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory; use org\bovigo\vfs\vfsStreamDirectory;
use Todaymade\Daux\Config; use Todaymade\Daux\ConfigBuilder;
use Todaymade\Daux\Daux; use Todaymade\Daux\Daux;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
@ -30,11 +30,10 @@ class BuilderIntegrationTest extends TestCase
public function testCreateHierarchy() public function testCreateHierarchy()
{ {
$config = new Config(); $config = ConfigBuilder::withMode()
$config->setDocumentationDirectory($this->root->url()); ->withDocumentationDirectory($this->root->url())
$config['valid_content_extensions'] = ['md']; ->withValidContentExtensions(['md'])
$config['mode'] = Daux::STATIC_MODE; ->build();
$config['index_key'] = 'index.html';
$tree = new Root($config); $tree = new Root($config);
Builder::build($tree, []); Builder::build($tree, []);

View File

@ -3,6 +3,7 @@ namespace Todaymade\Daux\Tree;
use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStream;
use Todaymade\Daux\Config; use Todaymade\Daux\Config;
use Todaymade\Daux\ConfigBuilder;
use Todaymade\Daux\Daux; use Todaymade\Daux\Daux;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
@ -44,8 +45,7 @@ class BuilderTest extends TestCase
public function testGetOrCreateDirNew() public function testGetOrCreateDirNew()
{ {
$config = new Config; $config = ConfigBuilder::withMode()->build();
$config->setDocumentationDirectory('');
$root = new Root($config); $root = new Root($config);
$dir = Builder::getOrCreateDir($root, 'directory'); $dir = Builder::getOrCreateDir($root, 'directory');
@ -57,8 +57,7 @@ class BuilderTest extends TestCase
public function testGetOrCreateDirExisting() public function testGetOrCreateDirExisting()
{ {
$config = new Config; $config = ConfigBuilder::withMode()->build();
$config->setDocumentationDirectory('');
$root = new Root($config); $root = new Root($config);
$directory = new Directory($root, 'directory'); $directory = new Directory($root, 'directory');
$directory->setTitle('directory'); $directory->setTitle('directory');
@ -73,11 +72,9 @@ class BuilderTest extends TestCase
public function getStaticRoot() public function getStaticRoot()
{ {
$config = new Config(); $config = ConfigBuilder::withMode()
$config->setDocumentationDirectory(''); ->withValidContentExtensions(['md'])
$config['mode'] = Daux::STATIC_MODE; ->build();
$config['index_key'] = 'index.html';
$config['valid_content_extensions'] = ['md'];
return new Root($config); return new Root($config);
} }
@ -168,11 +165,10 @@ class BuilderTest extends TestCase
]; ];
$root = vfsStream::setup('root', null, $structure); $root = vfsStream::setup('root', null, $structure);
$config = new Config; $config = ConfigBuilder::withMode()
$config->setDocumentationDirectory($root->url()); ->withDocumentationDirectory($root->url())
$config['valid_content_extensions'] = ['md']; ->withValidContentExtensions(['md'])
$config['mode'] = Daux::STATIC_MODE; ->build();
$config['index_key'] = 'index.html';
$tree = new Root($config); $tree = new Root($config);
Builder::build($tree, []); Builder::build($tree, []);
@ -194,11 +190,10 @@ class BuilderTest extends TestCase
]; ];
$root = vfsStream::setup('root', null, $structure); $root = vfsStream::setup('root', null, $structure);
$config = new Config; $config = ConfigBuilder::withMode()
$config->setDocumentationDirectory($root->url()); ->withDocumentationDirectory($root->url())
$config['valid_content_extensions'] = ['md']; ->withValidContentExtensions(['md'])
$config['mode'] = Daux::STATIC_MODE; ->build();
$config['index_key'] = 'index.html';
$tree = new Root($config); $tree = new Root($config);
Builder::build($tree, []); Builder::build($tree, []);

View File

@ -1,15 +1,14 @@
<?php <?php
namespace Todaymade\Daux\Tree; namespace Todaymade\Daux\Tree;
use Todaymade\Daux\Config; use Todaymade\Daux\ConfigBuilder;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class ContentTest extends TestCase class ContentTest extends TestCase
{ {
protected function createContent($content) protected function createContent($content)
{ {
$config = new Config; $config = ConfigBuilder::withMode()->build();
$config->setDocumentationDirectory('');
$dir = new Directory(new Root($config), ''); $dir = new Directory(new Root($config), '');
$obj = new Content($dir, ''); $obj = new Content($dir, '');

View File

@ -1,7 +1,8 @@
<?php <?php
namespace Todaymade\Daux\Tree; namespace Todaymade\Daux\Tree;
use Todaymade\Daux\Config; use Todaymade\Daux\Daux;
use Todaymade\Daux\ConfigBuilder;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class DirectoryTest extends TestCase class DirectoryTest extends TestCase
@ -32,8 +33,8 @@ class DirectoryTest extends TestCase
{ {
shuffle($list); shuffle($list);
$config = new Config; $config = ConfigBuilder::withMode()
$config->setDocumentationDirectory(''); ->build();
$directory = new Directory(new Root($config), 'dir'); $directory = new Directory(new Root($config), 'dir');