/**
  * Set-up default vars
  */
 public static function init()
 {
     // make sure config vars exist
     if (!Config::getOption("patternExtension")) {
         Console::writeError("the pattern extension config option needs to be set...");
     }
     if (!Config::getOption("styleguideKit")) {
         Console::writeError("the styleguideKit config option needs to be set...");
     }
     // set-up config vars
     $patternExtension = Config::getOption("patternExtension");
     $pluginDir = Config::getOption("packagesDir");
     $sourceDir = Config::getOption("sourceDir");
     $styleguideKit = Config::getOption("styleguideKit");
     // load pattern-lab's resources
     $partialPath = $pluginDir . "/" . $styleguideKit . "/views/partials";
     self::$htmlHead = file_get_contents($partialPath . "/general-header." . $patternExtension);
     self::$htmlFoot = file_get_contents($partialPath . "/general-footer." . $patternExtension);
     // gather the user-defined header and footer information
     $patternHeadPath = $sourceDir . "/_meta/_00-head." . $patternExtension;
     $patternFootPath = $sourceDir . "/_meta/_01-foot." . $patternExtension;
     self::$patternHead = file_exists($patternHeadPath) ? file_get_contents($patternHeadPath) : "";
     self::$patternFoot = file_exists($patternFootPath) ? file_get_contents($patternFootPath) : "";
     // add the filesystemLoader
     $patternEngineBasePath = PatternEngine::getInstance()->getBasePath();
     $filesystemLoaderClass = $patternEngineBasePath . "\\Loaders\\FilesystemLoader";
     $options = array();
     $options["templatePath"] = $pluginDir . "/" . $styleguideKit . "/views";
     $options["partialsPath"] = $pluginDir . "/" . $styleguideKit . "/views/partials";
     self::$filesystemLoader = new $filesystemLoaderClass($options);
     $stringLoaderClass = $patternEngineBasePath . "\\Loaders\\StringLoader";
     self::$stringLoader = new $stringLoaderClass();
     // i can't remember why i chose to implement the pattern loader directly in classes
     // i figure i had a good reason which is why it's not showing up here
 }
Example #2
0
 /**
  * Write out the time tracking file so the content sync service will work. A holdover
  * from how I put together the original AJAX polling set-up.
  */
 public static function updateChangeTime()
 {
     if (is_dir(Config::getOption("publicDir"))) {
         file_put_contents(Config::getOption("publicDir") . "/latest-change.txt", time());
     } else {
         Console::writeError("the public directory for Pattern Lab doesn't exist...");
     }
 }
 /**
  * Moves static files that aren't directly related to Pattern Lab
  * @param  {String}       file name to be moved
  * @param  {String}       copy for the message to be printed out
  * @param  {String}       part of the file name to be found for replacement
  * @param  {String}       the replacement
  */
 public static function moveStaticFile($fileName, $copy = "", $find = "", $replace = "")
 {
     self::moveFile($fileName, str_replace($find, $replace, $fileName));
     Util::updateChangeTime();
     if ($copy != "") {
         Console::writeInfo($fileName . " " . $copy . "...");
     }
 }
 public function run()
 {
     if (Console::findCommandOption("list")) {
         // get all of the options
         $options = Config::getOptions();
         // sort 'em alphabetically
         ksort($options);
         // find length of longest option
         $lengthLong = 0;
         foreach ($options as $optionName => $optionValue) {
             $lengthLong = strlen($optionName) > $lengthLong ? strlen($optionName) : $lengthLong;
         }
         // iterate over each option and spit it out
         foreach ($options as $optionName => $optionValue) {
             $optionValue = is_array($optionValue) ? implode(", ", $optionValue) : $optionValue;
             $optionValue = !$optionValue ? "false" : $optionValue;
             $spacer = Console::getSpacer($lengthLong, strlen($optionName));
             Console::writeLine("<info>" . $optionName . ":</info>" . $spacer . $optionValue);
         }
     } else {
         if (Console::findCommandOption("get")) {
             // figure out which optino was passed
             $searchOption = Console::findCommandOptionValue("get");
             $optionValue = Config::getOption($searchOption);
             // write it out
             if (!$optionValue) {
                 Console::writeError("the --get value you provided, <info>" . $searchOption . "</info>, does not exists in the config...");
             } else {
                 $optionValue = is_array($optionValue) ? implode(", ", $optionValue) : $optionValue;
                 $optionValue = !$optionValue ? "false" : $optionValue;
                 Console::writeInfo($searchOption . ": <ok>" . $optionValue . "</ok>");
             }
         } else {
             if (Console::findCommandOption("set")) {
                 // find the value that was passed
                 $updateOption = Console::findCommandOptionValue("set");
                 $updateOptionBits = explode("=", $updateOption);
                 if (count($updateOptionBits) == 1) {
                     Console::writeError("the --set value should look like <info>optionName=\"optionValue\"</info>. nothing was updated...");
                 }
                 // set the name and value that were passed
                 $updateName = $updateOptionBits[0];
                 $updateValue = $updateOptionBits[1][0] == "\"" || $updateOptionBits[1][0] == "'" ? substr($updateOptionBits[1], 1, strlen($updateOptionBits[1]) - 1) : $updateOptionBits[1];
                 // make sure the option being updated already exists
                 $currentValue = Config::getOption($updateName);
                 if (!$currentValue) {
                     Console::writeError("the --set option you provided, <info>" . $updateName . "</info>, does not exists in the config. nothing will be updated...");
                 } else {
                     Config::updateConfigOption($updateName, $updateValue);
                 }
             } else {
                 // no acceptable options were passed so write out the help
                 Console::writeHelpCommand($this->command);
             }
         }
     }
 }
 public function testGenerate()
 {
     Console::init();
     Config::init(__DIR__ . "/../../../../../..");
     Dispatcher::init();
     $generator = new Generator();
     $generator->generate(['foo' => 'baz']);
     echo '';
 }
Example #6
0
 /**
  * Returns the last error message when building a JSON file. Mimics json_last_error_msg() from PHP 5.5
  * @param  {String}       the file that generated the error
  */
 public static function lastErrorMsg($file, $message, $data)
 {
     Console::writeLine(PHP_EOL . "<error>The JSON file, " . $file . ", wasn't loaded. The error: " . $message . "</error>");
     if ($message == "Syntax error, malformed JSON") {
         Console::writeLine("");
         $parser = new JsonLint\JsonParser();
         $error = $parser->lint($data);
         Console::writeError($error->getMessage(), false, true);
     }
 }
 public function run()
 {
     // set-up required vars
     $options = array();
     $options["moveStatic"] = Console::findCommandOption("p|patternsonly") ? false : true;
     $options["noCacheBuster"] = Console::findCommandOption("n|nocache");
     $g = new Generator();
     $g->generate($options);
     $g->printSaying();
 }
 /**
  * Gather data from annotations.js and *.md files found in source/_annotations
  *
  * @return {Array}        populates Annotations::$store
  */
 public static function gather()
 {
     // set-up default var
     $annotationsDir = Config::getOption("annotationsDir");
     // set-up the dispatcher
     $dispatcherInstance = Dispatcher::getInstance();
     // dispatch that the data gather has started
     $dispatcherInstance->dispatch("annotations.gatherStart");
     // set-up the comments store
     self::$store["comments"] = array();
     // create the annotations dir if it doesn't exist
     if (!is_dir($annotationsDir)) {
         mkdir($annotationsDir);
     }
     // find the markdown-based annotations
     $finder = new Finder();
     $finder->files()->name("*.md")->in($annotationsDir);
     $finder->sortByName();
     foreach ($finder as $name => $file) {
         $data = array();
         $data[0] = array();
         $text = file_get_contents($file->getPathname());
         $matches = strpos($text, PHP_EOL . "~*~" . PHP_EOL) !== false ? explode(PHP_EOL . "~*~" . PHP_EOL, $text) : array($text);
         foreach ($matches as $match) {
             list($yaml, $markdown) = Documentation::parse($match);
             if (isset($yaml["el"]) || isset($yaml["selector"])) {
                 $data[0]["el"] = isset($yaml["el"]) ? $yaml["el"] : $yaml["selector"];
             } else {
                 $data[0]["el"] = "#someimpossibleselector";
             }
             $data[0]["title"] = isset($yaml["title"]) ? $yaml["title"] : "";
             $data[0]["comment"] = $markdown;
             self::$store["comments"] = array_merge(self::$store["comments"], $data);
         }
     }
     // read in the old style annotations.js, modify the data and generate JSON array to merge
     $data = array();
     $oldStyleAnnotationsPath = $annotationsDir . DIRECTORY_SEPARATOR . "annotations.js";
     if (file_exists($oldStyleAnnotationsPath)) {
         $text = trim(file_get_contents($oldStyleAnnotationsPath));
         $text = str_replace("var comments = ", "", $text);
         if ($text[strlen($text) - 1] == ";") {
             $text = rtrim($text, ";");
         }
         $data = json_decode($text, true);
         if ($jsonErrorMessage = JSON::hasError()) {
             JSON::lastErrorMsg(Console::getHumanReadablePath($oldStyleAnnotationsPath), $jsonErrorMessage, $data);
         }
     }
     // merge in any data from the old file if the json decode was successful
     if (is_array($data) && isset($data["comments"])) {
         self::$store["comments"] = array_merge(self::$store["comments"], $data["comments"]);
     }
     $dispatcherInstance->dispatch("annotations.gatherEnd");
 }
 public function build()
 {
     $command = $this->pathPHP . " " . $this->pathConsole . " --" . $this->command;
     if (Console::findCommandOption("p|patternsonly")) {
         $command .= " --patternsonly";
     }
     if (Console::findCommandOption("n|nocache")) {
         $command .= " --nocache";
     }
     return $command;
 }
Example #10
0
 /**
  * Randomly prints a saying after the generate is complete
  */
 public function say()
 {
     // set a color
     $colors = array("ok", "options", "info", "warning");
     $randomNumber = rand(0, count($colors) - 1);
     $color = isset($colors[$randomNumber]) ? $colors[$randomNumber] : "desc";
     // set a 1 in 3 chance that a saying is printed
     $randomNumber = rand(0, (count($this->sayings) - 1) * 3);
     if (isset($this->sayings[$randomNumber])) {
         Console::writeLine("<" . $color . ">" . $this->sayings[$randomNumber] . "...</" . $color . ">");
     }
 }
 public function run()
 {
     // set-up required vars
     $options = array();
     $options["exportFiles"] = true;
     $options["exportClean"] = Console::findCommandOption("clean");
     $options["moveStatic"] = false;
     FileUtil::cleanExport();
     $g = new Generator();
     $g->generate($options);
     FileUtil::exportStatic();
 }
 public function run()
 {
     if (version_compare(phpversion(), '5.4.0', '<')) {
         Console::writeWarning("you must have PHP 5.4.0 or greater to use this feature. you are using PHP " . phpversion() . "...");
     } else {
         // set-up defaults
         $publicDir = Config::getOption("publicDir");
         $coreDir = Config::getOption("coreDir");
         // start-up the server with the router
         Console::writeInfo("server started on localhost:8080. use ctrl+c to exit...");
         passthru("cd " . $publicDir . " && " . $_SERVER["_"] . " -S localhost:8080 " . $coreDir . "/server/router.php");
     }
 }
 public function run()
 {
     if ($helpCommand = Console::findCommandValue("h|help")) {
         $helpCommand = str_replace("-", "", $helpCommand);
         if ($commandFound = Console::findCommandLong($helpCommand)) {
             Console::writeHelpCommand($commandFound);
         } else {
             Console::writeHelp();
         }
     } else {
         Console::writeHelp();
     }
 }
 public function build()
 {
     $command = $this->pathPHP . " " . $this->pathConsole . " --" . $this->command;
     $host = Console::findCommandOptionValue("host");
     $port = Console::findCommandOptionValue("port");
     if ($host) {
         $command .= " --host " . $host;
     }
     if ($port) {
         $command .= " --port " . $port;
     }
     return $command;
 }
 /**
  * Gather data from annotations.js and *.md files found in source/_annotations
  *
  * @return {Array}        populates Annotations::$store
  */
 public static function gather()
 {
     // set-up default var
     $sourceDir = Config::getOption("sourceDir");
     // set-up the dispatcher
     $dispatcherInstance = Dispatcher::getInstance();
     // dispatch that the data gather has started
     $dispatcherInstance->dispatch("annotations.gatherStart");
     // set-up the comments store
     self::$store["comments"] = array();
     // iterate over all of the files in the annotations dir
     if (!is_dir($sourceDir . "/_annotations")) {
         Console::writeWarning("<path>_annotations/</path><warning> doesn't exist so you won't have annotations...");
         mkdir($sourceDir . "/_annotations");
     }
     // find the markdown-based annotations
     $finder = new Finder();
     $finder->files()->name("*.md")->in($sourceDir . "/_annotations");
     $finder->sortByName();
     foreach ($finder as $name => $file) {
         $data = array();
         $data[0] = array();
         $text = file_get_contents($file->getPathname());
         $matches = strpos($text, PHP_EOL . "~*~" . PHP_EOL) !== false ? explode(PHP_EOL . "~*~" . PHP_EOL, $text) : array($text);
         foreach ($matches as $match) {
             list($yaml, $markdown) = Documentation::parse($match);
             if (isset($yaml["el"]) || isset($yaml["selector"])) {
                 $data[0]["el"] = isset($yaml["el"]) ? $yaml["el"] : $yaml["selector"];
             } else {
                 $data[0]["el"] = "#someimpossibleselector";
             }
             $data[0]["title"] = isset($yaml["title"]) ? $yaml["title"] : "";
             $data[0]["comment"] = $markdown;
             self::$store["comments"] = array_merge(self::$store["comments"], $data);
         }
     }
     // read in the old style annotations.js, modify the data and generate JSON array to merge
     if (file_exists($sourceDir . "/_annotations/annotations.js")) {
         $text = file_get_contents($sourceDir . "/_annotations/annotations.js");
         $text = str_replace("var comments = ", "", $text);
         $text = rtrim($text, ";");
         $data = json_decode($text, true);
         if ($jsonErrorMessage = JSON::hasError()) {
             JSON::lastErrorMsg("_annotations/annotations.js", $jsonErrorMessage, $data);
         }
     }
     // merge in any data from the old file
     self::$store["comments"] = array_merge(self::$store["comments"], $data["comments"]);
     $dispatcherInstance->dispatch("annotations.gatherEnd");
 }
 /**
  * Spawn the passed commands and those collected from plugins
  * @param  {Array}       a list of commands to spawn
  * @param  {Boolean}     if this should be run in quiet mode
  */
 public function spawn($commands = array(), $quiet = false)
 {
     // set-up a default
     $processes = array();
     // add the default processes sent to the spawner
     if (!empty($commands)) {
         foreach ($commands as $command) {
             $processes[] = $this->buildProcess($command);
         }
     }
     // add the processes sent to the spawner from plugins
     foreach ($this->pluginProcesses as $pluginProcess) {
         $processes[] = $this->buildProcess($pluginProcess);
     }
     // if there are processes to spawn do so
     if (!empty($processes)) {
         // start the processes
         foreach ($processes as $process) {
             $process["process"]->start();
         }
         // check on them and produce output
         while (true) {
             foreach ($processes as $process) {
                 try {
                     if ($process["process"]->isRunning()) {
                         $process["process"]->checkTimeout();
                         if (!$quiet && $process["output"]) {
                             print $process["process"]->getIncrementalOutput();
                             $cmd = $process["process"]->getCommandLine();
                             if (strpos($cmd, "router.php") != strlen($cmd) - 10) {
                                 print $process["process"]->getIncrementalErrorOutput();
                             }
                         }
                     }
                 } catch (ProcessTimedOutException $e) {
                     if ($e->isGeneralTimeout()) {
                         Console::writeError("pattern lab processes should never time out. yours did...");
                     } else {
                         if ($e->isIdleTimeout()) {
                             Console::writeError("pattern lab processes automatically time out if their is no command line output in 30 minutes...");
                         }
                     }
                 }
             }
             usleep(100000);
         }
     }
 }
 /**
  * Load all of the rules related to Pattern Engines. They're located in the plugin dir
  */
 public static function loadRules()
 {
     // default var
     $configDir = Config::getOption("configDir");
     // make sure the pattern engine data exists
     if (file_exists($configDir . "/patternengines.json")) {
         // get pattern engine list data
         $patternEngineList = json_decode(file_get_contents($configDir . "/patternengines.json"), true);
         // get the pattern engine info
         foreach ($patternEngineList["patternengines"] as $patternEngineName) {
             self::$rules[] = new $patternEngineName();
         }
     } else {
         Console::writeError("The pattern engines list isn't available in <path>" . $configDir . "</path>...");
     }
 }
 public function run()
 {
     // find the value given to the command
     $init = Console::findCommandOption("i|init");
     $starterkit = Console::findCommandOptionValue("f|install");
     if ($init) {
         $patternEngine = Config::getOption("patternExtension");
         $starterkit = "pattern-lab/starterkit-" . $patternEngine . "-base";
     }
     if ($starterkit) {
         // download the starterkit
         $f = new Fetch();
         $f->fetchStarterKit($starterkit);
     } else {
         Console::writeHelpCommand($this->command);
     }
 }
 /**
  * Load all of the rules related to Pattern Engines. They're located in the plugin dir
  */
 public static function loadRules()
 {
     // default var
     $packagesDir = Config::getOption("packagesDir");
     // see if the package dir exists. if it doesn't it means composer hasn't been run
     if (!is_dir($packagesDir)) {
         Console::writeError("you haven't fully set-up Pattern Lab yet. please add a pattern engine...");
     }
     // make sure the pattern engine data exists
     if (file_exists($packagesDir . "/patternengines.json")) {
         // get pattern engine list data
         $patternEngineList = json_decode(file_get_contents($packagesDir . "/patternengines.json"), true);
         // get the pattern engine info
         foreach ($patternEngineList["patternengines"] as $patternEngineName) {
             self::$rules[] = new $patternEngineName();
         }
     } else {
         Console::writeError("The pattern engines list isn't available in <path>" . $packagesDir . "</path>...");
     }
 }
Example #20
0
 /**
  * Set-up default vars
  */
 public static function init()
 {
     // make sure config vars exist
     if (!Config::getOption("patternExtension")) {
         Console::writeError("the pattern extension config option needs to be set...");
     }
     if (!Config::getOption("styleguideKit")) {
         Console::writeError("the styleguideKit config option needs to be set...");
     }
     // set-up config vars
     $patternExtension = Config::getOption("patternExtension");
     $metaDir = Config::getOption("metaDir");
     $styleguideKit = Config::getOption("styleguideKit");
     $styleguideKitPath = Config::getOption("styleguideKitPath");
     if (!$styleguideKitPath || !is_dir($styleguideKitPath)) {
         Console::writeError("your styleguide won't render because i can't find your styleguide files. are you sure they're at <path>" . Console::getHumanReadablePath($styleguideKitPath) . "</path>? you can fix this in <path>./config/config.yml</path> by editing styleguideKitPath...");
     }
     // load pattern-lab's resources
     $partialPath = $styleguideKitPath . DIRECTORY_SEPARATOR . "views" . DIRECTORY_SEPARATOR . "partials";
     $generalHeaderPath = $partialPath . DIRECTORY_SEPARATOR . "general-header." . $patternExtension;
     $generalFooterPath = $partialPath . DIRECTORY_SEPARATOR . "general-footer." . $patternExtension;
     self::$htmlHead = file_exists($generalHeaderPath) ? file_get_contents($generalHeaderPath) : "";
     self::$htmlFoot = file_exists($generalFooterPath) ? file_get_contents($generalFooterPath) : "";
     // gather the user-defined header and footer information
     $patternHeadPath = $metaDir . DIRECTORY_SEPARATOR . "_00-head." . $patternExtension;
     $patternFootPath = $metaDir . DIRECTORY_SEPARATOR . "_01-foot." . $patternExtension;
     self::$patternHead = file_exists($patternHeadPath) ? file_get_contents($patternHeadPath) : "";
     self::$patternFoot = file_exists($patternFootPath) ? file_get_contents($patternFootPath) : "";
     // add the filesystemLoader
     $patternEngineBasePath = PatternEngine::getInstance()->getBasePath();
     $filesystemLoaderClass = $patternEngineBasePath . "\\Loaders\\FilesystemLoader";
     $options = array();
     $options["templatePath"] = $styleguideKitPath . DIRECTORY_SEPARATOR . "views";
     $options["partialsPath"] = $options["templatePath"] . DIRECTORY_SEPARATOR . "partials";
     self::$filesystemLoader = new $filesystemLoaderClass($options);
     $stringLoaderClass = $patternEngineBasePath . "\\Loaders\\StringLoader";
     self::$stringLoader = new $stringLoaderClass();
     // i can't remember why i chose to implement the pattern loader directly in classes
     // i figure i had a good reason which is why it's not showing up here
 }
 public function run()
 {
     // find the value given to the command
     $package = Console::findCommandOptionValue("p|package");
     if ($package) {
         // if <prompt> was passed ask the user for the package name
         if ($package == "prompt") {
             $prompt = "what is the name of the package you want to fetch?";
             $options = "(ex. pattern-lab/plugin-kss)";
             $package = Console::promptInput($prompt, $options);
         }
         // make sure it looks like a valid package
         if (strpos($package, "/") === false) {
             Console::writeError("that wasn't a valid package name. it should look like <info>pattern-lab/plugin-kss</info>...");
         }
         // run composer via fetch
         $f = new Fetch();
         $f->fetchPackage($package);
     } else {
         Console::writeHelpCommand($this->command);
     }
 }
 public function run()
 {
     // set-up required vars
     $options = array();
     $options["moveStatic"] = Console::findCommandOption("p|patternsonly") ? false : true;
     $options["noCacheBuster"] = Console::findCommandOption("n|nocache");
     // DEPRECATED
     // $options["autoReload"]    = Console::findCommandOption("r|autoreload");
     // see if the starterKit flag was passed so you know what dir to watch
     if (Console::findCommandOption("sk")) {
         // load the starterkit watcher
         $w = new Watcher();
         $w->watchStarterKit();
     } else {
         // load the generator
         $g = new Generator();
         $g->generate($options);
         // load the watcher
         $w = new Watcher();
         $w->watch($options);
     }
 }
 public function run()
 {
     // load default vars
     $patternExtension = Config::getOption("patternExtension");
     $patternSourceDir = Config::getOption("patternSourceDir");
     // load the pattern data
     $store = PatternData::get();
     // iterate to get raw data loaded into the PatternData Store
     foreach ($store as $patternStoreKey => $patternStoreData) {
         if ($patternStoreData["category"] == "pattern" && !$patternStoreData["hidden"]) {
             // figure out the source path for the pattern to render
             $srcPath = isset($patternStoreData["pseudo"]) ? PatternData::getPatternOption($patternStoreData["original"], "pathName") : $patternStoreData["pathName"];
             // load the raw data so it can be modified/rendered
             $path = $patternSourceDir . "/" . $srcPath . "." . $patternExtension;
             if (file_exists($path)) {
                 PatternData::setPatternOption($patternStoreKey, "patternRaw", file_get_contents($path));
             } else {
                 Console::writeError($patternStoreData["partial"] . " wasn't found for loading. the given path: " . $path);
             }
         }
     }
 }
 /**
  * Randomly prints a saying after the generate is complete
  */
 public function printSaying()
 {
     $randomNumber = rand(0, 3);
     $colors = array("ok", "options", "info", "warning", "error");
     $color = isset($colors[$randomNumber]) ? $colors[$randomNumber] : "desc";
     $randomNumber = rand(0, 60);
     $sayings = array("have fun storming the castle", "be well, do good work, and keep in touch", "may the sun shine, all day long", "smile :)", "namaste", "walk as if you are kissing the earth with your feet", "to be beautiful means to be yourself", "i was thinking of the immortal words of socrates, who said \"...i drank what?\"", "let me take this moment to compliment you on your fashion sense, particularly your slippers", "42", "he who controls the spice controls the universe", "the greatest thing you'll ever learn is just to love and be loved in return", "nice wand", "i don't have time for a grudge match with every poseur in a parka", "han shot first", "what we've got here is a failure to communicate", "mama always said life was like a box of chocolates. you never know what you're gonna get", "soylent green is people", "a little word of advice, my friend. sometimes you gotta let those hard-to-reach chips go", "shop smart. shop s-mart", "klaatu barada nikto", "(╯°□°)╯︵ ┻━┻", "¸.·´¯`·.´¯`·.¸¸.·´¯`·.¸><(((º>", "@}~}~~~", "(>'.')> (>'.')> (>'.')> ", "\\(^-^)/");
     if (isset($sayings[$randomNumber])) {
         Console::writeLine("<" . $color . ">" . $sayings[$randomNumber] . "...</" . $color . ">");
     }
 }
 public function run()
 {
     // set-up default vars
     $foundLineages = array();
     $patternSourceDir = Config::getOption("patternSourceDir");
     $patternExtension = Config::getOption("patternExtension");
     // check for the regular lineages in only normal patterns
     $store = PatternData::get();
     foreach ($store as $patternStoreKey => $patternStoreData) {
         if ($patternStoreData["category"] == "pattern" && !isset($patternStoreData["pseudo"])) {
             $patternLineages = array();
             $fileData = isset($patternStoreData["patternRaw"]) ? $patternStoreData["patternRaw"] : "";
             $foundLineages = $this->findLineages($fileData);
             if (!empty($foundLineages)) {
                 foreach ($foundLineages as $lineage) {
                     $lineageData = PatternData::getOption($lineage);
                     if ($lineageData) {
                         $patternLineages[] = array("lineagePattern" => $lineage, "lineagePath" => "../../patterns/" . $lineageData["pathDash"] . "/" . $lineageData["pathDash"] . ".html");
                     } else {
                         if (strpos($lineage, '/') === false) {
                             $fileName = $patternStoreData["pathName"] . "." . $patternExtension;
                             Console::writeWarning("you may have a typo in " . $fileName . ". {{> " . $lineage . " }} is not a valid pattern...");
                         }
                     }
                 }
                 // add the lineages to the PatternData::$store
                 PatternData::setPatternOption($patternStoreKey, "lineages", $patternLineages);
             }
         }
     }
     // handle all of those pseudo patterns
     $store = PatternData::get();
     foreach ($store as $patternStoreKey => $patternStoreData) {
         if ($patternStoreData["category"] == "pattern" && isset($patternStoreData["pseudo"])) {
             // add the lineages to the PatternData::$store
             $patternStoreKeyOriginal = $patternStoreData["original"];
             PatternData::setPatternOption($patternStoreKey, "lineages", PatternData::getPatternOption($patternStoreKeyOriginal, "lineages"));
         }
     }
     // check for the reverse lineages and skip pseudo patterns
     $store = PatternData::get();
     foreach ($store as $patternStoreKey => $patternStoreData) {
         if ($patternStoreData["category"] == "pattern" && !isset($patternStoreData["pseudo"])) {
             $patternLineagesR = array();
             $storeTake2 = PatternData::get();
             foreach ($storeTake2 as $haystackKey => $haystackData) {
                 if ($haystackData["category"] == "pattern" && isset($haystackData["lineages"]) && !empty($haystackData["lineages"])) {
                     foreach ($haystackData["lineages"] as $haystackLineage) {
                         if ($haystackLineage["lineagePattern"] == $patternStoreData["partial"]) {
                             $foundAlready = false;
                             foreach ($patternLineagesR as $patternCheck) {
                                 if ($patternCheck["lineagePattern"] == $patternStoreData["partial"]) {
                                     $foundAlready = true;
                                     break;
                                 }
                             }
                             if (!$foundAlready) {
                                 if (PatternData::getOption($haystackKey)) {
                                     $path = PatternData::getPatternOption($haystackKey, "pathDash");
                                     $patternLineagesR[] = array("lineagePattern" => $haystackKey, "lineagePath" => "../../patterns/" . $path . "/" . $path . ".html");
                                 }
                             }
                         }
                     }
                 }
             }
             PatternData::setPatternOption($patternStoreKey, "lineagesR", $patternLineagesR);
         }
     }
     // handle all of those pseudo patterns
     $store = PatternData::get();
     foreach ($store as $patternStoreKey => $patternStoreData) {
         if ($patternStoreData["category"] == "pattern" && isset($patternStoreData["pseudo"])) {
             // add the lineages to the PatternData::$store
             $patternStoreKeyOriginal = $patternStoreData["original"];
             PatternData::setPatternOption($patternStoreKey, "lineagesR", PatternData::getPatternOption($patternStoreKeyOriginal, "lineagesR"));
         }
     }
 }
Example #26
0
 /**
  * Force mirror the dist/ folder to source/
  * @param  {String}    path to the source directory
  * @param  {String}    path to the temp dist directory
  */
 protected function mirrorDist($sourceDir, $tempDirDist)
 {
     // set default vars
     $fsOptions = array();
     $emptyDir = true;
     $validFiles = array("README", ".gitkeep", ".DS_Store", "styleguide");
     // see if the source directory is empty
     if (is_dir($sourceDir)) {
         $objects = new \DirectoryIterator($sourceDir);
         foreach ($objects as $object) {
             if (!$object->isDot() && !in_array($object->getFilename(), $validFiles)) {
                 $emptyDir = false;
                 break;
             }
         }
     }
     // if source directory isn't empty ask if it's ok to nuke what's there
     if (!$emptyDir) {
         $prompt = "a starterkit is already installed. merge the new files with it or replace it?";
         $options = "M/r";
         $input = Console::promptInput($prompt, $options);
         $fsOptions = $input == "r" ? array("delete" => true, "override" => true) : array("delete" => false, "override" => false);
     }
     // mirror dist to source
     Console::writeInfo("installing the starterkit files...");
     $fs = new Filesystem();
     $fs->mirror($tempDirDist, $sourceDir, null);
     Console::writeInfo("starterkit files have been installed...");
 }
Example #27
0
 /**
  * Stop the timer
  */
 public static function stop()
 {
     // make sure start time is set
     if (empty(self::$startTime)) {
         Console::writeError("the timer wasn't started...");
     }
     // get the current time
     $endTime = self::getTime();
     // get the data for the output
     $totalTime = $endTime - self::$startTime;
     $mem = round(memory_get_peak_usage(true) / 1024 / 1024, 2);
     // figure out what tag to show
     $timeTag = "info";
     if ($totalTime > 0.5) {
         $timeTag = "error";
     } else {
         if ($totalTime > 0.3) {
             $timeTag = "warning";
         }
     }
     // write out time/mem stats
     Console::writeLine("site generation took <" . $timeTag . ">" . $totalTime . "</" . $timeTag . "> seconds and used <info>" . $mem . "MB</info> of memory...");
 }
Example #28
0
 /**
  * Gather data from any JSON and YAML files in source/_data
  *
  * Reserved attributes:
  *    - Data::$store["listItems"] : listItems from listitems.json, duplicated into separate arrays for Data::$store["listItems"]["one"], Data::$store["listItems"]["two"]... etc.
  *    - Data::$store["link"] : the links to each pattern
  *    - Data::$store["cacheBuster"] : the cache buster value to be appended to URLs
  *    - Data::$store["patternSpecific"] : holds attributes from the pattern-specific data files
  *
  * @return {Array}        populates Data::$store
  */
 public static function gather($options = array())
 {
     // set-up the dispatcher
     $dispatcherInstance = Dispatcher::getInstance();
     // dispatch that the data gather has started
     $dispatcherInstance->dispatch("data.gatherStart");
     // default vars
     $found = false;
     $dataJSON = array();
     $dataYAML = array();
     $listItemsJSON = array();
     $listItemsYAML = array();
     $sourceDir = Config::getOption("sourceDir");
     // iterate over all of the other files in the source directory
     if (!is_dir($sourceDir . "/_data/")) {
         Console::writeWarning("<path>_data/</path> doesn't exist so you won't have dynamic data...");
         mkdir($sourceDir . "/_data/");
     }
     // find the markdown-based annotations
     $finder = new Finder();
     $finder->files()->in($sourceDir . "/_data/");
     $finder->sortByName();
     foreach ($finder as $name => $file) {
         $ext = $file->getExtension();
         $data = array();
         $fileName = $file->getFilename();
         $hidden = $fileName[0] == "_";
         $isListItems = strpos($fileName, "listitems");
         $pathName = $file->getPathname();
         $pathNameClean = str_replace($sourceDir . "/", "", $pathName);
         if (!$hidden && ($ext == "json" || $ext == "yaml")) {
             if ($isListItems === false) {
                 if ($ext == "json") {
                     $file = file_get_contents($pathName);
                     $data = json_decode($file, true);
                     if ($jsonErrorMessage = JSON::hasError()) {
                         JSON::lastErrorMsg($pathNameClean, $jsonErrorMessage, $data);
                     }
                 } else {
                     if ($ext == "yaml") {
                         $file = file_get_contents($pathName);
                         try {
                             $data = YAML::parse($file);
                         } catch (ParseException $e) {
                             printf("unable to parse " . $pathNameClean . ": %s..\n", $e->getMessage());
                         }
                         // single line of text won't throw a YAML error. returns as string
                         if (gettype($data) == "string") {
                             $data = array();
                         }
                     }
                 }
                 if (is_array($data)) {
                     self::$store = array_replace_recursive(self::$store, $data);
                 }
             } else {
                 if ($isListItems !== false) {
                     $data = $ext == "json" ? self::getListItems("_data/" . $fileName) : self::getListItems("_data/" . $fileName, "yaml");
                     if (!isset(self::$store["listItems"])) {
                         self::$store["listItems"] = array();
                     }
                     self::$store["listItems"] = array_replace_recursive(self::$store["listItems"], $data);
                 }
             }
         }
     }
     if (is_array(self::$store)) {
         foreach (self::$reservedKeys as $reservedKey) {
             if (array_key_exists($reservedKey, self::$store)) {
                 Console::writeWarning("\"" . $reservedKey . "\" is a reserved key in Pattern Lab. the data using that key will be overwritten. please choose a new key...");
             }
         }
     }
     self::$store["cacheBuster"] = Config::getOption("cacheBuster");
     self::$store["link"] = array();
     self::$store["patternSpecific"] = array();
     $dispatcherInstance->dispatch("data.gatherEnd");
 }
Example #29
0
 /**
  * Write out the new config option value
  * @param  {String}       the name of the option to be changed
  * @param  {String}       the new value of the option to be changed
  */
 protected static function writeUpdateConfigOption($optionName, $optionValue)
 {
     // parse the YAML options
     try {
         $options = Yaml::parse(file_get_contents(self::$userConfigPath));
     } catch (ParseException $e) {
         Console::writeError("Config parse error in <path>" . self::$userConfigPath . "</path>: " . $e->getMessage());
     }
     if (isset($options[$optionName]) && is_array($options[$optionName])) {
         $optionValue = is_array($optionValue) ? $optionValue : array($optionValue);
         $options[$optionName] = array_merge($options[$optionName], $optionValue);
     } else {
         $options[$optionName] = $optionValue;
     }
     // dump the YAML
     $configOutput = Yaml::dump($options, 3);
     // write out the new config file
     file_put_contents(self::$userConfigPath, $configOutput);
 }
 /**
  * Pulls together a bunch of functions from builder.lib.php in an order that makes sense
  * @param  {Boolean}       decide if CSS should be parsed and saved. performance hog.
  * @param  {Boolean}       decide if static files like CSS and JS should be moved
  */
 public function generate($options = array())
 {
     // double-checks options was properly set
     if (empty($options)) {
         Console::writeError("need to pass options to generate...");
     }
     // set the default vars
     $moveStatic = isset($options["moveStatic"]) ? $options["moveStatic"] : true;
     $noCacheBuster = isset($options["noCacheBuster"]) ? $options["noCacheBuster"] : false;
     $exportFiles = isset($options["exportFiles"]) ? $options["exportFiles"] : false;
     $exportClean = isset($options["exportClean"]) ? $options["exportClean"] : false;
     $watchMessage = isset($options["watchMessage"]) ? $options["watchMessage"] : false;
     $watchVerbose = isset($options["watchVerbose"]) ? $options["watchVerbose"] : false;
     if ($noCacheBuster) {
         Config::setOption("cacheBuster", 0);
     }
     // gather up all of the data to be used in patterns
     Data::gather();
     // gather all of the various pattern info
     $options = array();
     $options["exportClean"] = $exportClean;
     $options["exportFiles"] = $exportFiles;
     PatternData::gather($options);
     // gather the annotations
     Annotations::gather();
     // clean the public directory to remove old files
     if (Config::getOption("cleanPublic") == "true" && $moveStatic) {
         FileUtil::cleanPublic();
     }
     // render out the index and style guide
     $this->generateIndex();
     $this->generateStyleguide();
     $this->generateViewAllPages();
     // render out the patterns and move them to public/patterns
     $options = array();
     $options["exportFiles"] = $exportFiles;
     $this->generatePatterns($options);
     // render the annotations as a js file
     $this->generateAnnotations();
     // move all of the files unless pattern only is set
     if ($moveStatic) {
         $this->moveStatic();
     }
     // update the change time so the auto-reload will fire (doesn't work for the index and style guide)
     Util::updateChangeTime();
     if ($watchVerbose && $watchMessage) {
         Console::writeLine($watchMessage);
     } else {
         Console::writeLine("your site has been generated...");
         Timer::stop();
     }
 }