sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function isEligible(PromotionSubjectInterface $subject, array $configuration) { if (!$subject instanceof OrderInterface) { throw new UnsupportedTypeException($subject, OrderInterface::class); } if (null === $address = $subject->getShippingAddress()) { return false; } return $this->isTargetCountry($subject, $configuration['country']); }
{@inheritdoc}
entailment
public function releaseLock($name) { if (isset($this->locks[$name]) && $this->memcached->delete($name)) { unset($this->locks[$name]); return true; } return false; }
Release lock @param string $name name of lock @return bool
entailment
public function bootstrap($app) { $models = Yii::$app->getModule('vote')->models; foreach ($models as $value) { $modelId = Rating::getModelIdByName($value); $modelName = Rating::getModelNameById($modelId); Event::on($modelName::className(), $modelName::EVENT_INIT, function ($event) { if (null === $event->sender->getBehavior('rating')) { $event->sender->attachBehavior('rating', [ 'class' => RatingBehavior::className(), ]); } }); } }
Bootstrap method to be called during application bootstrap stage. @param Application $app the application currently running
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('enhavo_grid'); $rootNode ->children() ->arrayNode('render') ->children() ->arrayNode('sets') ->useAttributeAsKey('name') ->prototype('array') ->prototype('scalar')->end() ->end() ->end() ->end() ->end() ->arrayNode('doctrine') ->addDefaultsIfNotSet() ->children() ->scalarNode('enable_columns')->defaultValue(true)->end() ->scalarNode('enable_items')->defaultValue(true)->end() ->end() ->end() ->arrayNode('column') ->addDefaultsIfNotSet() ->children() ->scalarNode('style_form')->defaultValue(StyleType::class)->end() ->scalarNode('width_form')->defaultValue(WidthType::class)->end() ->arrayNode('styles') ->useAttributeAsKey('name') ->prototype('array') ->children() ->scalarNode('label')->end() ->scalarNode('value')->end() ->end() ->end() ->end() ->end() ->end() ->arrayNode('items') ->isRequired() ->useAttributeAsKey('name') ->prototype('array') ->children() ->scalarNode('model')->end() ->scalarNode('form')->end() ->scalarNode('repository')->end() ->scalarNode('template')->end() ->scalarNode('form_template')->end() ->scalarNode('label')->end() ->scalarNode('translationDomain')->end() ->scalarNode('type')->end() ->scalarNode('parent')->end() ->scalarNode('factory')->end() ->variableNode('groups')->end() ->end() ->end() ->end() ->end(); return $treeBuilder; }
{@inheritDoc}
entailment
public function getBackButton(bool $json_serialized = true) { // Create the button $inline_keyboard = [ 'inline_keyboard' => [ [ [ 'text' => $this->bot->local->getStr('Back_Button'), 'callback_data' => 'back' ] ] ] ]; // Serialize everything as JSON if necessary if ($json_serialized) { return json_encode($inline_keyboard); } else { return $inline_keyboard; } }
\brief Get a simple Back button with back as <code>callback_data</code>. @param $json_serialized return a json serialized string, or an array. @return string|array A button with written "back".
entailment
public function getBackSkipKeyboard(bool $json_serialized = true) { // Create the keyboard $inline_keyboard = [ 'inline_keyboard' => [ [ [ 'text' => $this->bot->local->getStr('Back_Button'), 'callback_data' => 'back' ], [ 'text' => $this->bot->local->getStr('Skip_Button'), 'callback_data' => 'skip' ] ] ] ]; if ($json_serialized) { return json_encode($inline_keyboard); } else { return $inline_keyboard; } }
\brief Get a Back and a Skip buttons inthe same row. \details Back button has callback_data "back" and Skip button has callback_data "skip". @param bool $json_serialized return a json serialized string, or an array. @return string|array A button with written "back" and one with written "Skip".
entailment
public function getChooseLanguageKeyboard(string $prefix = 'cl', bool $json_serialized = true) { $inline_keyboard = ['inline_keyboard' => array()]; // $bot->local is an object of type Localization // $local->local is the array where the localizated strings are saved $localization = $this->bot->local->local; foreach ($localization as $languages => $language_msg) { // If the language is the same as the one set for the current user in $bot if (strpos($languages, $this->bot->local->language) !== false) { // Just create a button with one language in it array_push($inline_keyboard['inline_keyboard'], [ [ 'text' => $language_msg['Language'], 'callback_data' => 'same/language' ] ]); } else { array_push($inline_keyboard['inline_keyboard'], [ [ 'text' => $language_msg['Language'] . '/' . $localization, 'callback_data' => $prefix . '/' . $languages ] ]); } } // Unset the variables from the foreach unset($languages); unset($language_msg); array_push($inline_keyboard['inline_keyboard'], [ [ 'text' => $this->bot->local->getStr('Back_Button'), 'callback_data' => 'back' ] ]); if ($json_serialized) { return json_encode($inline_keyboard); } else { return $inline_keyboard; } }
\brief Get various buttons for set various languages. \details Create a button for each language contained in <code>$localization['languages']</code> variable of $bot object. There will be a button per row. The button's label will include the target language and the current one. The callback data for each button will be "cl/key" where key is the key in <code>$localization['languages']</code>. @param $prefix Prefix followed by '/' and the language index (en, it..). @param $json_serialized Get a JSON-serialized string or an array. @return string|array The buttons in the selected type.
entailment
public function addToc(\Enhavo\Bundle\ProjectBundle\Entity\Content $toc) { $toc->setMagazine($this); $this->toc[] = $toc; return $this; }
Add toc @param \Enhavo\Bundle\ProjectBundle\Entity\Content $toc @return Magazine
entailment
public function removeToc(\Enhavo\Bundle\ProjectBundle\Entity\Content $toc) { $toc->setMagazine(null); $this->toc->removeElement($toc); }
Remove toc @param \Enhavo\Bundle\ProjectBundle\Entity\Content $toc
entailment
public function addPicture(\Enhavo\Bundle\MediaBundle\Entity\File $pictures) { $this->pictures[] = $pictures; return $this; }
Add pictures @param \Enhavo\Bundle\MediaBundle\Entity\File $pictures @return Magazine
entailment
public function removePicture(\Enhavo\Bundle\MediaBundle\Entity\File $pictures) { $this->pictures->removeElement($pictures); }
Remove pictures @param \Enhavo\Bundle\MediaBundle\Entity\File $pictures
entailment
public function offsetGet($offset) { // Get name of the method, the class should have. Like "getText" $method = Text::camelCase("get $offset"); // If it exists, call it and return its return value if (method_exists($this, $method)) { return $this->{$method}(); } // If not return the data from the array after checking it is set return isset($this->container[$offset]) ? $this->container[$offset] : null; }
\brief Get the given offset. @param $offset The given offset. @return Data relative to the offset.
entailment
public function oldDispatch() { // For each update type foreach (BasicBot::$update_types as $offset => $class) { // Check if the bot has an inherited method if (method_exists($this, 'process' . $class)) { // Wrap it in a closure to make it works with the 3.0 version $this->answerUpdate[$offset] = function ($bot, $entity) use ($class) { $bot->{"process$class"}($entity); }; } } }
\brief Set compatibilityu mode for old processes method. \details If your bot uses `processMessage` or another deprecated function, call this method to make the old version works.
entailment
public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addModelTransformer(new CallbackTransformer( function ($originalDescription) use ($options) { if(true === $originalDescription) { return self::VALUE_TRUE; } if(false === $originalDescription) { return self::VALUE_FALSE; } if(null === $originalDescription || '' === $originalDescription) { if(true === $options['default'] || self::VALUE_TRUE === $options['default']) { return self::VALUE_TRUE; } if(false === $options['default']|| self::VALUE_FALSE === $options['default']) { return self::VALUE_FALSE; } return self::VALUE_NULL; } return $originalDescription; }, function ($submittedDescription) { if(self::VALUE_TRUE === $submittedDescription) { return true; } if(self::VALUE_FALSE === $submittedDescription) { return false; } return null; } )); }
{@inheritdoc}
entailment
public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['message'] = $this->translator->trans($options['message'], $options['parameters'], $options['translation_domain']); $view->vars['type'] = $options['type']; }
{@inheritdoc}
entailment
public function setChatLog(string $chat_id, bool $skip_check = false) { // Check that the bot can write in that chat if (!$skip_check && $this->getChat($chat_id) !== false) { $this->chat_log = $chat_id; } }
\brief Set chat_id choosed for logging. @param string $chat_id Chat_id choosed. @param bool $skip_check Skip checking if the chat is valid (set true only if the bot is using webhook to get updates).
entailment
public function addChild(\Enhavo\Bundle\NavigationBundle\Model\NodeInterface $children) { $this->children[] = $children; $children->setParent($this); return $this; }
Add children @param \Enhavo\Bundle\NavigationBundle\Model\NodeInterface $children @return Node
entailment
public function removeChild(\Enhavo\Bundle\NavigationBundle\Model\NodeInterface $children) { $children->setParent(null); $this->children->removeElement($children); }
Remove children @param \Enhavo\Bundle\NavigationBundle\Model\NodeInterface $children
entailment
public function setParent(\Enhavo\Bundle\NavigationBundle\Model\NodeInterface $parent = null) { $this->parent = $parent; return $this; }
Set parent @param \Enhavo\Bundle\NavigationBundle\Model\NodeInterface $parent @return Node
entailment
protected function generateAnnotations() { // set-up the dispatcher $dispatcherInstance = Dispatcher::getInstance(); // note the start of the operation $dispatcherInstance->dispatch("builder.generateAnnotationsStart"); // default var $publicDir = Config::getOption("publicDir"); // encode the content so it can be written out $json = json_encode(Annotations::get()); // make sure annotations/ exists if (!is_dir($publicDir."/annotations")) { mkdir($publicDir."/annotations"); } // write out the new annotations.js file file_put_contents($publicDir."/annotations/annotations.js","var comments = ".$json.";"); // note the end of the operation $dispatcherInstance->dispatch("builder.generateAnnotationsEnd"); }
Generates the annotations js file
entailment
protected function generateIndex() { /** * Handle missing index.html. Solves https://github.com/drupal-pattern-lab/patternlab-php-core/issues/14 * Could also be used to re-add missing styleguidekit assets with a few edits? * * 1. @TODO: Figure out a better way to future-proof path resolution for styleguidekit `dist` folder * 2. Recusirively copy files from styleguidekit to publicDir via https://stackoverflow.com/a/7775949 * 3. Make sure we only try to create new directories if they don't already exist * 4. Only copy files if they are missing (vs changed, etc) */ if (!file_exists(Config::getOption("publicDir")."/index.html")) { $index = Console::getHumanReadablePath(Config::getOption("publicDir")).DIRECTORY_SEPARATOR."index.html"; Console::writeWarning($index . " is missing. No biggie. Grabbing a fresh copy from your StyleguideKit..."); $baseDir = Config::getOption("baseDir") . '/vendor'; $finder = new Finder(); // Locate the current theme's styleguidekit assets via the patternlab-styleguidekit `type` in composer.json $finder->files()->name("composer.json")->in($baseDir)->contains('patternlab-styleguidekit')->sortByName(); foreach ($finder as $file) { $src = dirname($file->getRealPath()) . DIRECTORY_SEPARATOR . 'dist'; /* [1] */ $dest= Config::getOption("publicDir"); if (is_dir($src)){ if(!is_dir($dest)) { mkdir($dest, 0755); } foreach ( /* [2] */ $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($src, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item ) { if ($item->isDir()) { if(!is_dir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName())) { /* [3] */ mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName()); } } else { if(!file_exists($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName())) { /* [4] */ copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName()); } } } } } } // set-up the dispatcher $dispatcherInstance = Dispatcher::getInstance(); // note the start of the operation $dispatcherInstance->dispatch("builder.generateIndexStart"); // default var $dataDir = Config::getOption("publicDir")."/styleguide/data"; // double-check that the data directory exists if (!is_dir($dataDir)) { FileUtil::makeDir($dataDir); } $output = ""; // load and write out the config options $config = array(); $exposedOptions = Config::getOption("exposedOptions"); foreach ($exposedOptions as $exposedOption) { $config[$exposedOption] = Config::getOption($exposedOption); } $output .= "var config = ".json_encode($config).";\n"; // load the ish Controls $ishControls = array(); $controlsToHide = array(); $ishControlsHide = Config::getOption("ishControlsHide"); if ($ishControlsHide) { foreach ($ishControlsHide as $controlToHide) { $controlsToHide[$controlToHide] = "true"; } } $ishControls["ishControlsHide"] = $controlsToHide; $output .= "var ishControls = ".json_encode($ishControls).";\n"; // load and write out the items for the navigation $niExporter = new NavItemsExporter(); $navItems = $niExporter->run(); $output .= "var navItems = ".json_encode($navItems).";\n"; // load and write out the items for the pattern paths $patternPaths = array(); $ppdExporter = new PatternPathDestsExporter(); $patternPaths = $ppdExporter->run(); $output .= "var patternPaths = ".json_encode($patternPaths).";\n"; // load and write out the items for the view all paths $viewAllPaths = array(); $vapExporter = new ViewAllPathsExporter(); $viewAllPaths = $vapExporter->run($navItems); $output .= "var viewAllPaths = ".json_encode($viewAllPaths).";\n"; // gather plugin package information $packagesInfo = array(); $componentDir = Config::getOption("componentDir"); if (!is_dir($componentDir)) { mkdir($componentDir); } $componentPackagesDir = $componentDir."/packages"; if (!is_dir($componentDir."/packages")) { mkdir($componentDir."/packages"); } $finder = new Finder(); $finder->files()->name("*.json")->in($componentPackagesDir); $finder->sortByName(); foreach ($finder as $file) { $filename = $file->getFilename(); if ($filename[0] != "_") { $javascriptPaths = array(); $packageInfo = json_decode(file_get_contents($file->getPathname()),true); foreach ($packageInfo["templates"] as $templateKey => $templatePath) { $templatePathFull = $componentDir."/".$packageInfo["name"]."/".$templatePath; $packageInfo["templates"][$templateKey] = (file_exists($templatePathFull)) ? file_get_contents($templatePathFull) : ""; } foreach ($packageInfo["javascripts"] as $key => $javascriptPath) { $javascriptPaths[] = "patternlab-components/".$packageInfo["name"]."/".$javascriptPath; } $packageInfo["javascripts"] = $javascriptPaths; $packagesInfo[] = $packageInfo; } } $output .= "var plugins = ".json_encode($packagesInfo).";"; // write out the data file_put_contents($dataDir."/patternlab-data.js",$output); // Structuring all the same data that went into `patternlab-data.js` and putting it into `patternlab-data.json` too $allPlData = array( 'config' => $config, 'ishControls' => $ishControls, 'navItems' => $navItems, 'patternPaths' => $patternPaths, 'viewAllPaths' => $viewAllPaths, 'plugins' => $packagesInfo, ); file_put_contents($dataDir."/patternlab-data.json", json_encode($allPlData)); // note the end of the operation $dispatcherInstance->dispatch("builder.generateIndexEnd"); }
Generates the data that powers the index page
entailment
protected function generatePatterns($options = array()) { // set-up the dispatcher $dispatcherInstance = Dispatcher::getInstance(); // note the beginning of the operation $dispatcherInstance->dispatch("builder.generatePatternsStart"); // set-up common vars $exportFiles = (isset($options["exportFiles"]) && $options["exportFiles"]); $exportDir = Config::getOption("exportDir"); $patternPublicDir = !$exportFiles ? Config::getOption("patternPublicDir") : Config::getOption("patternExportDir"); $patternSourceDir = Config::getOption("patternSourceDir"); $patternExtension = Config::getOption("patternExtension"); $suffixRendered = Config::getOption("outputFileSuffixes.rendered"); $suffixRaw = Config::getOption("outputFileSuffixes.rawTemplate"); $suffixMarkupOnly = Config::getOption("outputFileSuffixes.markupOnly"); // make sure the export dir exists if ($exportFiles && !is_dir($exportDir)) { mkdir($exportDir); } // make sure patterns exists if (!is_dir($patternPublicDir)) { mkdir($patternPublicDir); } // loop over the pattern data store to render the individual patterns $store = PatternData::get(); foreach ($store as $patternStoreKey => $patternStoreData) { if (($patternStoreData["category"] == "pattern") && isset($patternStoreData["hidden"]) && (!$patternStoreData["hidden"])) { $path = $patternStoreData["pathDash"]; $pathName = (isset($patternStoreData["pseudo"])) ? $patternStoreData["pathOrig"] : $patternStoreData["pathName"]; // modify the pattern mark-up $markup = $patternStoreData["code"]; $markupFull = $patternStoreData["header"].$markup.$patternStoreData["footer"]; $markupEngine = file_get_contents($patternSourceDir."/".$pathName.".".$patternExtension); // if the pattern directory doesn't exist create it if (!is_dir($patternPublicDir."/".$path)) { mkdir($patternPublicDir."/".$path); } // write out the various pattern files file_put_contents($patternPublicDir."/".$path."/".$path.$suffixRendered.".html",$markupFull); if (!$exportFiles) { file_put_contents($patternPublicDir."/".$path."/".$path.$suffixMarkupOnly.".html",$markup); file_put_contents($patternPublicDir."/".$path."/".$path.$suffixRaw.".".$patternExtension,$markupEngine); } } } // note the end of the operation $dispatcherInstance->dispatch("builder.generatePatternsEnd"); }
Generates all of the patterns and puts them in the public directory @param {Array} various options that might affect the export. primarily the location.
entailment
protected function generateStyleguide() { // set-up the dispatcher $dispatcherInstance = Dispatcher::getInstance(); // note the beginning of the operation $dispatcherInstance->dispatch("builder.generateStyleguideStart"); // default var $publicDir = Config::getOption("publicDir"); // load the pattern loader $ppdExporter = new PatternPathSrcExporter(); $patternPathSrc = $ppdExporter->run(); $options = array(); $options["patternPaths"] = $patternPathSrc; $patternEngineBasePath = PatternEngine::getInstance()->getBasePath(); $patternLoaderClass = $patternEngineBasePath."\Loaders\PatternLoader"; $patternLoader = new $patternLoaderClass($options); // check directories i need if (!is_dir($publicDir."/styleguide/")) { mkdir($publicDir."/styleguide/"); } if (!is_dir($publicDir."/styleguide/html/")) { mkdir($publicDir."/styleguide/html/"); } // grab the partials into a data object for the style guide $ppExporter = new PatternPartialsExporter(); $partials = $ppExporter->run(); // add the pattern data so it can be exported $patternData = array(); // add the pattern lab specific mark-up $filesystemLoader = Template::getFilesystemLoader(); $stringLoader = Template::getStringLoader(); $globalData = Data::get(); $globalData["patternLabHead"] = $stringLoader->render(array("string" => Template::getHTMLHead(), "data" => array("cacheBuster" => $partials["cacheBuster"]))); $globalData["patternLabFoot"] = $stringLoader->render(array("string" => Template::getHTMLFoot(), "data" => array("cacheBuster" => $partials["cacheBuster"], "patternData" => json_encode($patternData)))); $globalData["viewall"] = true; $header = $patternLoader->render(array("pattern" => Template::getPatternHead(), "data" => $globalData)); $code = $filesystemLoader->render(array("template" => "viewall", "data" => $partials)); $footer = $patternLoader->render(array("pattern" => Template::getPatternFoot(), "data" => $globalData)); $styleGuidePage = $header.$code.$footer; file_put_contents($publicDir."/styleguide/html/styleguide.html",$styleGuidePage); // note the end of the operation $dispatcherInstance->dispatch("builder.generateStyleguideEnd"); }
Generates the style guide view
entailment
protected function generateViewAllPages() { // set-up the dispatcher $dispatcherInstance = Dispatcher::getInstance(); // note the beginning of the operation $dispatcherInstance->dispatch("builder.generateViewAllPagesStart"); // default vars $patternPublicDir = Config::getOption("patternPublicDir"); $htmlHead = Template::getHTMLHead(); $htmlFoot = Template::getHTMLFoot(); $patternHead = Template::getPatternHead(); $patternFoot = Template::getPatternFoot(); $filesystemLoader = Template::getFilesystemLoader(); $stringLoader = Template::getStringLoader(); $globalData = Data::get(); // load the pattern loader $ppdExporter = new PatternPathSrcExporter(); $patternPathSrc = $ppdExporter->run(); $options = array(); $options["patternPaths"] = $patternPathSrc; $patternEngineBasePath = PatternEngine::getInstance()->getBasePath(); $patternLoaderClass = $patternEngineBasePath."\Loaders\PatternLoader"; $patternLoader = new $patternLoaderClass($options); // make sure view all is set $globalData["viewall"] = true; // make sure the pattern dir exists if (!is_dir($patternPublicDir)) { mkdir($patternPublicDir); } // add view all to each list $store = PatternData::get(); foreach ($store as $patternStoreKey => $patternStoreData) { if ($patternStoreData["category"] == "patternSubtype") { // grab the partials into a data object for the style guide $ppExporter = new PatternPartialsExporter(); $partials = $ppExporter->run($patternStoreData["type"],$patternStoreData["name"]); if (!empty($partials["partials"])) { // add the pattern data so it can be exported $patternData = array(); $patternData["patternPartial"] = "viewall-".$patternStoreData["typeDash"]."-".$patternStoreData["nameDash"]; $globalData["patternLabHead"] = $stringLoader->render(array("string" => Template::getHTMLHead(), "data" => array("cacheBuster" => $partials["cacheBuster"]))); $globalData["patternLabFoot"] = $stringLoader->render(array("string" => Template::getHTMLFoot(), "data" => array("cacheBuster" => $partials["cacheBuster"], "patternData" => json_encode($patternData)))); // render the parts and join them $header = $patternLoader->render(array("pattern" => $patternHead, "data" => $globalData)); $code = $filesystemLoader->render(array("template" => "viewall", "data" => $partials)); $footer = $patternLoader->render(array("pattern" => $patternFoot, "data" => $globalData)); $viewAllPage = $header.$code.$footer; // if the pattern directory doesn't exist create it $patternPath = $patternStoreData["pathDash"]; if (!is_dir($patternPublicDir."/".$patternPath)) { mkdir($patternPublicDir."/".$patternPath); file_put_contents($patternPublicDir."/".$patternPath."/index.html",$viewAllPage); } else { file_put_contents($patternPublicDir."/".$patternPath."/index.html",$viewAllPage); } } } else if (($patternStoreData["category"] == "patternType") && PatternData::hasPatternSubtype($patternStoreData["nameDash"])) { // grab the partials into a data object for the style guide $ppExporter = new PatternPartialsExporter(); $partials = $ppExporter->run($patternStoreData["name"]); if (!empty($partials["partials"])) { // add the pattern data so it can be exported $patternData = array(); $patternData["patternPartial"] = "viewall-".$patternStoreData["nameDash"]."-all"; // add the pattern lab specific mark-up $globalData["patternLabHead"] = $stringLoader->render(array("string" => $htmlHead, "data" => array("cacheBuster" => $partials["cacheBuster"]))); $globalData["patternLabFoot"] = $stringLoader->render(array("string" => $htmlFoot, "data" => array("cacheBuster" => $partials["cacheBuster"], "patternData" => json_encode($patternData)))); // render the parts and join them $header = $patternLoader->render(array("pattern" => $patternHead, "data" => $globalData)); $code = $filesystemLoader->render(array("template" => "viewall", "data" => $partials)); $footer = $patternLoader->render(array("pattern" => $patternFoot, "data" => $globalData)); $viewAllPage = $header.$code.$footer; // if the pattern directory doesn't exist create it $patternPath = $patternStoreData["pathDash"]; if (!is_dir($patternPublicDir."/".$patternPath)) { mkdir($patternPublicDir."/".$patternPath); file_put_contents($patternPublicDir."/".$patternPath."/index.html",$viewAllPage); } else { file_put_contents($patternPublicDir."/".$patternPath."/index.html",$viewAllPage); } } } } // note the end of the operation $dispatcherInstance->dispatch("builder.generateViewAllPagesEnd"); }
Generates the view all pages
entailment
public function beforeValidate() { foreach ($this->attributes as $attribute) { $this->owner->$attribute = HtmlPurifier::process($this->owner->$attribute, $this->config); } }
Before validate event
entailment
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..."); } }
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.
entailment
public function create(UserInterface $user) { if($user == null || $user->getAuthIdentifier() == null) { return false; } $token = $this->generateAuthToken(); $token->setAuthIdentifier( $user->getAuthIdentifier() ); $t = new \DateTime; $insertData = array_merge($token->toArray(), array( 'created_at' => $t, 'updated_at' => $t )); $this->db()->insert($insertData); return $token; }
Creates an auth token for user. @param \Illuminate\Auth\UserInterface $user @return \TAppleby\AuthToken\AuthToken|false
entailment
public function find($serializedAuthToken) { $authToken = $this->deserializeToken($serializedAuthToken); if($authToken == null) { return null; } if(!$this->verifyAuthToken($authToken)) { return null; } $res = $this->db() ->where('auth_identifier', $authToken->getAuthIdentifier()) ->where('public_key', $authToken->getPublicKey()) ->where('private_key', $authToken->getPrivateKey()) ->first(); if($res == null) { return null; } return $authToken; }
Find user id from auth token. @param $serializedAuthToken string @return \TAppleby\AuthToken\AuthToken|null
entailment
public function register() { $app = $this->app; $app->bindShared('tappleby.auth.token', function ($app) { return new AuthTokenManager($app); }); $app->bindShared('tappleby.auth.token.filter', function ($app) { $driver = $app['tappleby.auth.token']->driver(); $events = $app['events']; return new AuthTokenFilter($driver, $events); }); $app->bind('Tappleby\AuthToken\AuthTokenController', function ($app) { $driver = $app['tappleby.auth.token']->driver(); $credsFormatter = $app['config']->get('laravel-auth-token::format_credentials', null); $events = $app['events']; return new AuthTokenController($driver, $credsFormatter, $events); }); }
Register the service provider. @return void
entailment
protected static function buildFileList($initialList) { $fileList = array(); // see if it's an array. loop over the multiple items if it is if (is_array($initialList)) { foreach ($initialList as $listItem) { $fileList[$listItem] = $listItem; } } else { $fileList[$listItem] = $listItem; } return $fileList; }
Move the component files from the package to their location in the patternlab-components dir @param {String/Array} the items to create a fileList for @return {Array} list of files destination and source
entailment
protected static function init() { // start the timer Timer::start(); // initialize the console to print out any issues Console::init(); // initialize the config for the pluginDir $baseDir = __DIR__."/../../../../../"; Config::init($baseDir,false); // make sure the source dir is set-up $sourceDir = Config::getOption("sourceDir"); if (!is_dir($sourceDir)) { FileUtil::makeDir($sourceDir); } // make sure the public dir is set-up $publicDir = Config::getOption("publicDir"); if (!is_dir($publicDir)) { FileUtil::makeDir($publicDir); } Dispatcher::init(); }
Common init sequence
entailment
protected static function moveFiles($source,$destination,$packageName,$sourceBase,$destinationBase) { $fs = new Filesystem(); // make sure the destination base exists if (!is_dir($destinationBase)) { $fs->mkdir($destinationBase); } // clean any * or / on the end of $destination $destination = (($destination != "*") && ($destination[strlen($destination)-1] == "*")) ? substr($destination,0,-1) : $destination; $destination = ($destination[strlen($destination)-1] == "/") ? substr($destination,0,-1) : $destination; // decide how to move the files. the rules: // src ~ dest -> action // * ~ * -> mirror all in {srcroot}/ to {destroot}/ // * ~ path/* -> mirror all in {srcroot}/ to {destroot}/path/ // foo/* ~ path/* -> mirror all in {srcroot}/foo/ to {destroot}/path/ // foo/s.html ~ path/k.html -> mirror {srcroot}/foo/s.html to {destroot}/path/k.html if (($source == "*") && ($destination == "*")) { $result = self::pathExists($packageName, $destinationBase.DIRECTORY_SEPARATOR); $options = ($result) ? array("delete" => true, "override" => true) : array("delete" => false, "override" => false); $fs->mirror($sourceBase, $destinationBase.DIRECTORY_SEPARATOR, null, $options); } else if ($source == "*") { $result = self::pathExists($packageName, $destinationBase.DIRECTORY_SEPARATOR.$destination); $options = ($result) ? array("delete" => true, "override" => true) : array("delete" => false, "override" => false); $fs->mirror($sourceBase, $destinationBase.DIRECTORY_SEPARATOR.$destination, null, $options); } else if ($source[strlen($source)-1] == "*") { $source = rtrim($source,"/*"); $result = self::pathExists($packageName, $destinationBase.DIRECTORY_SEPARATOR.$destination); $options = ($result) ? array("delete" => true, "override" => true) : array("delete" => false, "override" => false); $fs->mirror($sourceBase.$source, $destinationBase.DIRECTORY_SEPARATOR.$destination, null, $options); } else { $pathInfo = explode(DIRECTORY_SEPARATOR,$destination); $file = array_pop($pathInfo); $destinationDir = implode(DIRECTORY_SEPARATOR,$pathInfo); if (!$fs->exists($destinationBase.DIRECTORY_SEPARATOR.$destinationDir)) { $fs->mkdir($destinationBase.DIRECTORY_SEPARATOR.$destinationDir); } $result = self::pathExists($packageName, $destinationBase.DIRECTORY_SEPARATOR.$destination); $override = ($result) ? true : false; $fs->copy($sourceBase.$source, $destinationBase.DIRECTORY_SEPARATOR.$destination, $override); } }
Parse the component types to figure out what needs to be moved and added to the component JSON files @param {String} file path to move @param {String} file path to move to @param {String} the name of the package @param {String} the base directory for the source of the files @param {String} the base directory for the destination of the files (publicDir or sourceDir) @param {Array} the list of files to be moved
entailment
public static function parseComposerExtraList($composerExtra, $name, $pathDist) { // move assets to the base directory if (isset($composerExtra["dist"]["baseDir"])) { self::parseFileList($name,$pathDist,Config::getOption("baseDir"),$composerExtra["dist"]["baseDir"]); } // move assets to the public directory if (isset($composerExtra["dist"]["publicDir"])) { self::parseFileList($name,$pathDist,Config::getOption("publicDir"),$composerExtra["dist"]["publicDir"]); } // move assets to the source directory if (isset($composerExtra["dist"]["sourceDir"])) { self::parseFileList($name,$pathDist,Config::getOption("sourceDir"),$composerExtra["dist"]["sourceDir"]); } // move assets to the scripts directory if (isset($composerExtra["dist"]["scriptsDir"])) { self::parseFileList($name,$pathDist,Config::getOption("scriptsDir"),$composerExtra["dist"]["scriptsDir"]); } // move assets to the data directory if (isset($composerExtra["dist"]["dataDir"])) { self::parseFileList($name,$pathDist,Config::getOption("dataDir"),$composerExtra["dist"]["dataDir"]); } // move assets to the components directory if (isset($composerExtra["dist"]["componentDir"])) { $templateExtension = isset($composerExtra["templateExtension"]) ? $composerExtra["templateExtension"] : "mustache"; $onready = isset($composerExtra["onready"]) ? $composerExtra["onready"] : ""; $callback = isset($composerExtra["callback"]) ? $composerExtra["callback"] : ""; $componentDir = Config::getOption("componentDir"); self::parseComponentList($name,$pathDist,$componentDir."/".$name,$composerExtra["dist"]["componentDir"],$templateExtension,$onready,$callback); self::parseFileList($name,$pathDist,$componentDir."/".$name,$composerExtra["dist"]["componentDir"]); } // see if we need to modify the config if (isset($composerExtra["config"])) { foreach ($composerExtra["config"] as $option => $value) { // update the config option Config::updateConfigOption($option,$value); } } }
Parse the extra section from composer.json @param {Object} the JSON for the composer extra section
entailment
protected static function parseComponentList($packageName,$sourceBase,$destinationBase,$componentFileList,$templateExtension,$onready,$callback) { /* iterate over a source or source dirs and copy files into the componentdir. use file extensions to add them to the appropriate type arrays below. so... "patternlab": { "dist": { "componentDir": { { "*": "*" } } } "onready": "" "callback": "" "templateExtension": "" } } */ // decide how to type list files. the rules: // src ~ dest -> action // * ~ * -> iterate over all files in {srcroot}/ and create a type listing // foo/* ~ path/* -> iterate over all files in {srcroot}/foo/ and create a type listing // foo/s.html ~ path/k.html -> create a type listing for {srcroot}/foo/s.html // set-up component types store $componentTypes = array("stylesheets" => array(), "javascripts" => array(), "templates" => array()); // iterate over the file list foreach ($componentFileList as $componentItem) { // retrieve the source & destination $source = self::removeDots(key($componentItem)); $destination = self::removeDots($componentItem[$source]); if (($source == "*") || ($source[strlen($source)-1] == "*")) { // build the source & destination $source = (strlen($source) > 2) ? rtrim($source,"/*") : ""; $destination = (strlen($destination) > 2) ? rtrim($destination,"/*") : ""; // get files $finder = new Finder(); $finder->files()->in($sourceBase.$source); // iterate over the returned objects foreach ($finder as $file) { $ext = $file->getExtension(); $pathName = $file->getPathname(); if ($ext == "css") { $componentTypes["stylesheets"][] = str_replace(DIRECTORY_SEPARATOR,"/",str_replace($sourceBase.$source,$destination,$pathName)); } else if ($ext == "js") { $componentTypes["javascripts"][] = str_replace(DIRECTORY_SEPARATOR,"/",str_replace($sourceBase.$source,$destination,$pathName)); } else if ($ext == $templateExtension) { $componentTypes["templates"][] = str_replace(DIRECTORY_SEPARATOR,"/",str_replace($sourceBase.$source,$destination,$pathName)); } } } else { $bits = explode(".",$source); if (count($bits) > 0) { $ext = $bits[count($bits)-1]; if ($ext == "css") { $componentTypes["stylesheets"][] = $destination; } else if ($ext == "js") { $componentTypes["javascripts"][] = $destination; } else if ($ext == $templateExtension) { $componentTypes["templates"][] = $destination; } } } } /* FOR USE AS A PACKAGE TO BE LOADED LATER { "name": "pattern-lab-plugin-kss", "templates": { "filename": "filepath" }, // replace slash w/ dash in filename. replace extension "stylesheets": [ ], "javascripts": [ ], "onready": "", "callback": "" } */ $packageInfo = array(); $packageInfo["name"] = $packageName; $packageInfo["templates"] = array(); foreach ($componentTypes["templates"] as $templatePath) { $templateKey = preg_replace("/\W/","-",str_replace(".".$templateExtension,"",$templatePath)); $packageInfo["templates"][$templateKey] = $templatePath; } $packageInfo["stylesheets"] = $componentTypes["stylesheets"]; $packageInfo["javascripts"] = $componentTypes["javascripts"]; $packageInfo["onready"] = $onready; $packageInfo["callback"] = $callback; $packageInfoPath = Config::getOption("componentDir")."/packages/".str_replace("/","-",$packageName).".json"; // double-check the dirs are created if (!is_dir(Config::getOption("componentDir"))) { mkdir(Config::getOption("componentDir")); } if (!is_dir(Config::getOption("componentDir")."/packages/")) { mkdir(Config::getOption("componentDir")."/packages/"); } // write out the package info file_put_contents($packageInfoPath,json_encode($packageInfo)); }
Parse the component types to figure out what needs to be added to the component JSON files @param {String} the name of the package @param {String} the base directory for the source of the files @param {String} the base directory for the destination of the files (publicDir or sourceDir) @param {Array} the list of files to be parsed for component types @param {String} template extension for templates @param {String} the javascript to run on ready @param {String} the javascript to run as a callback
entailment
protected static function parseFileList($packageName,$sourceBase,$destinationBase,$fileList) { foreach ($fileList as $fileItem) { // retrieve the source & destination $source = self::removeDots(key($fileItem)); $destination = self::removeDots($fileItem[$source]); // depending on the source handle things differently. mirror if it ends in /* self::moveFiles($source,$destination,$packageName,$sourceBase,$destinationBase); } }
Move the files from the package to their location in the public dir or source dir @param {String} the name of the package @param {String} the base directory for the source of the files @param {String} the base directory for the destintation of the files (publicDir or sourceDir) @param {Array} the list of files to be moved
entailment
protected static function pathExists($packageName,$path) { $fs = new Filesystem; if ($fs->exists($path)) { // set-up a human readable prompt $humanReadablePath = str_replace(Config::getOption("baseDir"), "./", $path); // set if the prompt should fire $prompt = true; // are we checking a directory? if (is_dir($path)) { // see if the directory is essentially empty $files = scandir($path); foreach ($files as $key => $file) { $ignore = array("..",".",".gitkeep","README",".DS_Store","patternlab-components"); $file = explode("/",$file); if (in_array($file[count($file)-1],$ignore)) { unset($files[$key]); } } if (empty($files)) { $prompt = false; } } if ($prompt) { // prompt for input using the supplied query $prompt = "the path <path>".$humanReadablePath."</path> already exists. merge or replace with the contents of <path>".$packageName."</path> package?"; $options = "M/r"; $input = Console::promptInput($prompt,$options,"M"); if ($input == "m") { Console::writeTag("ok","contents of <path>".$humanReadablePath."</path> have been merged with the package's content...", false, true); return false; } else { Console::writeWarning("contents of <path>".$humanReadablePath."</path> have been replaced by the package's content...", false, true); return true; } } return false; } return false; }
Check to see if the path already exists. If it does prompt the user to double-check it should be overwritten @param {String} the package name @param {String} path to be checked @return {Boolean} if the path exists and should be overwritten
entailment
protected static function promptStarterKitInstall($starterKitSuggestions) { Console::writeLine(""); // suggest starterkits Console::writeInfo("suggested starterkits that work with this edition:", false, true); foreach ($starterKitSuggestions as $i => $suggestion) { $num = $i + 1; Console::writeLine($num.": ".$suggestion, true); } // prompt for input on the suggestions Console::writeLine(""); $prompt = "choose an option or hit return to skip:"; $options = "(ex. 1)"; $input = Console::promptInput($prompt,$options,"1"); $result = (int)$input - 1; if (isset($starterKitSuggestions[$result])) { Console::writeLine(""); $f = new Fetch(); $result = $f->fetchStarterKit($starterKitSuggestions[$result]); } }
Prompt the user to install a starterkit @param {Array} the starterkit suggestions
entailment
protected static function removeDots($path) { $parts = array(); foreach (explode("/", $path) as $chunk) { if ((".." !== $chunk) && ("." !== $chunk) && ("" !== $chunk)) { $parts[] = $chunk; } } return implode("/", $parts); }
Remove dots from the path to make sure there is no file system traversal when looking for or writing files @param {String} the path to check and remove dots @return {String} the path minus dots
entailment
protected static function packagesInstall($installerInfo, $event) { // mark if this is an interactive call or not self::$isInteractive = $event->getIO()->isInteractive(); // initialize a bunch of stuff like config and console self::init(); // reorder packages so the starterkit is first if it's being installed as a package if (isset($installerInfo["packages"])) { $packages = $installerInfo["packages"]; $packages = array_merge(array_filter($packages, "self::includeStarterKit"), array_filter($packages, "self::excludeStarterKit")); foreach ($packages as $package) { // set-up package info $extra = $package["extra"]; $type = $package["type"]; $name = $package["name"]; $pathBase = $package["pathBase"]; $pathDist = $package["pathDist"]; // make sure that it has the name-spaced section of data to be parsed. if it exists parse it if (!empty($extra)) { self::parseComposerExtraList($extra, $name, $pathDist); } // see if the package has a listener self::scanForListener($pathBase); // address other specific needs based on type if ($type == "patternlab-patternengine") { self::scanForPatternEngineRule($pathBase); } else if (($type == "patternlab-styleguidekit") && (strpos($name,"-assets-") === false)) { $dir = str_replace(Config::getOption("baseDir"), "", $pathBase); $dir = ($dir[strlen($dir)-1] == DIRECTORY_SEPARATOR) ? rtrim($dir, DIRECTORY_SEPARATOR) : $dir; Config::updateConfigOption("styleguideKit",$name); Config::updateConfigOption("styleguideKitPath",$dir); } } } // make sure user is prompted to install starterkit if (!empty($installerInfo["suggestedStarterKits"])) { self::promptStarterKitInstall($installerInfo["suggestedStarterKits"]); } // override any configs that have been set-up if (!empty($installerInfo["configOverrides"])) { foreach ($installerInfo["configOverrides"] as $option => $value) { Config::updateConfigOption($option,$value, true); // forces the update } } if ($installerInfo["projectInstall"]) { Console::writeLine(""); Console::writeLine("<h1><fire3>Thank you for installing...</fire3></h1>", false, true); Console::writeLine("<fire1>( ( </fire1>"); Console::writeLine("<fire2>)\ ) ) ) )\ ) )</fire2>"); Console::writeLine("<fire3>(()/( ) ( /(( /( ( ( (()/( ) ( /(</fire3>"); Console::writeLine("<fire4>/(_)| /( )\())\())))\ )( ( /(_))( /( )\())</fire4>"); Console::writeLine("<fire5>(</fire5><cool>_</cool><fire5>)) )(_)|</fire5><cool>_</cool><fire5>))(</fire5><cool>_</cool><fire5>))//((_|()\ )\ )(</fire5><cool>_</cool><fire5>)) )(_)|(_)\</fire5>"); Console::writeLine("<cool>| _ </cool><fire6>((</fire6><cool>_</cool><fire6>)</fire6><cool>_| |_| |_</cool><fire6>(</fire6><cool>_</cool><fire6>)) ((</fire6><cool>_</cool><fire6>)</fire6><cool>_</cool><fire6>(</fire6><cool>_</cool><fire6>/(</fire6><cool>| | </cool><fire6>((</fire6><cool>_</cool><fire6>)</fire6><cool>_| |</cool><fire6>(</fire6><cool>_</cool><fire6>)</fire6>"); Console::writeLine("<cool>| _/ _` | _| _/ -_)| '_| ' \</cool><fire6>))</fire6><cool> |__/ _` | '_ \ </cool>"); Console::writeLine("<cool>|_| \__,_|\__|\__\___||_| |_||_||____\__,_|_.__/ </cool>", false, true); } }
Handle some Pattern Lab specific tasks based on what's found in the package's composer.json file on install @param {Array} the info culled from installing various pattern lab-related packages
entailment
public static function packageRemove($packageInfo) { // run the console and config inits self::init(); // see if the package has a listener and remove it self::scanForListener($packageInfo["pathBase"],true); // see if the package is a pattern engine and remove the rule if ($packageInfo["type"] == "patternlab-patternengine") { self::scanForPatternEngineRule($packageInfo["pathBase"],true); } // remove the component package file if it exists $jsonFile = Config::getOption("componentDir")."/packages/".str_replace("/","-",$packageInfo["name"]).".json"; if (file_exists($jsonFile)) { unlink($jsonFile); } }
Handle some Pattern Lab specific tasks based on what's found in the package's composer.json file on uninstall @param {Array} the info culled from a pattern lab-related package that's being removed
entailment
protected static function scanForListener($pathPackage,$remove = false) { // get listener list path $pathList = Config::getOption("configDir")."/listeners.json"; // make sure listeners.json exists. if not create it if (!file_exists($pathList)) { file_put_contents($pathList, "{ \"listeners\": [ ] }"); } // load listener list $listenerList = json_decode(file_get_contents($pathList),true); // set-up a finder to find the listener $finder = new Finder(); $finder->files()->name('PatternLabListener.php')->in($pathPackage); // iterate over the returned objects foreach ($finder as $file) { // create the name $classes = self::findClasses($file->getPathname()); $listenerName = "\\".$classes[0]; // check to see what we should do with the listener info if (!$remove && !in_array($listenerName,$listenerList["listeners"])) { $listenerList["listeners"][] = $listenerName; } else if ($remove && in_array($listenerName,$listenerList["listeners"])) { $key = array_search($listenerName, $listenerList["listeners"]); unset($listenerList["listeners"][$key]); } // write out the listener list file_put_contents($pathList,json_encode($listenerList)); } }
Scan the package for a listener @param {String} the path for the package
entailment
protected static function scanForPatternEngineRule($pathPackage,$remove = false) { // get listener list path $pathList = Config::getOption("configDir")."/patternengines.json"; // make sure patternengines.json exists. if not create it if (!file_exists($pathList)) { file_put_contents($pathList, "{ \"patternengines\": [ ] }"); } // load pattern engine list $patternEngineList = json_decode(file_get_contents($pathList),true); // set-up a finder to find the pattern engine $finder = new Finder(); $finder->files()->name("PatternEngineRule.php")->in($pathPackage); // iterate over the returned objects foreach ($finder as $file) { // create the name $classes = self::findClasses($file->getPathname()); $patternEngineName = "\\".$classes[0]; // check what we should do with the pattern engine info if (!$remove && !in_array($patternEngineName, $patternEngineList["patternengines"])) { $patternEngineList["patternengines"][] = $patternEngineName; } else if ($remove && in_array($patternEngineName, $patternEngineList["patternengines"])) { $key = array_search($patternEngineName, $patternEngineList["patternengines"]); unset($patternEngineList["patternengines"][$key]); } // write out the pattern engine list file_put_contents($pathList,json_encode($patternEngineList)); } }
Scan the package for a pattern engine rule @param {String} the path for the package
entailment
public function setSlugAttribute($value) { array_set($this->attributes, $this->getSlugKey(), $this->makeSlug($value)); }
Mutate the value to a slug format and assign to the sluggable key. @param string $value
entailment
public function getDates() { $defaults = [static::CREATED_AT, static::UPDATED_AT, $this->getDeletedAtColumn()]; return array_merge($this->dates, $defaults); }
Get the attributes that should be converted to dates. Overwriting this method here allows the developer to extend the dates using the $dates property without needing to maintain the "deleted_at" column. @return array
entailment
public static function checkPathFromConfig($path, $configPath, $configOption = "") { if (!isset($path)) { Console::writeError("please make sure ".$configOption." is set in <path>".Console::getHumanReadablePath($configPath)."</path> by adding '".$configOption."=some/path'. sorry, stopping pattern lab... :("); } else if (!is_dir($path)) { Console::writeWarning("i can't seem to find the directory <path>".Console::getHumanReadablePath($path)."</path>..."); self::makeDir($path); Console::writeWarning("i created <path>".Console::getHumanReadablePath($path)."</path> just in case. you can edit this in <path>".Console::getHumanReadablePath($configPath)."</path> by editing ".$configOption."..."); } }
Check that a dir from the config exists and try to build it if needed @param {String} directory to be checked/built @param {String} the config path @param {String} the config option that would help them
entailment
public static function makeDir($dir) { $fs = new Filesystem(); try { $fs->mkdir($dir); } catch (IOExceptionInterface $e) { Console::writeError("an error occurred while creating your directory at <path>".$e->getPath()."</path>..."); } unset($fs); }
Make a directory @param {String} directory to be made
entailment
protected static function moveFile($s,$p) { // default vars $sourceDir = Config::getOption("sourceDir"); $publicDir = Config::getOption("publicDir"); $fs = new Filesystem(); $fs->copy($sourceDir.DIRECTORY_SEPARATOR.$s,$publicDir.DIRECTORY_SEPARATOR.$p); }
Copies a file from the given source path to the given public path. THIS IS NOT FOR PATTERNS @param {String} the source file @param {String} the public file
entailment
public static function moveStaticFile($fileName,$copy = "", $find = "", $replace = "") { self::moveFile($fileName,str_replace($find, $replace, $fileName)); Util::updateChangeTime(); if ($copy != "") { Console::writeInfo($fileName." ".$copy."..."); } }
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
entailment
public static function ignoreDir($fileName) { $id = Config::getOption("id"); foreach ($id as $dir) { $pos = strpos(DIRECTORY_SEPARATOR.$fileName,DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR); if ($pos !== false) { return true; } } return false; }
Check to see if a given filename is in a directory that should be ignored @param {String} file name to be checked @return {Boolean} whether the directory should be ignored
entailment
public static function cleanExport() { // default var $exportDir = Config::getOption("exportDir"); if (is_dir($exportDir)) { $files = scandir($exportDir); foreach ($files as $file) { if (($file == "..") || ($file == ".")) { array_shift($files); } else { $key = array_keys($files,$file); $files[$key[0]] = $exportDir.DIRECTORY_SEPARATOR.$file; } } $fs = new Filesystem(); $fs->remove($files); } }
Delete everything in export/
entailment
public static function cleanPublic() { // set-up the dispatcher $dispatcherInstance = Dispatcher::getInstance(); // dispatch that the data gather has started $dispatcherInstance->dispatch("fileUtil.cleanPublicStart"); // default var $patternPublicDir = Config::getOption("patternPublicDir"); // make sure patterns exists before trying to clean it if (is_dir($patternPublicDir)) { // symfony finder doesn't support child first and I don't want to do array crap $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($patternPublicDir), \RecursiveIteratorIterator::CHILD_FIRST); // make sure dots are skipped $objects->setFlags(\FilesystemIterator::SKIP_DOTS); // for each file figure out what to do with it foreach ($objects as $name => $object) { if ($object->isDir()) { // if this is a directory remove it rmdir($name); } else if ($object->isFile() && ($object->getFilename() != "README")) { // if this is a file remove it unlink($name); } } } // scan source/ & public/ to figure out what directories might need to be cleaned up $publicDir = Config::getOption("publicDir"); $sourceDir = Config::getOption("sourceDir"); $publicDirs = glob($publicDir.DIRECTORY_SEPARATOR."*",GLOB_ONLYDIR); $sourceDirs = glob($sourceDir.DIRECTORY_SEPARATOR."*",GLOB_ONLYDIR); // make sure some directories aren't deleted $ignoreDirs = array("styleguide","patternlab-components"); foreach ($ignoreDirs as $ignoreDir) { $key = array_search($publicDir.DIRECTORY_SEPARATOR.$ignoreDir,$publicDirs); if ($key !== false){ unset($publicDirs[$key]); } } // compare source dirs against public. remove those dirs w/ an underscore in source/ from the public/ list foreach ($sourceDirs as $dir) { $cleanDir = str_replace($sourceDir.DIRECTORY_SEPARATOR,"",$dir); if ($cleanDir[0] == "_") { $key = array_search($publicDir.DIRECTORY_SEPARATOR.str_replace("_","",$cleanDir),$publicDirs); if ($key !== false){ unset($publicDirs[$key]); } } } // for the remaining dirs in public delete them and their files foreach ($publicDirs as $dir) { // symfony finder doesn't support child first and I don't want to do array crap $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::CHILD_FIRST); // make sure dots are skipped $objects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($objects as $name => $object) { if ($object->isDir()) { rmdir($name); } else if ($object->isFile()) { unlink($name); } } rmdir($dir); } $dispatcherInstance->dispatch("fileUtil.cleanPublicEnd"); }
Delete patterns and user-created directories and files in public/
entailment
public static function exportStatic() { // default vars $exportDir = Config::getOption("exportDir"); $publicDir = Config::getOption("publicDir"); $sourceDir = Config::getOption("sourceDir"); if (!is_dir($exportDir)) { mkdir($exportDir); } if (is_dir($publicDir)) { // decide which files in public should def. be ignored $ignore = array("annotations","data","patterns","styleguide","index.html","latest-change.txt",".DS_Store",".svn","README"); $files = scandir($publicDir); foreach ($files as $key => $file) { if (($file == "..") || ($file == ".")) { unset($files[$key]); } else if (in_array($file,$ignore)) { unset($files[$key]); } else if (is_dir($publicDir.DIRECTORY_SEPARATOR.$file) && !is_dir($sourceDir.DIRECTORY_SEPARATOR.$file)) { unset($files[$key]); } else if (is_file($publicDir.DIRECTORY_SEPARATOR.$file) && !is_file($sourceDir.DIRECTORY_SEPARATOR.$file)) { unset($files[$key]); } } $fs = new Filesystem(); foreach ($files as $file) { if (is_dir($publicDir.DIRECTORY_SEPARATOR.$file)) { $fs->mirror($publicDir.DIRECTORY_SEPARATOR.$file,$exportDir.DIRECTORY_SEPARATOR.$file); } else if (is_file($publicDir.DIRECTORY_SEPARATOR.$file)) { $fs->copy($publicDir.DIRECTORY_SEPARATOR.$file,$exportDir.DIRECTORY_SEPARATOR.$file); } } } }
moves user-generated static files from public/ to export/
entailment
public static function findCommand($args) { $args = explode("|",$args); foreach ($args as $arg) { if (isset(self::$options[$arg])) { return true; } } return false; }
See if a particular command was passed to the script via the command line and return a boolean. Can either be the short or long version @param {String} list of arguments to check @return {Boolean} if the command has been passed to the script via the command line
entailment
public static function findCommandValue($args) { $args = explode("|",$args); foreach ($args as $arg) { if (isset(self::$options[$arg])) { return self::$options[$arg]; } } return false; }
See if a particular command was passed to the script via the command line and return a value. Can either be the short or long version @param {String} list of arguments to check @return {String} the value that was passed via the command line
entailment
public static function findCommandLong($arg) { foreach (self::$commands as $command => $commandOptions) { if (($commandOptions["commandLong"] == $arg) || ($commandOptions["commandShort"] == $arg)) { return $command; } } return false; }
Find the short command for a given long gommand @param {String} long command to search for @return {String} the search command
entailment
public static function getCommand() { foreach (self::$commands as $command => $attributes) { if (isset(self::$options[$command]) || isset(self::$options[$attributes["commandShort"]])) { return $command; } } return false; }
Return the command that was given in the command line arguments @return {String} the command. passes false if no command was found
entailment
public static function getPathPHP() { $manualPHP = Config::getOption("phpBin"); $autoPHP = new PhpExecutableFinder(); $path = $manualPHP ? $manualPHP : $autoPHP->find(); if (!$path) { $configPath = Console::getHumanReadablePath(Config::getOption("configPath")); $examplePHP = (DIRECTORY_SEPARATOR === "/") ? "C:\wamp\bin\php\php5.5.12" : "/opt/local/lib/php54"; Console::writeError("can't find PHP. add the path to PHP by adding the option \"phpBin\" to <path>".$configPath."</path>. it should look like \"phpBin\": \"".$examplePHP."\""); } return $path; }
Get the path to PHP binary @return {String} the path to the PHP executable
entailment
public static function getPathConsole() { $console = isset($_SERVER["SCRIPT_NAME"]) ? $_SERVER["SCRIPT_NAME"] : Config::getOption("phpScriptName"); if (!$console) { $configPath = Console::getHumanReadablePath(Config::getOption("configPath")); Console::writeError("please add the option `phpScriptName` with the path to your console option (e.g. core".DIRECTORY_SEPARATOR."console) to <path>".$configPath."</path> to run this process..."); } return Config::getOption("baseDir").$console; }
Get the path to the calling script. Should be core/console but let's not make that assumption @return {String} the path to the calling script
entailment
public static function loadCommands() { foreach (glob(__DIR__."/Console/Commands/*.php") as $filename) { $command = str_replace(".php","",str_replace(__DIR__."/Console/Commands/","",$filename)); if ($command[0] != "_") { $commandClass = "\PatternLab\Console\Commands\\".$command; self::$commandInstances[] = new $commandClass(); } } }
Load all of the rules related to Pattern Data
entailment
public static function setCommand($long,$desc,$help,$short = "") { if (!empty($short)) { self::$optionsShort .= $short; } self::$optionsLong[] = $long; $short = str_replace(":","",$short); $long = str_replace(":","",$long); self::$commands[$long] = array("commandShort" => $short, "commandLong" => $long, "commandLongLength" => strlen($long), "commandDesc" => $desc, "commandHelp" => $help, "commandOptions" => array(), "commandExamples" => array()); }
Set-up the command so it can be used from the command line @param {String} the single character version of the command @param {String} the long version of the command @param {String} the description to be used in the "available commands" section of writeHelp() @param {String} the description to be used in the "help" section of writeHelpCommand()
entailment
public static function setCommandSample($command,$sample,$extra) { $command = str_replace(":","",$command); self::$commands[$command]["commandExamples"][] = array("exampleSample" => $sample, "exampleExtra" => $extra); }
Set a sample for a specific command @param {String} the long version of the command that this option is related to @param {String} the sample to be used in the "sample" section of writeHelpCommand() @param {String} the extra info to be used in the example command for the "sample" section of writeHelpCommand()
entailment
public static function setCommandOption($command,$long,$desc,$sample,$short = "",$extra = "") { if (($short != "") && ($short != "z") && (strpos(self::$optionsShort,$short) === false)) { self::$optionsShort .= $short; } if (!in_array($long,self::$optionsLong)) { self::$optionsLong[] = $long; } $short = str_replace(":","",$short); $long = str_replace(":","",$long); if ($short == "z") { $short = "z".self::$zTracker; self::$zTracker++; } self::$commands[$command]["commandOptions"][$long] = array("optionShort" => $short, "optionLong" => $long, "optionLongLength" => strlen($long), "optionDesc" => $desc, "optionSample" => $sample, "optionExtra" => $extra); }
Set-up an option for a given command so it can be used from the command line @param {String} the long version of the command that this option is related to @param {String} the long version of the option @param {String} the description to be used in the "available options" section of writeHelpCommand() @param {String} the sample to be used in the "sample" section of writeHelpCommand() @param {String} the single character version of the option @param {String} the extra info to be used in the example command for the "sample" section of writeHelpCommand()
entailment
public static function writeHelp() { /* The generic help follows this format: Pattern Lab Console Options Usage: php core/console command [options] Available commands: --build (-b) Build Pattern Lab --watch (-w) Build Pattern Lab and watch for changes and rebuild as necessary --version (-v) Display the version number --help (-h) Display this help message. */ // find length of longest command $lengthLong = 0; foreach (self::$commands as $command => $attributes) { $lengthLong = ($attributes["commandLongLength"] > $lengthLong) ? $attributes["commandLongLength"] : $lengthLong; } // write out the generic usage info self::writeLine(""); self::writeLine("<h1>Pattern Lab Console Options</h1>",true,true); self::writeLine("<h2>Usage</h2>:",true,true); self::writeLine(" php ".self::$self." command <optional>[options]</optional>",true,true); self::writeLine("<h2>Available commands</h2>:",true,true); // write out the commands foreach (self::$commands as $command => $attributes) { $spacer = self::getSpacer($lengthLong,$attributes["commandLongLength"]); self::writeLine(" --".$attributes["commandLong"].$spacer." <desc>".$attributes["commandDesc"]."</desc>",true); } // write out how to get more help self::writeLine(""); self::writeLine("<h2>Get options for a specific command:</h2>",true,true); self::writeLine(" php ".self::$self." --help --command",true); self::writeLine(""); }
Write out the generic help
entailment
public static function writeHelpCommand($command = "") { /* The command help follows this format: Build Command Options Usage: php core/console --build [--patternsonly|-p] [--nocache|-n] [--enablecss|-c] Available options: --patternsonly (-p) Build only the patterns. Does NOT clean public/. --nocache (-n) Set the cacheBuster value to 0. --enablecss (-c) Generate CSS for each pattern. Resource intensive. --help (-h) Display this help message. Help: The build command builds an entire site a single time. It compiles the patterns and moves content from source/ into public/ Samples: To run and generate the CSS for each pattern: php core/console --build -c To build only the patterns and not move other files from source/ to public/ php core/console --build -p To turn off the cacheBuster php core/console --build -n */ // if given an empty command or the command doesn't exist in the lists give the generic help if (empty($command)) { self::writeHelp(); return; } $commandLong = self::$commands[$command]["commandLong"]; $commandLongUC = ucfirst($commandLong); $commandHelp = self::$commands[$command]["commandHelp"]; $commandExtra = isset(self::$commands[$command]["commandExtra"]) ? self::$commands[$command]["commandExtra"] : ""; $commandOptions = self::$commands[$command]["commandOptions"]; $commandExamples = self::$commands[$command]["commandExamples"]; $commandShort = self::$commands[$command]["commandShort"]; $commandShortInc = ($commandShort != "") ? "|-".$commandShort : ""; // write out the option list and get the longest item $optionList = ""; $lengthLong = 0; foreach ($commandOptions as $option => $attributes) { $optionShort = (!empty($attributes["optionShort"][0]) && (($attributes["optionShort"][0] != "z") || ($attributes["optionShort"] != ""))) ? "|-".$attributes["optionShort"] : ""; $optionExtra = (!empty($attributes["optionExtra"])) ? " ".$attributes["optionExtra"] : ""; $optionList .= "[--".$attributes["optionLong"].$optionShort.$optionExtra."] "; $lengthLong = ($attributes["optionLongLength"] > $lengthLong) ? $attributes["optionLongLength"] : $lengthLong; } $commandExampleList = ""; if (count($commandExamples) > 0) { foreach ($commandExamples as $example => $attributes) { $commandExampleList .= $attributes["exampleExtra"]." "; } } // write out the generic usage info self::writeLine(""); self::writeLine("<h1>".$commandLongUC." Command Options</h1>",true,true); self::writeLine("<h2>Usage</h2>:",true,true); self::writeLine(" php ".self::$self." --".$commandLong.$commandShortInc." ".$optionList,true,true); // write out the available options if (count($commandOptions) > 0) { self::writeLine("<h2>Available options</h2>:",true,true); foreach ($commandOptions as $option => $attributes) { $optionShort = (!empty($attributes["optionShort"]) && (($attributes["optionShort"][0] != "z") || ($attributes["optionShort"] != ""))) ? "(-".$attributes["optionShort"].")" : " "; $spacer = self::getSpacer($lengthLong,$attributes["optionLongLength"]); self::writeLine(" --".$attributes["optionLong"].$spacer.$optionShort." <desc>".$attributes["optionDesc"]."</desc>",true); } self::writeLine(""); } self::writeLine("<h2>Help</h2>:",true,true); self::writeLine(" ".$commandHelp,true,true); // write out the samples if ((count($commandOptions) > 0) || (count($commandExamples) > 0)) { self::writeLine("<h2>Samples</h2>:",true,true); } if (count($commandExamples) > 0) { foreach ($commandExamples as $example => $attributes) { self::writeLine(" ".$attributes["exampleSample"],true,true); self::writeLine(" <desc>php ".self::$self." --".$commandLong." ".$attributes["exampleExtra"]."</desc>",true,true); } } if (count($commandOptions) > 0) { foreach ($commandOptions as $option => $attributes) { self::writeLine(" ".$attributes["optionSample"],true,true); self::writeLine(" <desc>php ".self::$self." --".$commandLong." --".$attributes["optionLong"]." ".$attributes["optionExtra"]."</desc>",true,true); } } }
Write out the command-specific help @param {String} the single character of the command that this option is related to
entailment
public static function getSpacer($lengthLong,$itemLongLength) { $i = 0; $spacer = " "; $spacerLength = $lengthLong - $itemLongLength; while ($i < $spacerLength) { $spacer .= " "; $i++; } return $spacer; }
Make sure the space is properly set between long command options and short command options @param {Integer} the longest length of the command's options @param {Integer} the character length of the given option
entailment
public static function addTags($line,$tag) { $lineFinal = "<".$tag.">".preg_replace("/<[A-z0-9-_]{1,}>[^<]{1,}<\/[A-z0-9-_]{1,}>/","</".$tag.">$0<".$tag.">",$line)."</".$tag.">"; return $lineFinal; }
Modify a line to include the given tag by default @param {String} the content to be written out
entailment
public static function writeError($line,$doubleSpace = false,$doubleBreak = false) { $lineFinal = self::addTags($line,"error"); self::writeLine($lineFinal,$doubleSpace,$doubleBreak); exit(1); }
Write out a line to the console with error tags. It forces an exit of the script @param {String} the content to be written out @param {Boolean} if there should be two spaces added to the beginning of the line @param {Boolean} if there should be two breaks added to the end of the line
entailment
public static function writeInfo($line,$doubleSpace = false,$doubleBreak = false) { $lineFinal = self::addTags($line,"info"); self::writeLine($lineFinal,$doubleSpace,$doubleBreak); }
Write out a line to the console with info tags @param {String} the content to be written out @param {Boolean} if there should be two spaces added to the beginning of the line @param {Boolean} if there should be two breaks added to the end of the line
entailment
public static function log($line,$doubleSpace = false,$doubleBreak = false) { self::writeInfo($line,$doubleSpace = false,$doubleBreak = false); }
Alias for writeInfo because I keep wanting to use it @param {String} the content to be written out @param {Boolean} if there should be two spaces added to the beginning of the line @param {Boolean} if there should be two breaks added to the end of the line
entailment
public static function writeLine($line,$doubleSpace = false,$doubleBreak = false) { $break = ($doubleBreak) ? PHP_EOL.PHP_EOL : PHP_EOL; if (strpos($line,"<nophpeol>") !== false) { $break = ""; $line = str_replace("<nophpeol>","",$line); } $space = ($doubleSpace) ? " " : ""; $c = self::$color; print $space.$c($line)->colorize().$break; }
Write out a line to the console @param {String} the content to be written out @param {Boolean} if there should be two spaces added to the beginning of the line @param {Boolean} if there should be two breaks added to the end of the line
entailment
public static function writeTag($tag,$line,$doubleSpace = false,$doubleBreak = false) { $lineFinal = self::addTags($line,$tag); self::writeLine($lineFinal,$doubleSpace,$doubleBreak); }
Write out a line to the console with a specific tag @param {String} the tag to add to the line @param {String} the content to be written out @param {Boolean} if there should be two spaces added to the beginning of the line @param {Boolean} if there should be two breaks added to the end of the line
entailment
public static function promptInput($prompt = "", $options = "", $default = "", $lowercase = true, $tag = "info") { // check prompt if (empty($prompt)) { Console::writeError("an input prompt requires prompt text..."); } // if there are suggested options add them if (!empty($options)) { $prompt .= " <options>".$options."</options> >"; } // make sure no end-of-line is added $prompt .= " <nophpeol>"; // make sure we're not running in no interaction mode. if so just use the default for the input if (InstallerUtil::$isInteractive) { // open the terminal and wait for feedback $stdin = fopen("php://stdin", "r"); Console::writeTag($tag,$prompt); $input = trim(fgets($stdin)); fclose($stdin); } else { $input = $default; } // check to see if it should be lowercased before sending back return ($lowercase) ? strtolower($input) : $input; }
Prompt the user for some input @param {String} the text for the prompt @param {String} the text for the options @param {String} the text for the default option @param {Boolean} if we should lowercase the input before sending it back @param {String} the tag that should be used when drawing the content @return {String} trimmed input given by the user
entailment
protected static function loadListeners() { // default var $configDir = Config::getOption("configDir"); // make sure the listener data exists if (file_exists($configDir."/listeners.json")) { // get listener list data $listenerList = json_decode(file_get_contents($configDir."/listeners.json"), true); // get the listener info foreach ($listenerList["listeners"] as $listenerName) { if ($listenerName[0] != "_") { $listener = new $listenerName(); $listeners = $listener->getListeners(); foreach ($listeners as $event => $eventProps) { $eventPriority = (isset($eventProps["priority"])) ? $eventProps["priority"] : 0; self::$instance->addListener($event, array($listener, $eventProps["callable"]), $eventPriority); } } } } }
Load listeners that may be a part of plug-ins that should be notified by the dispatcher
entailment
public function watch($options = array()) { // double-checks options was properly set if (empty($options)) { Console::writeError("need to pass options to generate..."); } // set default attributes $moveStatic = (isset($options["moveStatic"])) ? $options["moveStatic"] : true; $noCacheBuster = (isset($options["noCacheBuster"])) ? $options["noCacheBuster"] : false; // make sure a copy of the given options are saved for using when running generate $this->options = $options; // set-up the Dispatcher $dispatcherInstance = Dispatcher::getInstance(); $dispatcherInstance->dispatch("watcher.start"); if ($noCacheBuster) { Config::setOption("cacheBuster",0); } $c = false; // track that one loop through the pattern file listing has completed $o = new \stdClass(); // create an object to hold the properties $cp = new \stdClass(); // create an object to hold a clone of $o $o->patterns = new \stdClass(); Console::writeLine("watching your site for changes..."); // default vars $publicDir = Config::getOption("publicDir"); $sourceDir = Config::getOption("sourceDir"); $patternSourceDir = Config::getOption("patternSourceDir"); $ignoreExts = Config::getOption("ie"); $ignoreDirs = Config::getOption("id"); $patternExt = Config::getOption("patternExtension"); // build the file extensions based on the rules $fileExtensions = array(); $patternRules = PatternData::getRules(); foreach ($patternRules as $patternRule) { $extensions = $patternRule->getProp("extProp"); if (strpos($extensions,"&&") !== false) { $extensions = explode("&&",$extensions); } else if (strpos($extensions,"||") !== false) { $extensions = explode("||",$extensions); } else { $extensions = array($extensions); } foreach ($extensions as $extension) { if (!in_array($extension, $fileExtensions)) { $fileExtensions[] = $extension; } } } // run forever while (true) { // clone the patterns so they can be checked in case something gets deleted $cp = clone $o->patterns; // iterate over the patterns & related data and regenerate the entire site if they've changed $patternObjects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($patternSourceDir), \RecursiveIteratorIterator::SELF_FIRST); // make sure dots are skipped $patternObjects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($patternObjects as $name => $object) { // clean-up the file name and make sure it's not one of the pattern lab files or to be ignored $fileName = str_replace($patternSourceDir.DIRECTORY_SEPARATOR,"",$name); $fileNameClean = str_replace(DIRECTORY_SEPARATOR."_",DIRECTORY_SEPARATOR,$fileName); if ($object->isFile() && in_array($object->getExtension(), $fileExtensions)) { // make sure this isn't a hidden pattern $patternParts = explode(DIRECTORY_SEPARATOR,$fileName); $pattern = isset($patternParts[2]) ? $patternParts[2] : $patternParts[1]; // make sure the pattern still exists in source just in case it's been deleted during the iteration if (file_exists($name)) { $mt = $object->getMTime(); if (isset($o->patterns->$fileName) && ($o->patterns->$fileName != $mt)) { $o->patterns->$fileName = $mt; $this->updateSite($fileName,"changed"); } else if (!isset($o->patterns->$fileName) && $c) { $o->patterns->$fileName = $mt; $this->updateSite($fileName,"added"); if ($object->getExtension() == $patternExt) { $patternSrcPath = str_replace(".".$patternExt,"",$fileName); $patternDestPath = str_replace("/","-",$patternSrcPath); $render = ($pattern[0] != "_") ? true : false; $this->patternPaths[$patternParts[0]][$pattern] = array("patternSrcPath" => $patternSrcPath, "patternDestPath" => $patternDestPath, "render" => $render); } } else if (!isset($o->patterns->$fileName)) { $o->patterns->$fileName = $mt; } if ($c && isset($o->patterns->$fileName)) { unset($cp->$fileName); } } else { // the file was removed during the iteration so remove references to the item unset($o->patterns->$fileName); unset($cp->$fileName); unset($this->patternPaths[$patternParts[0]][$pattern]); $this->updateSite($fileName,"removed"); } } } // make sure old entries are deleted // will throw "pattern not found" errors if an entire directory is removed at once but that shouldn't be a big deal if ($c) { foreach($cp as $fileName => $mt) { unset($o->patterns->$fileName); $patternParts = explode(DIRECTORY_SEPARATOR,$fileName); $pattern = isset($patternParts[2]) ? $patternParts[2] : $patternParts[1]; unset($this->patternPaths[$patternParts[0]][$pattern]); $this->updateSite($fileName,"removed"); } } // iterate over annotations, data, meta and any other _ dirs $watchDirs = glob($sourceDir.DIRECTORY_SEPARATOR."_*",GLOB_ONLYDIR); foreach ($watchDirs as $watchDir) { if ($watchDir != $patternSourceDir) { // iterate over the data files and regenerate the entire site if they've changed $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($watchDir), \RecursiveIteratorIterator::SELF_FIRST); // make sure dots are skipped $objects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($objects as $name => $object) { $fileName = str_replace($sourceDir.DIRECTORY_SEPARATOR,"",$name); $mt = $object->getMTime(); if (!isset($o->$fileName)) { $o->$fileName = $mt; if ($c) { $this->updateSite($fileName,"added"); } } else if ($o->$fileName != $mt) { $o->$fileName = $mt; if ($c) { $this->updateSite($fileName,"changed"); } } } } } // iterate over all of the other files in the source directory and move them if their modified time has changed if ($moveStatic) { $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($sourceDir.DIRECTORY_SEPARATOR), \RecursiveIteratorIterator::SELF_FIRST); // make sure dots are skipped $objects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($objects as $name => $object) { // clean-up the file name and make sure it's not one of the pattern lab files or to be ignored $fileName = str_replace($sourceDir.DIRECTORY_SEPARATOR,"",$name); if (($fileName[0] != "_") && (!in_array($object->getExtension(),$ignoreExts)) && (!in_array($object->getFilename(),$ignoreDirs))) { // catch directories that have the ignored dir in their path $ignoreDir = FileUtil::ignoreDir($fileName); // check to see if it's a new directory if (!$ignoreDir && $object->isDir() && !isset($o->$fileName) && !is_dir($publicDir."/".$fileName)) { mkdir($publicDir."/".$fileName); $o->$fileName = "dir created"; // placeholder Console::writeLine($fileName."/ directory was created..."); } // check to see if it's a new file or a file that has changed if (file_exists($name)) { $mt = $object->getMTime(); if (!$ignoreDir && $object->isFile() && !isset($o->$fileName) && !file_exists($publicDir."/".$fileName)) { $o->$fileName = $mt; FileUtil::moveStaticFile($fileName,"added"); if ($object->getExtension() == "css") { $this->updateSite($fileName,"changed",0); // make sure the site is updated for MQ reasons } } else if (!$ignoreDir && $object->isFile() && isset($o->$fileName) && ($o->$fileName != $mt)) { $o->$fileName = $mt; FileUtil::moveStaticFile($fileName,"changed"); if ($object->getExtension() == "css") { $this->updateSite($fileName,"changed",0); // make sure the site is updated for MQ reasons } } else if (!isset($o->fileName)) { $o->$fileName = $mt; } } else { unset($o->$fileName); } } } } $c = true; // taking out the garbage. basically killing mustache after each run. if (gc_enabled()) gc_collect_cycles(); // pause for .05 seconds to give the CPU a rest usleep(50000); } }
Watch the source/ directory for any changes to existing files. Will run forever if given the chance. @param {Boolean} decide if the reload server should be turned on @param {Boolean} decide if static files like CSS and JS should be moved
entailment
private function updateSite($fileName,$message,$verbose = true) { $watchMessage = ""; if ($verbose) { if ($message == "added") { $watchMessage = "<warning>".$fileName." was added to Pattern Lab. reload the website to see this change in the navigation...</warning>"; } elseif ($message == "removed") { $watchMessage = "<warning>".$fileName." was removed from Pattern Lab. reload the website to see this change reflected in the navigation...</warning>"; } elseif ($message == "hidden") { $watchMessage = "<warning>".$fileName." was hidden from Pattern Lab. reload the website to see this change reflected in the navigation...</warning>"; } else { $watchMessage = "<info>".$fileName." changed...</info>"; } } $options = $this->options; $options["watchVerbose"] = $verbose; $options["watchMessage"] = $watchMessage; $options["moveStatic"] = false; // clear the various data stores for re-population Data::clear(); PatternData::clear(); Annotations::clear(); $g = new Generator(); $g->generate($options); }
Updates the Pattern Lab Website and prints the appropriate message @param {String} file name to included in the message @param {String} a switch for decided which message isn't printed @return {String} the final message
entailment
protected function getDynamicRelationship($name) { // Dynamically get the relationship if ($this->isRelationship($name)) { // Use the relationship already loaded if (array_key_exists($name, $this->getRelations())) { return $this->getRelation($name); } // Load the relationship return $this->getRelationshipFromMethod($name, camel_case($name)); } }
Get a dynamically resolved relationship. @param string $name @return mixed
entailment
public function getRelationship($name) { // If relationship does not exist throw an exception if ( ! $this->isRelationship($name)) { $exception = new ModelNotFoundException(); $exception->setModel($name); throw $exception; } return $this->relationships[$name]; }
Return the relationship configurations. @param string $name of related model @throws Illuminate\Database\Eloquent\ModelNotFoundException @return array
entailment
protected function callRelationship($name) { // Get the relationship arguments $args = $this->getRelationship($name); // Build the relationship $method = array_shift($args); $relationship = call_user_func_array([$this, $method], $args); // Check to see if this relationship has extended pivot attributes if ($this->hasPivotAttributes($name)) { // Add timestamps to relationship $attributes = $this->getPivotAttributes($name); if (in_array('timestamps', $attributes)) { unset($attributes[array_search('timestamps', $attributes)]); $relationship->withTimestamps(); } // Add the pivot attributes to the relationship $relationship->withPivot($attributes); } return $relationship; }
Proxy call a relationship method using the configuration arguments of the relationship. @param string $name of related model @return mixed
entailment
public function scopeWithout($query, $relations) { $relations = is_array($relations) ? $relations : array_slice(func_get_args(), 1); $relationships = array_dot($query->getEagerLoads()); foreach ($relations as $relation) { unset($relationships[$relation]); } return $query->setEagerLoads([])->with(array_keys($relationships)); }
Set the relationships that should not be eager loaded. @param Illuminate\Database\Query\Builder $query @param mixed $relations @return $this
entailment
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(); } }
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
entailment
protected function moveStatic() { // set-up the dispatcher $dispatcherInstance = Dispatcher::getInstance(); // note the start of the operation $dispatcherInstance->dispatch("generator.moveStaticStart"); // common values $publicDir = Config::getOption("publicDir"); $sourceDir = Config::getOption("sourceDir"); $ignoreExt = Config::getOption("ie"); $ignoreDir = Config::getOption("id"); // iterate over all of the other files in the source directory $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($sourceDir), \RecursiveIteratorIterator::SELF_FIRST); // make sure dots are skipped $objects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($objects as $name => $object) { // clean-up the file name and make sure it's not one of the pattern lab files or to be ignored $fileName = str_replace($sourceDir.DIRECTORY_SEPARATOR,"",$name); if (($fileName[0] != "_") && (!in_array($object->getExtension(),$ignoreExt)) && (!in_array($object->getFilename(),$ignoreDir))) { // catch directories that have the ignored dir in their path $ignored = FileUtil::ignoreDir($fileName); // check to see if it's a new directory if (!$ignored && $object->isDir() && !is_dir($publicDir."/".$fileName)) { mkdir($publicDir."/".$fileName); } // check to see if it's a new file or a file that has changed if (!$ignored && $object->isFile() && (!file_exists($publicDir."/".$fileName))) { FileUtil::moveStaticFile($fileName); } } } // note the end of the operation $dispatcherInstance->dispatch("generator.moveStaticEnd"); }
Move static files from source/ to public/
entailment
public static function hasError() { $error = json_last_error(); $errorMessage = array_key_exists($error, self::$errors) ? self::$errors[$error] : "Unknown error ({$error})"; return $errorMessage; }
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
entailment
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); } }
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
entailment
protected function findLineages($data) { if (preg_match_all("/".$this->lineageMatch."/",$data,$matches)) { return array_unique($matches[$this->lineageMatchKey]); } return array(); }
Get the lineage for a given pattern by parsing it and matching mustache partials @param {String} the data from the raw pattern @return {Array} a list of patterns
entailment
public static function configure() { $config = \BoletoSimples::$configuration; $oauth2 = new Oauth2Subscriber(); $oauth2->setAccessToken($config->access_token); self::$client = new Client([ 'base_url' => $config->baseUri(), 'defaults' => [ 'headers' => [ 'User-Agent' => $config->userAgent() ], 'auth' => 'oauth2', 'subscribers' => [$oauth2] ], 'verify' => false ]); self::$default_options = ['headers' => ['Content-Type'=> 'application/json'], 'exceptions' => false]; }
Configure the GuzzleHttp\Client with default options.
entailment
protected function getDynamicEncrypted($attribute) { // Dynamically get the encrypted attributes if ($this->isEncryptable($attribute)) { // Decrypt only encrypted values if ($this->isEncrypted($attribute)) { return $this->getEncryptedAttribute($attribute); } } }
Get an encrypted attribute dynamically. @param string $attribute @return mixed
entailment
protected function setDynamicEncryptable($attribute, $value) { // Dynamically set the encryptable attribute if ($this->isEncryptable($attribute)) { // Encrypt only decrypted values if ($this->isDecrypted($attribute)) { $this->setEncryptingAttribute($attribute, $value); return true; } } return false; }
Set an encryptable attribute dynamically. @param string $attribute @param mixed $value @return bool
entailment
public function isEncrypted($attribute) { if ( ! array_key_exists($attribute, $this->attributes)) { return false; } try { $this->decrypt(array_get($this->attributes, $attribute)); } catch (DecryptException $exception) { return false; } return true; }
Returns whether the attribute is encrypted. @param string $attribute name @return bool
entailment
public function encryptAttributes() { foreach ($this->getEncryptable() as $attribute) { $this->setEncryptingAttribute($attribute, array_get($this->attributes, $attribute)); } }
Encrypt attributes that should be encrypted.
entailment
public function getEncryptedAttribute($attribute) { $value = array_get($this->attributes, $attribute); return $this->isEncrypted($attribute) ? $this->decrypt($value) : $value; }
Get the decrypted value for an encrypted attribute. @param string $attribute name @return string
entailment
public function setEncryptingAttribute($attribute, $value) { array_set($this->attributes, $attribute, $this->encrypt($value)); }
Set an encrypted value for an encryptable attribute. @param string $attribute name @param string $value to encrypt
entailment
public function migrate($diffVersion = false) { $migrations = new \DirectoryIterator(__DIR__."/../../migrations/"); $migrationsValid = array(); foreach ($migrations as $migration) { $filename = $migration->getFilename(); if (!$migration->isDot() && $migration->isFile() && ($filename[0] != "_")) { $migrationsValid[] = $filename; } } asort($migrationsValid); foreach ($migrationsValid as $filename) { $basePath = __DIR__."/../../../"; $migrationData = json_decode(file_get_contents(__DIR__."/../../migrations/".$filename)); $checkType = $migrationData->checkType; $sourcePath = ($checkType == "fileExists") ? $basePath.$migrationData->sourcePath : $basePath.$migrationData->sourcePath.DIRECTORY_SEPARATOR; $destinationPath = ($checkType == "fileExists") ? $basePath.$migrationData->destinationPath : $basePath.$migrationData->destinationPath.DIRECTORY_SEPARATOR; if ($checkType == "dirEmpty") { $emptyDir = true; $objects = new \DirectoryIterator($destinationPath); foreach ($objects as $object) { if (!$object->isDot() && ($object->getFilename() != "README") && ($object->getFilename() != ".DS_Store")) { $emptyDir = false; } } if ($emptyDir) { $this->runMigration($filename, $sourcePath, $destinationPath, false); } } else if ($checkType == "dirExists") { if (!is_dir($destinationPath)) { mkdir($destinationPath); } } else if ($checkType == "fileExists") { if (!file_exists($destinationPath)) { $this->runMigration($filename, $sourcePath, $destinationPath, true); } } else if (($checkType == "versionDiffDir") && $diffVersion) { // make sure the destination path exists if (!is_dir($destinationPath)) { mkdir($destinationPath); } $this->runMigration($filename, $sourcePath, $destinationPath, false); } else if (($checkType == "versionDiffFile") && $diffVersion) { $this->runMigration($filename, $sourcePath, $destinationPath, true); } else { print "pattern Lab doesn't recognize a checkType of ".$checkType.". The migrator class is pretty thin at the moment.\n"; exit; } } }
Read through the migrations and move files as needed @param {Boolean} is this a different version
entailment
protected function runMigration($filename, $sourcePath, $destinationPath, $singleFile) { $filename = str_replace(".json","",$filename); print "starting the ".$filename." migration...\n"; if ($singleFile) { copy($sourcePath.$fileName,$destinationPath.$fileName); } else { if (strpos($sourcePath,"pattern-lab/") !== false) { $sourcePath = str_replace(__DIR__."/../../../","",rtrim($sourcePath,"/")); $f = new Fetch(); $f->fetch("starterkit",$sourcePath); } else { $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($sourcePath), \RecursiveIteratorIterator::SELF_FIRST); $objects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach ($objects as $object) { // clean-up the file name and make sure it's not one of the pattern lab files or to be ignored $fileName = str_replace($sourcePath,"",$object->getPathname()); // check to see if it's a new directory if ($object->isDir() && !is_dir($destinationPath.$fileName)) { mkdir($destinationPath.$fileName); } else if ($object->isFile()) { copy($sourcePath.$fileName,$destinationPath.$fileName); } } } } print "completed the ".$filename." migration...\n"; }
Run any migrations found in core/migrations that match the approved types @param {String} the filename of the migration @param {String} the path of the source directory @param {String} the path to the destination @param {Boolean} moving a single file or a directory
entailment
public function attributesToCarbon($event) { foreach ($this->attributes as $attribute) { $value = $this->owner->$attribute; if (!empty($value)) { // If this value is an integer, we will assume it is a UNIX timestamp's value // and format a Carbon object from this timestamp. if (is_numeric($value)) { $this->owner->$attribute = Carbon::createFromTimestamp($value); } // If the value is in simply year, month, day format, we will instantiate the // Carbon instances from that format. elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value)) { $this->owner->$attribute = Carbon::createFromFormat('Y-m-d', $value)->startOfDay(); } else { $this->owner->$attribute = Carbon::createFromFormat($this->dateFormat, $this->owner->$attribute); } } } }
Convert the model's attributes to an Carbon instance. @param $event @return static
entailment
public function attributesToDefaultFormat($event) { $oldAttributes = $this->owner->oldAttributes; foreach ($this->attributes as $attribute) { $oldAttributeValue = $oldAttributes[$attribute]; if ($this->owner->$attribute instanceof Carbon) { //If old attribute value is an integer, then we convert the current attribute value to the timestamp for prevent db errors if (is_numeric($oldAttributeValue)) { $this->owner->$attribute = $this->owner->$attribute->timestamp; } } } }
Handles owner 'beforeUpdate' event for converting attributes values to the default format @param $event @return bool
entailment
protected function getDynamicJuggle($key, $value) { if ($this->isJugglable($key)) { return $this->juggle($value, $this->getJuggleType($key)); } return $value; }
If juggling is active, it returns the juggleAttribute. If not it just returns the value as it was passed. @param string $key @param mixed $value @return mixed
entailment
protected function setDynamicJuggle($key, $value) { // Check that the attribute is jugglable if ( ! is_null($value) && $this->isJugglable($key)) { // Cast the value to the type set for the attribute $this->juggleAttribute($key, $value); } }
If juggling is active, it sets the attribute in the model by type juggling the value first. @param string $key @param mixed $value
entailment
public function setJugglable(array $attributes) { // Check that each of the types are indeed jugglable types foreach ($attributes as $attribute => $type) { $this->checkJuggleType($type); } // Set the juggle attributes $this->jugglable = $attributes; }
Set the jugglable attributes. @param array $attributes to juggle @throws InvalidArgumentException
entailment
public function removeJugglable($attributes) { // Make sure we are dealing an associative array if ( ! is_array($attributes)) { $attributes = func_get_args(); } $attributes = array_flip($attributes); // Get the remaining jugglables $jugglables = array_diff_key($this->getJugglable(), $attributes); // Set the remaining jugglables $this->setJugglable($jugglables); }
Remove an attribute or several attributes from the jugglable array. @example removeJugglable( string $attribute, ... ) @param mixed $attributes
entailment
public function isJuggleType($type) { // Construct a normalized juggle method from the type $method = $this->buildJuggleMethod($type); // Any type that does map to a model method is invalid if ( ! method_exists($this, $method)) { return false; } return true; }
Returns whether the type is a type that can be juggled to. @param string $type to cast @return bool
entailment