sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function buildJuggleMethod($type)
{
// Convert type to acceptable pattern
$type = lcfirst(studly_case($type));
// Map the type to it's normalized type
switch ($type) {
case 'bool':
case 'boolean':
$normalizedType = 'boolean';
break;
case 'int':
case 'integer':
$normalizedType = 'integer';
break;
case 'float':
case 'double':
$normalizedType = 'float';
break;
case 'datetime':
case 'dateTime':
$normalizedType = 'dateTime';
break;
case 'date':
case 'timestamp':
case 'string':
case 'array':
default:
$normalizedType = $type;
break;
}
// Construct a dynamic method name
return 'juggle'.studly_case($normalizedType);
} | Build the method name that the type normalizes to.
@param string $type to cast
@return string | entailment |
public function juggleAttributes()
{
// Iterate the juggable fields, and if the field is present
// cast the attribute and replace within the attributes array.
foreach ($this->getJugglable() as $attribute => $type) {
if (isset($this->attributes[$attribute])) {
$this->juggleAttribute($attribute, $this->attributes[$attribute]);
}
}
} | Juggles all attributes that are configured to be juggled. | entailment |
public function juggleAttribute($attribute, $value)
{
$type = $this->getJuggleType($attribute);
$this->attributes[$attribute] = $this->juggle($value, $type);
} | Casts a value to the coresponding attribute type and sets
it on the attributes array of this model.
@param string $attribute
@param string $value | entailment |
public function juggle($value, $type)
{
// Cast non-null values
if ( ! is_null($value)) {
// Ensure that the type is a valid type to cast.
// We do this check here because it might not have been done
// as is the case when the model is first initialized.
if ($this->checkJuggleType($type)) {
// Get the method that the type maps to
$method = $this->buildJuggleMethod($type);
// Cast the value to the type using the method
$value = $this->{$method}($value);
}
}
return $value;
} | Cast the value to the attribute's type as specified in the juggable array.
@param mixed $value
@param string $type
@throws InvalidArgumentException
@return mixed | entailment |
public function purgeAttributes()
{
// Get the attribute keys
$keys = array_keys($this->getAttributes());
// Filter out keys that should purged
$attributes = array_filter($keys, function ($key) {
// Remove attributes that should be purged
if (in_array($key, $this->getPurgeable())) {
return false;
}
// Remove attributes ending with _confirmation
if (Str::endsWith($key, '_confirmation')) {
return false;
}
// Remove attributes starting with _ prefix
if (Str::startsWith($key, '_')) {
return false;
}
return true;
});
// Keep only the attributes that were not purged
$this->attributes = array_intersect_key($this->getAttributes(), array_flip($attributes));
} | Unset attributes that should be purged. | entailment |
protected function setPurgingAndSave($purge)
{
// Set purging state
$purging = $this->getPurging();
$this->setPurging($purge);
// Save the model
$result = $this->save();
// Reset purging back to it's previous state
$this->setPurging($purging);
return $result;
} | Set purging state and then save and then reset it.
@param bool $purge
@return bool | entailment |
private static function compareReplaceListVars($value) {
if (is_string($value) && preg_match("/^link\.([\S]+)$/",$value)) {
$valueCheck = strtolower($value);
$valueThin = str_replace("link.","",$valueCheck);
$linkStore = self::getOption("link");
if ((strpos($valueCheck, 'link.') !== false) && array_key_exists($valueThin,$linkStore)) {
$value = $linkStore[$valueThin];
}
}
return $value;
} | Go through data and replace any values that match items from the link.array
@param {String} a string entry from the data to check for link.pattern
@return {String} replaced version of link.pattern | entailment |
private static function recursiveWalk($array) {
foreach ($array as $k => $v) {
if (is_array($v)) {
$array[$k] = self::recursiveWalk($v);
} else {
$array[$k] = self::compareReplaceListVars($v);
}
}
return $array;
} | Work through a given array and decide if the walk should continue or if we should replace the var
@param {Array} the array to be checked
@return {Array} the "fixed" array | entailment |
public static function gather($options = array()) {
// set-up the dispatcher
$dispatcherInstance = Dispatcher::getInstance();
// dispatch that the data gather has started
$dispatcherInstance->dispatch("data.gatherStart");
// default vars
$found = false;
$dataJSON = array();
$dataYAML = array();
$listItemsJSON = array();
$listItemsYAML = array();
$sourceDir = Config::getOption("sourceDir");
// iterate over all of the other files in the source directory
if (!is_dir($sourceDir."/_data/")) {
Console::writeWarning("<path>_data/</path> doesn't exist so you won't have dynamic data...");
mkdir($sourceDir."/_data/");
}
// find the markdown-based annotations
$finder = new Finder();
$finder->files()->in($sourceDir."/_data/");
$finder->sortByName();
foreach ($finder as $name => $file) {
$ext = $file->getExtension();
$data = array();
$fileName = $file->getFilename();
$hidden = ($fileName[0] == "_");
$isListItems = strpos($fileName,"listitems");
$pathName = $file->getPathname();
$pathNameClean = str_replace($sourceDir."/","",$pathName);
if (!$hidden && (($ext == "json") || ($ext == "yaml") || ($ext == "yml"))) {
if ($isListItems === false) {
if ($ext == "json") {
$file = file_get_contents($pathName);
$data = json_decode($file,true);
if ($jsonErrorMessage = JSON::hasError()) {
JSON::lastErrorMsg($pathNameClean,$jsonErrorMessage,$data);
}
} else if (($ext == "yaml") || ($ext == "yml")) {
$file = file_get_contents($pathName);
try {
$data = YAML::parse($file);
} catch (ParseException $e) {
printf("unable to parse ".$pathNameClean.": %s..\n", $e->getMessage());
}
// single line of text won't throw a YAML error. returns as string
if (gettype($data) == "string") {
$data = array();
}
}
if (is_array($data)) {
self::$store = array_replace_recursive(self::$store,$data);
}
} else if ($isListItems !== false) {
$data = ($ext == "json") ? self::getListItems("_data/".$fileName) : self::getListItems("_data/".$fileName,"yaml");
if (!isset(self::$store["listItems"])) {
self::$store["listItems"] = array();
}
self::$store["listItems"] = array_replace_recursive(self::$store["listItems"],$data);
}
}
}
if (is_array(self::$store)) {
foreach (self::$reservedKeys as $reservedKey) {
if (array_key_exists($reservedKey,self::$store)) {
Console::writeWarning("\"".$reservedKey."\" is a reserved key in Pattern Lab. the data using that key will be overwritten. please choose a new key...");
}
}
}
self::$store["cacheBuster"] = Config::getOption("cacheBuster");
self::$store["link"] = array();
self::$store["patternSpecific"] = array();
$dispatcherInstance->dispatch("data.gatherEnd");
} | Gather data from any JSON and YAML files in source/_data
Reserved attributes:
- Data::$store["listItems"] : listItems from listitems.json, duplicated into separate arrays for Data::$store["listItems"]["one"], Data::$store["listItems"]["two"]... etc.
- Data::$store["link"] : the links to each pattern
- Data::$store["cacheBuster"] : the cache buster value to be appended to URLs
- Data::$store["patternSpecific"] : holds attributes from the pattern-specific data files
@return {Array} populates Data::$store | entailment |
public static function getListItems($filepath,$ext = "json") {
// set-up the dispatcher
$dispatcherInstance = Dispatcher::getInstance();
// dispatch that the data gather has started
$dispatcherInstance->dispatch("data.getListItemsStart");
// default vars
$sourceDir = Config::getOption("sourceDir");
$listItems = array();
$listItemsData = array();
// add list item data, makes 'listItems' a reserved word
if (file_exists($sourceDir."/".$filepath)) {
$file = file_get_contents($sourceDir."/".$filepath);
if ($ext == "json") {
$listItemsData = json_decode($file, true);
if ($jsonErrorMessage = JSON::hasError()) {
JSON::lastErrorMsg($filepath,$jsonErrorMessage,$listItems);
}
} else {
try {
$listItemsData = YAML::parse($file);
} catch (ParseException $e) {
printf("unable to parse ".$pathNameClean.": %s..\n", $e->getMessage());
}
// single line of text won't throw a YAML error. returns as string
if (gettype($listItemsData) == "string") {
$listItemsData = array();
}
}
$numbers = array("one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve");
$i = 0;
$k = 1;
$c = count($listItemsData)+1;
while ($k < $c) {
shuffle($listItemsData);
$itemsArray = array();
while ($i < $k) {
$itemsArray[] = $listItemsData[$i];
$i++;
}
$listItems[$numbers[$k-1]] = $itemsArray;
$i = 0;
$k++;
}
}
$dispatcherInstance->dispatch("data.getListItemsEnd");
return $listItems;
} | Generate the listItems array
@param {String} the filename for the pattern to be parsed
@param {String} the extension so that a flag switch can be used to parse data
@return {Array} the final set of list items | entailment |
public static function getPatternSpecificData($patternPartial,$extraData = array()) {
// if there is pattern-specific data make sure to override the default in $this->d
$d = self::get();
if (isset($d["patternSpecific"]) && array_key_exists($patternPartial,$d["patternSpecific"])) {
if (!empty($d["patternSpecific"][$patternPartial]["data"])) {
$d = array_replace_recursive($d, $d["patternSpecific"][$patternPartial]["data"]);
}
if (!empty($d["patternSpecific"][$patternPartial]["listItems"])) {
$numbers = array("one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve");
$k = 0;
$c = count($d["patternSpecific"][$patternPartial]["listItems"]);
while ($k < $c) {
$section = $numbers[$k];
$d["listItems"][$section] = array_replace_recursive( $d["listItems"][$section], $d["patternSpecific"][$patternPartial]["listItems"][$section]);
$k++;
}
}
}
if (!empty($extraData)) {
$d = array_replace_recursive($d, $extraData);
}
unset($d["patternSpecific"]);
return $d;
} | Get the final data array specifically for a pattern
@param {String} the filename for the pattern to be parsed
@param {Array} any extra data that should be added to the pattern specific data that's being returned
@return {Array} the final set of list items | entailment |
public static function initPattern($optionName) {
if (!isset(self::$store["patternSpecific"])) {
self::$store["patternSpecific"] = array();
}
if ((!isset(self::$store["patternSpecific"][$optionName])) || (!is_array(self::$store["patternSpecific"][$optionName]))) {
self::$store["patternSpecific"][$optionName] = array();
}
} | Initialize a pattern specific data store under the patternSpecific option
@param {String} the pattern to create an array for | entailment |
public static function setOption($key = "", $value = "") {
if (empty($key)) {
return false;
}
$arrayFinder = new ArrayFinder(self::$store);
$arrayFinder->set($key, $value);
self::$store = $arrayFinder->get();
} | Set an option for the data store
@param {String} a string in dot notation dictating where the option is in the data structure
@param {Mixed} the value for the key
@return {Array} the store | entailment |
public static function setOptionLink($optionName,$optionValue) {
if (!isset(self::$store["link"])) {
self::$store["link"] = array();
}
self::$store["link"][$optionName] = $optionValue;
} | Set an option on a sub element of the data array
@param {String} name of the option
@param {String} value for the option | entailment |
public static function setPatternData($optionName,$optionValue) {
if (isset(self::$store["patternSpecific"][$optionName])) {
self::$store["patternSpecific"][$optionName]["data"] = $optionValue;
return true;
}
return false;
} | Set the pattern data option
@param {String} name of the pattern
@param {String} value for the pattern's data attribute | entailment |
public static function setPatternListItems($optionName,$optionValue) {
if (isset(self::$store["patternSpecific"][$optionName])) {
self::$store["patternSpecific"][$optionName]["listItems"] = $optionValue;
return true;
}
return false;
} | Set the pattern listitems option
@param {String} name of the pattern
@param {String} value for the pattern's listItem attribute | entailment |
protected function compareProp($name, $propCompare, $exact = false) {
if (($name == "") && ($propCompare == "")) {
$result = true;
} else if ((($name == "") && ($propCompare != "")) || (($name != "") && ($propCompare == ""))) {
$result = false;
} else if (strpos($propCompare,"&&") !== false) {
$result = true;
$props = explode("&&",$propCompare);
foreach ($props as $prop) {
$pos = $this->testProp($name, $prop, $exact);
$result = ($result && $pos);
}
} else if (strpos($propCompare,"||") !== false) {
$result = false;
$props = explode("||",$propCompare);
foreach ($props as $prop) {
$pos = $this->testProp($name, $prop, $exact);
$result = ($result || $pos);
}
} else {
$result = $this->testProp($name, $propCompare, $exact);
}
return $result;
} | Compare the search and ignore props against the name.
Can use && or || in the comparison
@param {String} the name of the item
@param {String} the value of the property to compare
@return {Boolean} whether the compare was successful or not | entailment |
protected function getPatternName($pattern, $clean = true) {
$patternBits = explode("-",$pattern,2);
$patternName = (((int)$patternBits[0] != 0) || ($patternBits[0] == '00')) ? $patternBits[1] : $pattern;
// replace possible dots with dashes. pattern names cannot contain dots
// since they are used as id/class names in the styleguidekit.
$patternName = str_replace('.', '-', $patternName);
return ($clean) ? (str_replace("-"," ",$patternName)) : $patternName;
} | Get the name for a given pattern sans any possible digits used for reordering
@param {String} the pattern based on the filesystem name
@param {Boolean} whether or not to strip slashes from the pattern name
@return {String} a lower-cased version of the pattern name | entailment |
public function updateProp($propName, $propValue, $action = "or") {
if (!isset($this->$propName) || !is_scalar($propValue)) {
return false;
}
if ($action == "or") {
$propValue = $this->$propName."||".$propValue;
} else if ($action == "and") {
$propValue = $this->$propName."&&".$propValue;
}
return $this->setProp($this->$propName,$propValue);
} | Update a property on a given rule
@param {String} the name of the property
@param {String} the value of the property
@param {String} the action that should be taken with the new value
@return {Boolean} whether the update was successful | entailment |
public static function pluralize($word) {
$word .= 's';
$word = preg_replace('/(x|ch|sh|ss])s$/', '\1es', $word);
$word = preg_replace('/ss$/', 'ses', $word);
$word = preg_replace('/([ti])ums$/', '\1a', $word);
$word = preg_replace('/sises$/', 'ses', $word);
$word = preg_replace('/([^aeiouy]|qu)ys$/', '\1ies', $word);
$word = preg_replace('/(?:([^f])fe|([lr])f)s$/', '\1\2ves', $word);
$word = preg_replace('/ieses$/', 'ies', $word);
return $word;
} | Pluralize the element name. | entailment |
public static function underscorize($word) {
$word = preg_replace('/[\'"]/', '', $word);
$word = preg_replace('/[^a-zA-Z0-9]+/', '_', $word);
$word = preg_replace('/([A-Z\d]+)([A-Z][a-z])/', '\1_\2', $word);
$word = preg_replace('/([a-z\d])([A-Z])/', '\1_\2', $word);
$word = trim($word, '_');
$word = strtolower($word);
$word = str_replace('boleto_simples_', '', $word);
return $word;
} | Undescorize the element name. | entailment |
public static function init() {
// make sure config vars exist
if (!Config::getOption("patternExtension")) {
Console::writeError("the pattern extension config option needs to be set...");
}
if (!Config::getOption("styleguideKit")) {
Console::writeError("the styleguideKit config option needs to be set...");
}
// set-up config vars
$patternExtension = Config::getOption("patternExtension");
$metaDir = Config::getOption("metaDir");
$styleguideKit = Config::getOption("styleguideKit");
$styleguideKitPath = Config::getOption("styleguideKitPath");
if (!$styleguideKitPath || !is_dir($styleguideKitPath)) {
Console::writeError("your styleguide won't render because i can't find your styleguide files. are you sure they're at <path>".Console::getHumanReadablePath($styleguideKitPath)."</path>? you can fix this in <path>./config/config.yml</path> by editing styleguideKitPath...");
}
// load pattern-lab's resources
$partialPath = $styleguideKitPath.DIRECTORY_SEPARATOR."views".DIRECTORY_SEPARATOR."partials";
$generalHeaderPath = $partialPath.DIRECTORY_SEPARATOR."general-header.".$patternExtension;
$generalFooterPath = $partialPath.DIRECTORY_SEPARATOR."general-footer.".$patternExtension;
self::$htmlHead = (file_exists($generalHeaderPath)) ? file_get_contents($generalHeaderPath) : "";
self::$htmlFoot = (file_exists($generalFooterPath)) ? file_get_contents($generalFooterPath) : "";
// gather the user-defined header and footer information
$patternHeadPath = $metaDir.DIRECTORY_SEPARATOR."_00-head.".$patternExtension;
$patternFootPath = $metaDir.DIRECTORY_SEPARATOR."_01-foot.".$patternExtension;
self::$patternHead = (file_exists($patternHeadPath)) ? file_get_contents($patternHeadPath) : "";
self::$patternFoot = (file_exists($patternFootPath)) ? file_get_contents($patternFootPath) : "";
// add the filesystemLoader
$patternEngineBasePath = PatternEngine::getInstance()->getBasePath();
$filesystemLoaderClass = $patternEngineBasePath."\Loaders\FilesystemLoader";
$options = array();
$options["templatePath"] = $styleguideKitPath.DIRECTORY_SEPARATOR."views";
$options["partialsPath"] = $options["templatePath"].DIRECTORY_SEPARATOR."partials";
self::$filesystemLoader = new $filesystemLoaderClass($options);
$stringLoaderClass = $patternEngineBasePath."\Loaders\StringLoader";
self::$stringLoader = new $stringLoaderClass();
// i can't remember why i chose to implement the pattern loader directly in classes
// i figure i had a good reason which is why it's not showing up here
} | Set-up default vars | entailment |
public function validate($authTokenPayload) {
if($authTokenPayload == null) {
return false;
}
$tokenResponse = $this->tokens->find($authTokenPayload);
if($tokenResponse == null) {
return false;
}
$user = $this->users->retrieveByID( $tokenResponse->getAuthIdentifier() );
if($user == null) {
return false;
}
return $user;
} | Validates a public auth token. Returns User object on success, otherwise false.
@param $authTokenPayload
@return bool|UserInterface | entailment |
public function attempt(array $credentials) {
$user = $this->users->retrieveByCredentials($credentials);
if($user instanceof UserInterface && $this->users->validateCredentials($user, $credentials)) {
return $this->create($user);
}
return false;
} | Attempt to create an AuthToken from user credentials.
@param array $credentials
@return bool|AuthToken | entailment |
public function create(UserInterface $user) {
$this->tokens->purge($user);
return $this->tokens->create($user);
} | Create auth token for user.
@param UserInterface $user
@return bool|AuthToken | entailment |
public function isHashed($attribute)
{
if ( ! array_key_exists($attribute, $this->attributes)) {
return false;
}
$info = password_get_info($this->attributes[$attribute]);
return (bool) ($info['algo'] !== 0);
} | Returns whether the attribute is hashed.
@param string $attribute name
@return bool | entailment |
public function hashAttributes()
{
foreach ($this->getHashable() as $attribute) {
$this->setHashingAttribute($attribute, $this->getAttribute($attribute));
}
} | Hash attributes that should be hashed. | entailment |
public function setHashingAttribute($attribute, $value)
{
// Set the value which is presumably plain text
$this->attributes[$attribute] = $value;
// Do the hashing if it needs it
if ( ! empty($value) && ($this->isDirty($attribute) || ! $this->isHashed($attribute))) {
$this->attributes[$attribute] = $this->hash($value);
}
} | Set a hashed value for a hashable attribute.
@param string $attribute name
@param string $value to hash | entailment |
protected function setHashingAndSave($hash)
{
// Set hashing state
$hashing = $this->getHashing();
$this->setHashing($hash);
// Save the model
$result = $this->save();
// Reset hashing back to it's previous state
$this->setHashing($hashing);
return $result;
} | Set hashing state and then save and then reset it.
@param bool $hash
@return bool | entailment |
public function getRuleset($ruleset, $mergeWithSaving = false)
{
$rulesets = $this->getRulesets();
if (array_key_exists($ruleset, $rulesets)) {
// If the ruleset exists and merge with saving is true, return
// the rulesets merged.
if ($mergeWithSaving) {
return $this->mergeRulesets(['saving', $ruleset]);
}
// If merge with saving is not true then simply retrun the ruleset.
return $rulesets[$ruleset];
}
// If the ruleset requested does not exist but merge with saving is true
// attempt to return
elseif ($mergeWithSaving) {
return $this->getDefaultRules();
}
} | Get a ruleset, and merge it with saving if required.
@deprecated watson/[email protected]
@param string $ruleset
@param bool $mergeWithSaving
@return array | entailment |
public function addRules(array $rules, $ruleset = null)
{
if ($ruleset) {
$newRules = array_merge($this->getRuleset($ruleset), $rules);
$this->setRuleset($newRules, $ruleset);
} else {
$newRules = array_merge($this->getRules(), $rules);
$this->setRules($newRules);
}
} | Add rules to the existing rules or ruleset, overriding any existing.
@deprecated watson/[email protected]
@param array $rules
@param string $ruleset | entailment |
public function removeRules($keys, $ruleset = null)
{
$keys = is_array($keys) ? $keys : func_get_args();
$rules = $ruleset ? $this->getRuleset($ruleset) : $this->getRules();
array_forget($rules, $keys);
if ($ruleset) {
$this->setRuleset($rules, $ruleset);
} else {
$this->setRules($rules);
}
} | Remove rules from the existing rules or ruleset.
@deprecated watson/[email protected]
@param mixed $keys
@param string $ruleset | entailment |
public function mergeRulesets($keys)
{
$keys = is_array($keys) ? $keys : func_get_args();
$rulesets = [];
foreach ($keys as $key) {
$rulesets[] = (array) $this->getRuleset($key, false);
}
return array_filter(call_user_func_array('array_merge', $rulesets));
} | Helper method to merge rulesets, with later rules overwriting
earlier ones.
@deprecated watson/[email protected]
@param array $keys
@return array | entailment |
public function isValid($ruleset = null, $mergeWithSaving = true)
{
$rules = is_array($ruleset) ? $ruleset : $this->getRuleset($ruleset, $mergeWithSaving) ?: $this->getDefaultRules();
return $this->performValidation($rules);
} | Returns whether the model is valid or not.
@param mixed $ruleset (@deprecated watson/[email protected])
@param bool $mergeWithSaving (@deprecated watson/[email protected])
@return bool | entailment |
public function updateRulesetUniques($ruleset = null)
{
$rules = $this->getRuleset($ruleset);
$this->setRuleset($ruleset, $this->injectUniqueIdentifierToRules($rules));
} | Update the unique rules of the given ruleset to
include the model identifier.
@deprecated watson/[email protected]
@param string $ruleset | entailment |
public static function gather() {
// set-up default var
$annotationsDir = Config::getOption("annotationsDir");
// set-up the dispatcher
$dispatcherInstance = Dispatcher::getInstance();
// dispatch that the data gather has started
$dispatcherInstance->dispatch("annotations.gatherStart");
// set-up the comments store
self::$store["comments"] = array();
// create the annotations dir if it doesn't exist
if (!is_dir($annotationsDir)) {
mkdir($annotationsDir);
}
// find the markdown-based annotations
$finder = new Finder();
$finder->files()->name("*.md")->in($annotationsDir);
$finder->sortByName();
foreach ($finder as $name => $file) {
$data = array();
$data[0] = array();
$text = file_get_contents($file->getPathname());
$matches = (strpos($text,PHP_EOL."~*~".PHP_EOL) !== false) ? explode(PHP_EOL."~*~".PHP_EOL,$text) : array($text);
foreach ($matches as $match) {
list($yaml,$markdown) = Documentation::parse($match);
if (isset($yaml["el"]) || isset($yaml["selector"])) {
$data[0]["el"] = (isset($yaml["el"])) ? $yaml["el"] : $yaml["selector"];
} else {
$data[0]["el"] = "#someimpossibleselector";
}
$data[0]["title"] = isset($yaml["title"]) ? $yaml["title"] : "";
$data[0]["comment"] = $markdown;
self::$store["comments"] = array_merge(self::$store["comments"],$data);
}
}
// read in the old style annotations.js, modify the data and generate JSON array to merge
$data = array();
$oldStyleAnnotationsPath = $annotationsDir.DIRECTORY_SEPARATOR."annotations.js";
if (file_exists($oldStyleAnnotationsPath)) {
$text = trim(file_get_contents($oldStyleAnnotationsPath));
$text = str_replace("var comments = ","",$text);
if ($text[strlen($text)-1] == ";") {
$text = rtrim($text,";");
}
$data = json_decode($text,true);
if ($jsonErrorMessage = JSON::hasError()) {
JSON::lastErrorMsg(Console::getHumanReadablePath($oldStyleAnnotationsPath),$jsonErrorMessage,$data);
}
}
// merge in any data from the old file if the json decode was successful
if (is_array($data) && isset($data["comments"])) {
self::$store["comments"] = array_merge(self::$store["comments"],$data["comments"]);
}
$dispatcherInstance->dispatch("annotations.gatherEnd");
} | Gather data from annotations.js and *.md files found in source/_annotations
@return {Array} populates Annotations::$store | entailment |
public function spawn($commands = array(), $quiet = false) {
// set-up a default
$processes = array();
// add the default processes sent to the spawner
if (!empty($commands)) {
foreach ($commands as $command) {
$processes[] = $this->buildProcess($command);
}
}
// add the processes sent to the spawner from plugins
foreach ($this->pluginProcesses as $pluginProcess) {
$processes[] = $this->buildProcess($pluginProcess);
}
// if there are processes to spawn do so
if (!empty($processes)) {
// start the processes
foreach ($processes as $process) {
$process["process"]->start();
}
// check on them and produce output
while (true) {
foreach ($processes as $process) {
try {
if ($process["process"]->isRunning()) {
$process["process"]->checkTimeout();
if (!$quiet && $process["output"]) {
print $process["process"]->getIncrementalOutput();
$cmd = $process["process"]->getCommandLine();
if (strpos($cmd,"router.php") != (strlen($cmd) - 10)) {
print $process["process"]->getIncrementalErrorOutput();
}
}
}
} catch (ProcessTimedOutException $e) {
if ($e->isGeneralTimeout()) {
Console::writeError("pattern lab processes should never time out. yours did...");
} else if ($e->isIdleTimeout()) {
Console::writeError("pattern lab processes automatically time out if their is no command line output in 30 minutes...");
}
}
}
usleep(100000);
}
}
} | Spawn the passed commands and those collected from plugins
@param {Array} a list of commands to spawn
@param {Boolean} if this should be run in quiet mode | entailment |
protected function buildProcess($commandOptions) {
if (is_string($commandOptions)) {
$process = new Process(escapeshellcmd((string) $commandOptions));
return array("process" => $process, "output" => true);
} else if (is_array($commandOptions)) {
$commandline = escapeshellcmd((string) $commandOptions["command"]);
$cwd = isset($commandOptions["cwd"]) ? $commandOptions["cwd"] : null;
$env = isset($commandOptions["env"]) ? $commandOptions["env"] : null;
$input = isset($commandOptions["input"]) ? $commandOptions["input"] : null;
$timeout = isset($commandOptions["timeout"]) ? $commandOptions["timeout"] : null;
$options = isset($commandOptions["options"]) ? $commandOptions["options"] : array();
$idle = isset($commandOptions["idle"]) ? $commandOptions["idle"] : null;
$output = isset($commandOptions["output"]) ? $commandOptions["output"] : true;
$process = new Process($commandline, $cwd, $env, $input, $timeout, $options);
// double-check idle
if (!empty($idle)) {
$process->setIdleTimeout($idle);
}
return array("process" => $process, "output" => $output);
}
} | Build the process from the given commandOptions
@param {Array} the options from which to build the process | entailment |
public function saving(Model $model)
{
if ( ! $model->getRuleset('creating') && ! $model->getRuleset('updating')) {
return $this->performValidation($model, 'saving');
}
} | Register the validation event for saving the model. Saving validation
should only occur if creating and updating validation does not.
@param Illuminate\Database\Eloquent\Model $model
@return bool | entailment |
public function run($type = "", $subtype = "") {
// default vars
$patternPartials = array();
$suffixRendered = Config::getOption("outputFileSuffixes.rendered");
foreach ($this->store as $patternStoreKey => $patternStoreData) {
// Docs for patternTypes (i.e. `atoms.md`), don't have these rules and need them to pass below conditionals
if (
!isset($patternStoreData['depth'])
&& !isset($patternStoreData['hidden'])
&& !isset($patternStoreData['noviewall'])
) {
$patternStoreData["hidden"] = false;
$patternStoreData["noviewall"] = false;
$patternStoreData["depth"] = 0;
}
$canShow = isset($patternStoreData["hidden"]) && (!$patternStoreData["hidden"]) && (!$patternStoreData["noviewall"]);
if (($patternStoreData["category"] == "pattern") && $canShow && ($patternStoreData["depth"] > 1) && (!in_array($patternStoreData["type"],$this->styleGuideExcludes))) {
if ((($patternStoreData["type"] == $type) && empty($subtype)) || (empty($type) && empty($subtype)) || (($patternStoreData["type"] == $type) && ($patternStoreData["subtype"] == $subtype))) {
$patternPartialData = array();
$patternPartialData["patternName"] = $patternStoreData["nameClean"];
$patternPartialData["patternLink"] = $patternStoreData["pathDash"]."/".$patternStoreData["pathDash"].$suffixRendered.".html";
$patternPartialData["patternPartial"] = $patternStoreData["partial"];
$patternPartialData["patternPartialCode"] = $patternStoreData["code"];
$patternPartialData["patternState"] = $patternStoreData["state"];
$patternPartialData["patternLineageExists"] = isset($patternStoreData["lineages"]);
$patternPartialData["patternLineages"] = isset($patternStoreData["lineages"]) ? $patternStoreData["lineages"] : array();
$patternPartialData["patternLineageRExists"] = isset($patternStoreData["lineagesR"]);
$patternPartialData["patternLineagesR"] = isset($patternStoreData["lineagesR"]) ? $patternStoreData["lineagesR"] : array();
$patternPartialData["patternLineageEExists"] = (isset($patternStoreData["lineages"]) || isset($patternStoreData["lineagesR"]));
$patternPartialData["patternDescExists"] = isset($patternStoreData["desc"]);
$patternPartialData["patternDesc"] = isset($patternStoreData["desc"]) ? $patternStoreData["desc"] : "";
$patternPartialData["patternDescAdditions"] = isset($patternStoreData["partialViewDescAdditions"]) ? $patternStoreData["partialViewDescAdditions"] : array();
$patternPartialData["patternExampleAdditions"] = isset($patternStoreData["partialViewExampleAdditions"]) ? $patternStoreData["partialViewExampleAdditions"] : array();
// add the pattern data so it can be exported
$patternData = array();
$patternData["lineage"] = isset($patternStoreData["lineages"]) ? $patternStoreData["lineages"] : array();
$patternData["lineageR"] = isset($patternStoreData["lineagesR"]) ? $patternStoreData["lineagesR"] : array();
$patternData["patternBreadcrumb"] = $patternStoreData["breadcrumb"];
$patternData["patternDesc"] = (isset($patternStoreData["desc"])) ? $patternStoreData["desc"] : "";
$patternData["patternExtension"] = Config::getOption("patternExtension");
$patternData["patternName"] = $patternStoreData["nameClean"];
$patternData["patternPartial"] = $patternStoreData["partial"];
$patternData["patternState"] = $patternStoreData["state"];
$patternPartialData["patternData"] = json_encode($patternData);
$patternPartials[] = $patternPartialData;
}
} else if (($patternStoreData["category"] == "patternSubtype") && (!in_array($patternStoreData["type"],$this->styleGuideExcludes))) {
if ((($patternStoreData["type"] == $type) && empty($subtype)) || (empty($type) && empty($subtype)) || (($patternStoreData["type"] == $type) && ($patternStoreData["name"] == $subtype))) {
$patternPartialData = array();
$patternPartialData["patternName"] = $patternStoreData["nameClean"];
$patternPartialData["patternLink"] = $patternStoreData["pathDash"]."/index.html";
$patternPartialData["patternPartial"] = $patternStoreData["partial"];
$patternPartialData["patternSectionSubtype"] = true;
$patternPartialData["patternDesc"] = isset($patternStoreData["desc"]) ? $patternStoreData["desc"] : "";
$patternPartials[] = $patternPartialData;
}
} else if (
($patternStoreData["category"] == "pattern")
&& $canShow
&& (isset($patternStoreData["full"])
&& ($type === $patternStoreData["full"] || $type === ""))
&& ($subtype === "")
) {
// This is for `patternType` docs. Given this structure:
// - _patterns/
// - atoms/
// - forms/
// - atoms.md
// This will take the contents of `atoms.md` and place at top of "Atoms > View All"
$patternPartialData = array();
// Getting the name from md's `title: My Name` works here, as does the link, but it doesn't make sense to link to the view you are already on. Plus you can just do the title in the MD doc. Keeping here for now in case it's wanted later.
// $patternPartialData["patternName"] = isset($patternStoreData["nameClean"]) ? $patternStoreData["nameClean"] : '';
// $patternPartialData["patternLink"] = $patternStoreData["full"] . "/index.html";
$patternPartialData["patternSectionSubtype"] = true;
$patternPartialData["patternDesc"] = isset($patternStoreData["desc"]) ? $patternStoreData["desc"] : "";
$patternPartials[] = $patternPartialData;
}
}
return array("partials" => $patternPartials, "cacheBuster" => $this->cacheBuster);
} | Compare the search and ignore props against the name.
Can use && or || in the comparison
@param {String} the type of the pattern that should be used in the view all
@param {String} the subtype of the pattern that be used in the view all
@return {Array} the list of partials | entailment |
private function getOption() {
// figure out which option was passed
$searchOption = Console::findCommandOptionValue("get");
$optionValue = Config::getOption($searchOption);
// write it out
if (!$optionValue) {
Console::writeError("the --get value you provided, <info>".$searchOption."</info>, does not exists in the config...");
} else {
$optionValue = (is_array($optionValue)) ? implode(", ",$optionValue) : $optionValue;
$optionValue = (!$optionValue) ? "false" : $optionValue;
Console::writeInfo($searchOption.": <ok>".$optionValue."</ok>");
}
} | Get the given option and return its value | entailment |
private function listOptions() {
// get all of the options
$options = Config::getOptions();
// sort 'em alphabetically
ksort($options);
// find length of longest option
$this->lengthLong = 0;
foreach ($options as $optionName => $optionValue) {
$this->lengthLong = (strlen($optionName) > $this->lengthLong) ? strlen($optionName) : $this->lengthLong;
}
$this->writeOutOptions($options);
} | List out of the options available in the config | entailment |
protected function setOption() {
// find the value that was passed
$updateOption = Console::findCommandOptionValue("set");
$updateOptionBits = explode("=",$updateOption);
if (count($updateOptionBits) == 1) {
Console::writeError("the --set value should look like <info>optionName=\"optionValue\"</info>. nothing was updated...");
}
// set the name and value that were passed
$updateName = $updateOptionBits[0];
$updateValue = (($updateOptionBits[1][0] == "\"") || ($updateOptionBits[1][0] == "'")) ? substr($updateOptionBits[1],1,strlen($updateOptionBits[1])-1) : $updateOptionBits[1];
// make sure the option being updated already exists
$currentValue = Config::getOption($updateName);
if (!$currentValue) {
Console::writeError("the --set option you provided, <info>".$updateName."</info>, does not exists in the config. nothing will be updated...");
} else {
Config::updateConfigOption($updateName,$updateValue);
Console::writeInfo("config option updated...");
}
} | Set the given option to the given value | entailment |
private function writeOutOptions($options, $pre = "") {
foreach ($options as $optionName => $optionValue) {
if (is_array($optionValue) && (count($optionValue) > 0) && !isset($optionValue[0])) {
$this->writeOutOptions($optionValue, $optionName.".");
} else {
$optionValue = (is_array($optionValue) && isset($optionValue[0])) ? implode(", ",$optionValue) : $optionValue;
$optionValue = (!$optionValue) ? "false" : $optionValue;
$spacer = Console::getSpacer($this->lengthLong,strlen($pre.$optionName));
Console::writeLine("<info>".$pre.$optionName.":</info>".$spacer.$optionValue);
}
}
} | Write out the given options. Check to see if it's a nested sequential or associative array
@param {Mixed} the options to check and write out
@param {String} copy to be added to the beginning of the option if nested | entailment |
public static function init() {
$found = false;
$patternExtension = Config::getOption("patternExtension");
self::loadRules();
foreach (self::$rules as $rule) {
if ($rule->test($patternExtension)) {
self::$instance = $rule;
$found = true;
break;
}
}
if (!$found) {
Console::writeError("the supplied pattern extension didn't match a pattern loader rule. check your config...");
}
} | Load a new instance of the Pattern Loader | entailment |
public static function loadRules() {
// default var
$configDir = Config::getOption("configDir");
// make sure the pattern engine data exists
if (file_exists($configDir."/patternengines.json")) {
// get pattern engine list data
$patternEngineList = json_decode(file_get_contents($configDir."/patternengines.json"), true);
// get the pattern engine info
foreach ($patternEngineList["patternengines"] as $patternEngineName) {
self::$rules[] = new $patternEngineName();
}
} else {
Console::writeError("The pattern engines list isn't available in <path>".$configDir."</path>...");
}
} | Load all of the rules related to Pattern Engines. They're located in the plugin dir | entailment |
public function findReplaceParameters($fileData, $parameters) {
$numbers = array("zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve");
foreach ($parameters as $k => $v) {
if (is_array($v)) {
if (preg_match('/{{\#([\s]*'.$k.'[\s]*)}}(.*?){{\/([\s]*'.$k.'[\s]*)}}/s',$fileData,$matches)) {
if (isset($matches[2])) {
$partialData = "";
foreach ($v as $v2) {
$partialData .= $this->findReplaceParameters($matches[2], $v2);
}
$fileData = preg_replace('/{{\#([\s]*'.$k.'[\s]*)}}(.*?){{\/([\s]*'.$k .'[\s]*)}}/s',$partialData,$fileData);
}
}
} else if ($v == "true") {
$fileData = preg_replace('/{{\#([\s]*'.$k.'[\s]*)}}(.*?){{\/([\s]*'.$k .'[\s]*)}}/s','$2',$fileData); // {{# asdf }}STUFF{{/ asdf}}
$fileData = preg_replace('/{{\^([\s]*'.$k.'[\s]*)}}(.*?){{\/([\s]*'.$k .'[\s]*)}}/s','',$fileData); // {{^ asdf }}STUFF{{/ asdf}}
} else if ($v == "false") {
$fileData = preg_replace('/{{\^([\s]*'.$k.'[\s]*)}}(.*?){{\/([\s]*'.$k .'[\s]*)}}/s','$2',$fileData); // {{# asdf }}STUFF{{/ asdf}}
$fileData = preg_replace('/{{\#([\s]*'.$k.'[\s]*)}}(.*?){{\/([\s]*'.$k .'[\s]*)}}/s','',$fileData); // {{^ asdf }}STUFF{{/ asdf}}
} else if ($k == "listItems") {
$v = ((int)$v != 0) && ((int)$v < 13) ? $numbers[$v] : $v;
if (($v != "zero") && in_array($v,$numbers)) {
$fileData = preg_replace('/{{\#([\s]*listItems\.[A-z]{3,10}[\s]*)}}/s','{{# listItems.'.$v.' }}',$fileData);
$fileData = preg_replace('/{{\/([\s]*listItems\.[A-z]{3,10}[\s]*)}}/s','{{/ listItems.'.$v.' }}',$fileData);
}
} else {
$fileData = preg_replace('/{{{([\s]*'.$k.'[\s]*)}}}/', $v, $fileData); // {{{ asdf }}}
$fileData = preg_replace('/{{([\s]*'.$k.'[\s]*)}}/', htmlspecialchars($v), $fileData); // escaped {{ asdf }}
}
}
return $fileData;
} | Helper function to find and replace the given parameters in a particular partial before handing it back to Mustache
@param {String} the file contents
@param {Array} an array of paramters to match
@return {String} the modified file contents | entailment |
public function getFileName($name,$ext) {
$fileName = "";
$dirSep = DIRECTORY_SEPARATOR;
// test to see what kind of path was supplied
$posDash = strpos($name,"-");
$posSlash = strpos($name,$dirSep);
if (($posSlash === false) && ($posDash !== false)) {
$fileName = $this->getPatternFileName($name);
} else {
$fileName = $name;
}
if (substr($fileName, 0 - strlen($ext)) !== $ext) {
$fileName .= $ext;
}
return $fileName;
} | Helper function for getting a Mustache template file name.
@param {String} the pattern type for the pattern
@param {String} the pattern sub-type
@return {Array} an array of rendered partials that match the given path | entailment |
public function getPatternFileName($name) {
$patternFileName = "";
list($patternType,$pattern) = $this->getPatternInfo($name);
// see if the pattern is an exact match for patternPaths. if not iterate over patternPaths to find a likely match
if (isset($this->patternPaths[$patternType][$pattern])) {
$patternFileName = $this->patternPaths[$patternType][$pattern];
} else if (isset($this->patternPaths[$patternType])) {
foreach($this->patternPaths[$patternType] as $patternMatchKey=>$patternMatchValue) {
$pos = strpos($patternMatchKey,$pattern);
if ($pos !== false) {
$patternFileName = $patternMatchValue;
break;
}
}
}
return $patternFileName;
} | Helper function to return the pattern file name
@param {String} the name of the pattern
@return {String} the file path to the pattern | entailment |
public function getPatternInfo($name) {
$patternBits = explode("-",$name);
$i = 1;
$k = 2;
$c = count($patternBits);
$patternType = $patternBits[0];
while (!isset($this->patternPaths[$patternType]) && ($i < $c)) {
$patternType .= "-".$patternBits[$i];
$i++;
$k++;
}
$patternBits = explode("-",$name,$k);
$pattern = $patternBits[count($patternBits)-1];
return array($patternType, $pattern);
} | Helper function to return the parts of a partial name
@param {String} the name of the partial
@return {Array} the pattern type and the name of the pattern | entailment |
public function getPartialInfo($partial) {
$styleModifier = array();
$parameters = array();
if (strpos($partial, "(") !== false) {
$partialBits = explode("(",$partial,2);
$partial = trim($partialBits[0]);
$parametersString = substr($partialBits[1],0,(strlen($partialBits[1]) - strlen(strrchr($partialBits[1],")"))));
$parameters = $this->parseParameters($parametersString);
}
if (strpos($partial, ":") !== false) {
$partialBits = explode(":",$partial,2);
$partial = $partialBits[0];
$styleModifier = $partialBits[1];
if (strpos($styleModifier, "|") !== false) {
$styleModifierBits = explode("|",$styleModifier);
$styleModifier = join(" ",$styleModifierBits);
}
$styleModifier = array("styleModifier" => $styleModifier);
}
return array($partial,$styleModifier,$parameters);
} | Helper function for finding if a partial name has style modifier or parameters
@param {String} the pattern name
@return {Array} an array containing just the partial name, a style modifier, and any parameters | entailment |
private function parseParameters($string) {
$parameters = array();
$arrayParameters = array();
$arrayOptions = array();
$betweenSQuotes = false;
$betweenDQuotes = false;
$inKey = true;
$inValue = false;
$inArray = false;
$inOption = false;
$char = "";
$buffer = "";
$keyBuffer = "";
$arrayKeyBuffer = "";
$strLength = strlen($string);
for ($i = 0; $i < $strLength; $i++) {
$previousChar = $char;
$char = $string[$i];
if ($inKey && !$betweenDQuotes && !$betweenSQuotes && (($char == "\"") || ($char == "'"))) {
// if inKey, a quote, and betweenQuotes is false ignore quote, set betweenQuotes to true and empty buffer to kill spaces
($char == "\"") ? ($betweenDQuotes = true) : ($betweenSQuotes = true);
} else if ($inKey && (($betweenDQuotes && ($char == "\"")) || ($betweenSQuotes && ($char == "'"))) && ($previousChar == "\\")) {
// if inKey, a quote, betweenQuotes is true, and previous character is \ add to buffer
$buffer .= $char;
} else if ($inKey && (($betweenDQuotes && ($char == "\"")) || ($betweenSQuotes && ($char == "'")))) {
// if inKey, a quote, betweenQuotes is true set betweenQuotes to false, save as key buffer, empty buffer set inKey false
$keyBuffer = $buffer;
$buffer = "";
$inKey = false;
$betweenSQuotes = false;
$betweenDQuotes = false;
} else if ($inKey && !$betweenDQuotes && !$betweenSQuotes && ($char == ":")) {
// if inKey, a colon, betweenQuotes is false, save as key buffer, empty buffer, set inKey false set inValue true
$keyBuffer = $buffer;
$buffer = "";
$inKey = false;
$inValue = true;
} else if ($inKey) {
// if inKey add to buffer
$buffer .= $char;
} else if (!$inKey && !$inValue && ($char == ":")) {
// if inKey is false, inValue false, and a colon set inValue true
$inValue = true;
} else if ($inValue && !$inArray && !$betweenDQuotes && !$betweenSQuotes && ($char == "[")) {
// if inValue, outside quotes, and find a bracket set inArray to true and add to array buffer
$inArray = true;
$inValue = false;
$arrayKeyBuffer = trim($keyBuffer);
} else if ($inArray && !$betweenDQuotes && !$betweenSQuotes && ($char == "]")) {
// if inValue, outside quotes, and find a bracket set inArray to true and add to array buffer
$inArray = false;
$parameters[$arrayKeyBuffer] = $arrayParameters;
$arrayParameters = array();
} else if ($inArray && !$inOption && !$betweenDQuotes && !$betweenSQuotes && ($char == "{")) {
$inOption = true;
$inKey = true;
} else if ($inArray && $inOption && !$betweenDQuotes && !$betweenSQuotes && ($char == "}")) {
$inOption = false;
$inValue = false;
$inKey = false;
$arrayParameters[] = $arrayOptions;
$arrayOptions = array();
} else if ($inValue && !$betweenDQuotes && !$betweenSQuotes && (($char == "\"") || ($char == "'"))) {
// if inValue, a quote, and betweenQuote is false set betweenQuotes to true and empty buffer to kill spaces
($char == "\"") ? ($betweenDQuotes = true) : ($betweenSQuotes = true);
} else if ($inValue && (($betweenDQuotes && ($char == "\"")) || ($betweenSQuotes && ($char == "'"))) && ($previousChar == "\\")) {
// if inValue, a quote, betweenQuotes is true, and previous character is \ add to buffer
$buffer .= $char;
} else if ($inValue && (($betweenDQuotes && ($char == "\"")) || ($betweenSQuotes && ($char == "'")))) {
// if inValue, a quote, betweenQuotes is true set betweenQuotes to false, save to parameters array, empty buffer, set inValue false
$buffer = str_replace("\\\"","\"",$buffer);
$buffer = str_replace('\\\'','\'',$buffer);
if ($inArray) {
$arrayOptions[trim($keyBuffer)] = trim($buffer);
} else {
$parameters[trim($keyBuffer)] = trim($buffer);
}
$buffer = "";
$inValue = false;
$betweenSQuotes = false;
$betweenDQuotes = false;
} else if ($inValue && !$betweenDQuotes && !$betweenSQuotes && ($char == ",")) {
// if inValue, a comman, betweenQuotes is false, save to parameters array, empty buffer, set inValue false, set inKey true
if ($inArray) {
$arrayOptions[trim($keyBuffer)] = trim($buffer);
} else {
$parameters[trim($keyBuffer)] = trim($buffer);
}
$buffer = "";
$inValue = false;
$inKey = true;
} else if ($inValue && (($i + 1) == $strLength)) {
// if inValue and end of the string add to buffer, save to parameters array
$buffer .= $char;
if ($inArray) {
$arrayOptions[trim($keyBuffer)] = trim($buffer);
} else {
$parameters[trim($keyBuffer)] = trim($buffer);
}
} else if ($inValue) {
// if inValue add to buffer
$buffer .= $char;
} else if (!$inValue && !$inKey && ($char == ",")) {
// if inValue is false, inKey false, and a comma set inKey true
if ($inArray && !$inOption) {
// don't do anything
} else {
$inKey = true;
}
}
}
return $parameters;
} | Helper function to parse the parameters and return them as an array
@param {String} the parameter string
@return {Array} the keys and values for the parameters | entailment |
public static function check($text = "") {
// make sure start time is set
if (empty(self::$startTime)) {
Console::writeError("the timer wasn't started...");
}
// make sure check time is set
if (empty(self::$checkTime)) {
self::$checkTime = self::$startTime;
}
// format any extra text
$insert = "";
if (!empty($text)) {
$insert = "<info>".$text." >> </info>";
}
// get the current time
$checkTime = self::getTime();
// get the data for the output
$totalTime = ($checkTime - self::$startTime);
$mem = round((memory_get_peak_usage(true)/1024)/1024,2);
// figure out what tag to show
$timeTag = "info";
if (($checkTime - self::$checkTime) > 0.2) {
$timeTag = "error";
} else if (($checkTime - self::$checkTime) > 0.1) {
$timeTag = "warning";
}
// set the checkTime for the next check comparison
self::$checkTime = $checkTime;
// write out time/mem stats
Console::writeLine($insert."currently taken <".$timeTag.">".$totalTime."</".$timeTag."> seconds and used <info>".$mem."MB</info> of memory...");
} | Check the current timer | entailment |
protected static function getTime() {
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
return $mtime;
} | /*
Get the time stamp | entailment |
public static function stop() {
// make sure start time is set
if (empty(self::$startTime)) {
Console::writeError("the timer wasn't started...");
}
// get the current time
$endTime = self::getTime();
// get the data for the output
$totalTime = ($endTime - self::$startTime);
$mem = round((memory_get_peak_usage(true)/1024)/1024,2);
// figure out what tag to show
$timeTag = "info";
if ($totalTime > 0.5) {
$timeTag = "error";
} else if ($totalTime > 0.3) {
$timeTag = "warning";
}
// write out time/mem stats
Console::writeLine("site generation took <".$timeTag.">".$totalTime."</".$timeTag."> seconds and used <info>".$mem."MB</info> of memory...");
} | Stop the timer | entailment |
public static function checkPatternOption($patternStoreKey,$optionName) {
if (isset(self::$store[$patternStoreKey])) {
return isset(self::$store[$patternStoreKey][$optionName]);
}
return false;
} | Return if a specific option for a pattern is set
@param {String} the pattern to check
@param {String} the option to check | entailment |
public static function hasPatternSubtype($patternType) {
foreach (self::$store as $patternStoreKey => $patternStoreData) {
if (($patternStoreData["category"] == "patternSubtype") && ($patternStoreData["typeDash"] == $patternType)) {
return true;
}
}
return false;
} | Check to see if the given pattern type has a pattern subtype associated with it
@param {String} the name of the pattern
@return {Boolean} if it was found or not | entailment |
public static function gather($options = array()) {
// set default vars
$exportClean = (isset($options["exportClean"])) ? $options["exportClean"] : false;
$exportFiles = (isset($options["exportClean"])) ? $options["exportFiles"] : false;
$dispatcherInstance = Dispatcher::getInstance();
// cleaning the var for use below, i know this is stupid
$options = array();
// dispatch that the data gather has started
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.gatherStart",$event);
// load up the rules for parsing patterns and the directories
self::loadRules($options);
// dispatch that the rules are loaded
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.rulesLoaded",$event);
// iterate over the patterns & related data and regenerate the entire site if they've changed
// seems a little silly to use symfony finder here. not really giving me any power
if (!is_dir(Config::getOption("patternSourceDir"))) {
Console::writeError("having patterns is important. please make sure you've installed a starterkit and/or that ".Console::getHumanReadablePath(Config::getOption("patternSourceDir"))." exists...");
}
$patternSourceDir = Config::getOption("patternSourceDir");
$patternObjects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($patternSourceDir, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);
// sort the returned objects
$patternObjects = iterator_to_array($patternObjects);
ksort($patternObjects);
/**
* @var string $name
* @var \SplFileInfo $object
*/
foreach ($patternObjects as $name => $object) {
$ext = $object->getExtension();
$isDir = $object->isDir();
$isFile = $object->isFile();
$path = str_replace($patternSourceDir.DIRECTORY_SEPARATOR,"",$object->getPath());
$pathName = str_replace($patternSourceDir.DIRECTORY_SEPARATOR,"",$object->getPathname());
$name = $object->getFilename();
$depth = substr_count($pathName,DIRECTORY_SEPARATOR);
// iterate over the rules and see if the current file matches one, if so run the rule
foreach (self::$rules as $rule) {
if ($rule->test($depth, $ext, $isDir, $isFile, $name)) {
$rule->run($depth, $ext, $path, $pathName, $name);
}
}
}
// dispatch that the data is loaded
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.dataLoaded",$event);
// make sure all of the appropriate pattern data is pumped into $this->d for rendering patterns
$dataLinkExporter = new DataLinkExporter();
$dataLinkExporter->run();
// make sure all of the appropriate pattern data is pumped into $this->d for rendering patterns
$dataMergeExporter = new DataMergeExporter();
$dataMergeExporter->run();
// dispatch that the raw pattern helper is about to start
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.rawPatternHelperStart",$event);
// add the lineage info to PatternData::$store
$rawPatternHelper = new RawPatternHelper();
$rawPatternHelper->run();
// dispatch that the raw pattern helper is ended
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.rawPatternHelperEnd",$event);
// dispatch that the lineage helper is about to start
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.lineageHelperStart",$event);
// add the lineage info to PatternData::$store
$lineageHelper = new LineageHelper();
$lineageHelper->run();
// dispatch that the lineage helper is ended
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.lineageHelperEnd",$event);
// dispatch that the pattern state helper is about to start
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.patternStateHelperStart",$event);
// using the lineage info update the pattern states on PatternData::$store
$patternStateHelper = new PatternStateHelper();
$patternStateHelper->run();
// dispatch that the pattern state helper is ended
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.patternStateHelperEnd",$event);
// set-up code pattern paths
$ppdExporter = new PatternPathSrcExporter();
$patternPathSrc = $ppdExporter->run();
$options = array();
$options["patternPaths"] = $patternPathSrc;
// dispatch that the code helper is about to start
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.codeHelperStart",$event);
// render out all of the patterns and store the generated info in PatternData::$store
$options["exportFiles"] = $exportFiles;
$options["exportClean"] = $exportClean;
$patternCodeHelper = new PatternCodeHelper($options);
$patternCodeHelper->run();
// dispatch that the pattern code helper is ended
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.patternCodeHelperEnd",$event);
// dispatch that the gather has ended
$event = new PatternDataEvent($options);
$dispatcherInstance->dispatch("patternData.gatherEnd",$event);
} | Gather all of the information related to the patterns | entailment |
public static function getOption($optionName) {
if (isset(self::$store[$optionName])) {
return self::$store[$optionName];
}
return false;
} | Get a specific item from the store
@param {String} the option to check | entailment |
public static function getPatternOption($patternStoreKey,$optionName) {
if (isset(self::$store[$patternStoreKey][$optionName])) {
return self::$store[$patternStoreKey][$optionName];
}
return false;
} | Get a specific item from a pattern in the store data
@param {String} the name of the pattern
@param {String} the name of the option to get
@return {String|Boolean} the value of false if it wasn't found | entailment |
public static function getRule($ruleName) {
if (isset(self::$rules[$ruleName])) {
return self::$rules[$ruleName];
}
return false;
} | Get a particular rule
@param {String} the name of the pattern | entailment |
public static function loadRules($options) {
foreach (glob(__DIR__."/PatternData/Rules/*.php") as $filename) {
$ruleName = str_replace(".php","",str_replace(__DIR__."/PatternData/Rules/","",$filename));
if ($ruleName[0] != "_") {
$ruleClass = "\PatternLab\PatternData\Rules\\".$ruleName;
$rule = new $ruleClass($options);
self::setRule($ruleName, $rule);
}
}
} | Load all of the rules related to Pattern Data | entailment |
public static function setOption($optionName,$optionValue) {
if (isset(self::$store)) {
self::$store[$optionName] = $optionValue;
return true;
}
return false;
} | Set an options value
@param {String} the name of the option to set
@param {String} the name of the value to give to it
@return {Boolean} if it was set or not | entailment |
public static function setPatternOption($patternStoreKey,$optionName,$optionValue) {
if (isset(self::$store[$patternStoreKey])) {
self::$store[$patternStoreKey][$optionName] = $optionValue;
return true;
}
return false;
} | Set a pattern option value
@param {String} the name of the pattern
@param {String} the name of the option to set
@param {String} the name of the value to give to it
@return {Boolean} if it was set or not | entailment |
public static function setPatternOptionArray($patternStoreKey,$optionName,$optionValue,$optionKey = "") {
if (isset(self::$store[$patternStoreKey]) && isset(self::$store[$patternStoreKey][$optionName]) && is_array(self::$store[$patternStoreKey][$optionName])) {
if (empty($optionKey)) {
self::$store[$patternStoreKey][$optionName][] = $optionValue;
} else {
self::$store[$patternStoreKey][$optionName][$optionKey] = $optionValue;
}
return true;
}
return false;
} | Set a pattern option value for an option element that has an array
@param {String} the name of the pattern
@param {String} the name of the option to set
@param {String} the name of the value to give to it
@param {String} the key to be added to the array
@return {Boolean} if it was set or not | entailment |
public static function setPatternSubOption($patternStoreKey,$optionName,$patternSubStoreKey,$optionSubName,$optionSubValue) {
if (isset(self::$store[$patternStoreKey]) && isset(self::$store[$patternStoreKey][$optionName]) && isset(self::$store[$patternStoreKey][$optionName][$patternSubStoreKey])) {
self::$store[$patternStoreKey][$optionName][$patternSubStoreKey][$optionSubName] = $optionSubValue;
return true;
}
return false;
} | Set a pattern sub option value
@param {String} the name of the pattern
@param {String} the name of the option to check
@param {String} the name of the pattern sub key
@param {String} the name of the option to set
@param {String} the name of the value to give to it
@return {Boolean} if it was set or not | entailment |
public function updateRuleProp($ruleName, $propName, $propValue, $action = "or") {
if ($rule != self::getRule($ruleName)) {
return false;
}
$rule->updateProp($propName, $propValue, $action);
self::setRule($ruleName, $rule);
} | Update a property for a given rule
@param {String} the name of the rule to update
@param {String} the name of the property
@param {String} the value of the property
@param {String} the action that should be taken with the new value
@return {Boolean} whether the update was successful | entailment |
public function serializeToken(AuthToken $token)
{
$payload = $this->encrypter->encrypt(array(
'id' => $token->getAuthIdentifier(),
'key' => $token->getPublicKey())
);
$payload = str_replace(array('+', '/', '\r', '\n', '='), array('-', '_'), $payload);
return $payload;
} | Returns serialized token.
@param AuthToken $token
@return string | entailment |
public function deserializeToken($payload)
{
try {
$payload = str_replace(array('-', '_'), array('+', '/'), $payload);
$data = $this->encrypter->decrypt($payload);
} catch (DecryptException $e) {
return null;
}
if(empty($data['id']) || empty($data['key'])) {
return null;
}
$token = $this->generateAuthToken($data['key']);
$token->setAuthIdentifier($data['id']);
return $token;
} | Deserializes token.
@param string $payload
@return AuthToken|null | entailment |
protected static function cleanDir($dir) {
if (isset($dir[0])) {
$dir = trim($dir);
$dir = ($dir[0] == DIRECTORY_SEPARATOR) ? ltrim($dir, DIRECTORY_SEPARATOR) : $dir;
$dir = ($dir[strlen($dir)-1] == DIRECTORY_SEPARATOR) ? rtrim($dir, DIRECTORY_SEPARATOR) : $dir;
}
return $dir;
} | Clean a given dir from the config file
@param {String} directory to be cleaned
@return {String} cleaned directory | entailment |
public static function getOption($key = "") {
if (!empty($key)) {
$arrayFinder = new ArrayFinder(self::$options);
return $arrayFinder->get($key);
}
return false;
} | Get the value associated with an option from the Config
@param {String} the name of the option to be checked
@return {String/Boolean} the value of the get or false if it wasn't found | entailment |
protected static function getStyleguideKitPath($styleguideKitPath = "") {
$styleguideKitPathFinal = "";
if (isset($styleguideKitPath[0]) && ($styleguideKitPath[0] == DIRECTORY_SEPARATOR)) {
if (strpos($styleguideKitPath, DIRECTORY_SEPARATOR."vendor".DIRECTORY_SEPARATOR === 0)) {
$styleguideKitPathFinal = $styleguideKitPath; // mistaken set-up, pass to final for clean-up
} else if (strpos($styleguideKitPath, self::$options["baseDir"]) === 0) {
$styleguideKitPathFinal = str_replace(self::$options["baseDir"], "", $styleguideKitPath); // just need to peel off the base
} else if (strpos($styleguideKitPath, DIRECTORY_SEPARATOR."vendor") !== false) {
$parts = explode(DIRECTORY_SEPARATOR."vendor".DIRECTORY_SEPARATOR, $styleguideKitPath); // set on another machine's config.yml? try to be smart about it
$styleguideKitPathFinal = "vendor".DIRECTORY_SEPARATOR.$parts[1];
Console::writeInfo("Please double-check the styleguideKitPath option in <path>./config/config.yml</path>. It should be a path relative to the root of your Pattern Lab project...");
}
} else {
$styleguideKitPathFinal = $styleguideKitPath; // fingers crossed everything is fine
}
return $styleguideKitPathFinal;
} | Review the given styleguideKitPath to handle pre-2.1.0 backwards compatibility
@param {String} styleguideKitPath from config.yml
@return {String} the final, post-2.1.0-style styleguideKitPath | entailment |
public static function init($baseDir = "", $verbose = true) {
// make sure a base dir was supplied
if (empty($baseDir)) {
Console::writeError("need a base directory to initialize the config class...");
}
// normalize the baseDir
$baseDir = FileUtil::normalizePath($baseDir);
// double-check the default config file exists
if (!is_dir($baseDir)) {
Console::writeError("make sure ".$baseDir." exists...");
}
// set the baseDir option
self::$options["baseDir"] = ($baseDir[strlen($baseDir)-1] == DIRECTORY_SEPARATOR) ? $baseDir : $baseDir.DIRECTORY_SEPARATOR;
// set-up the paths
self::$userConfigDirClean = self::$options["baseDir"].self::$userConfigDirClean;
self::$userConfigDirDash = self::$options["baseDir"].self::$userConfigDirDash;
self::$userConfigDir = (is_dir(self::$userConfigDirDash)) ? self::$userConfigDirDash : self::$userConfigDirClean;
self::$userConfigPath = self::$userConfigDir.DIRECTORY_SEPARATOR.self::$userConfig;
self::$plConfigPath = self::$options["baseDir"]."vendor/pattern-lab/core/".self::$plConfigPath;
// can't add __DIR__ above so adding here
if (!is_dir(self::$userConfigDir)) {
mkdir(self::$userConfigDir);
}
// check to see if the user config exists, if not create it
if ($verbose) {
Console::writeLine("configuring pattern lab...");
}
// make sure migrate doesn't happen by default
$migrate = false;
$diffVersion = false;
$defaultOptions = array();
$userOptions = array();
// double-check the default config file exists
if (!file_exists(self::$plConfigPath)) {
Console::writeError("the default options for Pattern Lab don't seem to exist at <path>".Console::getHumanReadablePath(self::$plConfigPath)."</path>. please check on the install location of pattern lab...");
}
// set the default config using the pattern lab config
try {
$defaultOptions = Yaml::parse(file_get_contents(self::$plConfigPath));
self::$options = array_merge(self::$options, $defaultOptions);
} catch (ParseException $e) {
Console::writeError("Config parse error in <path>".Console::getHumanReadablePath(self::$plConfigPath)."</path>: ".$e->getMessage());
}
// double-check the user's config exists. if not mark that we should migrate the default one
if (file_exists(self::$userConfigPath)) {
try {
$userOptions = Yaml::parse(file_get_contents(self::$userConfigPath));
self::$options = array_merge(self::$options, $userOptions);
} catch (ParseException $e) {
Console::writeError("Config parse error in <path>".Console::getHumanReadablePath(self::$userConfigPath)."</path>: ".$e->getMessage());
}
} else {
$migrate = true;
}
// compare version numbers
$diffVersion = (isset($userOptions["v"]) && ($userOptions["v"] == $defaultOptions["v"])) ? false : true;
// run an upgrade and migrations if necessary
if ($migrate || $diffVersion) {
if ($verbose) {
Console::writeInfo("upgrading your version of pattern lab...");
}
if ($migrate) {
if (!@copy(self::$plConfigPath, self::$userConfigPath)) {
Console::writeError("make sure that Pattern Lab can write a new config to ".self::$userConfigPath."...");
exit;
}
} else {
self::$options = self::writeNewConfigFile(self::$options, $defaultOptions);
}
}
// making sure the config isn't empty
if (empty(self::$options) && $verbose) {
Console::writeError("a set of configuration options is required to use Pattern Lab...");
exit;
}
// set-up the various dirs
self::$options["configDir"] = self::$userConfigDir;
self::$options["configPath"] = self::$userConfigPath;
self::$options["coreDir"] = is_dir(self::$options["baseDir"]."_core") ? self::$options["baseDir"]."_core" : self::$options["baseDir"]."core";
self::$options["exportDir"] = isset(self::$options["exportDir"]) ? self::$options["baseDir"].self::cleanDir(self::$options["exportDir"]) : self::$options["baseDir"]."exports";
self::$options["publicDir"] = isset(self::$options["publicDir"]) ? self::$options["baseDir"].self::cleanDir(self::$options["publicDir"]) : self::$options["baseDir"]."public";
self::$options["scriptsDir"] = isset(self::$options["scriptsDir"]) ? self::$options["baseDir"].self::cleanDir(self::$options["scriptsDir"]) : self::$options["baseDir"]."scripts";
self::$options["sourceDir"] = isset(self::$options["sourceDir"]) ? self::$options["baseDir"].self::cleanDir(self::$options["sourceDir"]) : self::$options["baseDir"]."source";
self::$options["componentDir"] = isset(self::$options["componentDir"]) ? self::$options["publicDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["componentDir"]) : self::$options["publicDir"].DIRECTORY_SEPARATOR."patternlab-components";
self::$options["dataDir"] = isset(self::$options["dataDir"]) ? self::$options["sourceDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["dataDir"]) : self::$options["sourceDir"].DIRECTORY_SEPARATOR."_data";
self::$options["patternExportDir"] = isset(self::$options["patternExportDir"]) ? self::$options["exportDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["patternExportDir"]) : self::$options["exportDir"].DIRECTORY_SEPARATOR."patterns";
self::$options["patternPublicDir"] = isset(self::$options["patternPublicDir"]) ? self::$options["publicDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["patternPublicDir"]) : self::$options["publicDir"].DIRECTORY_SEPARATOR."patterns";
self::$options["patternSourceDir"] = isset(self::$options["patternSourceDir"]) ? self::$options["sourceDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["patternSourceDir"]) : self::$options["sourceDir"].DIRECTORY_SEPARATOR."_patterns";
self::$options["metaDir"] = isset(self::$options["metaDir"]) ? self::$options["sourceDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["metaDir"]) : self::$options["sourceDir"].DIRECTORY_SEPARATOR."_meta/";
self::$options["annotationsDir"] = isset(self::$options["annotationsDir"]) ? self::$options["sourceDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["annotationsDir"]) : self::$options["sourceDir"].DIRECTORY_SEPARATOR."_annotations/";
// set-up outputFileSuffixes
self::$options["outputFileSuffixes"]["rendered"] = isset(self::$options["outputFileSuffixes"]["rendered"]) ? self::$options["outputFileSuffixes"]["rendered"] : '';
self::$options["outputFileSuffixes"]["rawTemplate"] = isset(self::$options["outputFileSuffixes"]["rawTemplate"]) ? self::$options["outputFileSuffixes"]["rawTemplate"] : '';
self::$options["outputFileSuffixes"]["markupOnly"] = isset(self::$options["outputFileSuffixes"]["markupOnly"]) ? self::$options["outputFileSuffixes"]["markupOnly"] : '.markup-only';
// handle a pre-2.1.0 styleguideKitPath before saving it
if (isset(self::$options["styleguideKitPath"])) {
self::$options["styleguideKitPath"] = self::$options["baseDir"].self::cleanDir(self::getStyleguideKitPath(self::$options["styleguideKitPath"]));
}
// double-check a few directories are real and set-up
FileUtil::checkPathFromConfig(self::$options["sourceDir"], self::$userConfigPath, "sourceDir");
FileUtil::checkPathFromConfig(self::$options["publicDir"], self::$userConfigPath, "publicDir");
// make sure styleguideExcludes is set to an array even if it's empty
if (is_string(self::$options["styleGuideExcludes"])) {
self::$options["styleGuideExcludes"] = array();
}
// set the cacheBuster
self::$options["cacheBuster"] = (self::$options["cacheBusterOn"] == "false") ? 0 : time();
// provide the default for enable CSS. performance hog so it should be run infrequently
self::$options["enableCSS"] = false;
// which of these should be exposed in the front-end?
self::$options["exposedOptions"] = array();
self::setExposedOption("cacheBuster");
self::setExposedOption("defaultPattern");
self::setExposedOption("defaultShowPatternInfo");
self::setExposedOption("patternExtension");
self::setExposedOption("ishFontSize");
self::setExposedOption("ishMaximum");
self::setExposedOption("ishMinimum");
self::setExposedOption("ishViewportRange");
self::setExposedOption("outputFileSuffixes");
self::setExposedOption("patternStates");
self::setExposedOption("theme");
self::setExposedOption("plugins");
} | Adds the config options to a var to be accessed from the rest of the system
If it's an old config or no config exists this will update and generate it.
@param {Boolean} whether we should print out the status of the config being loaded | entailment |
public static function setOption($optionName = "", $optionValue = "") {
if (empty($optionName) || empty($optionValue)) {
return false;
}
$arrayFinder = new ArrayFinder(self::$options);
$arrayFinder->set($optionName, $optionValue);
self::$options = $arrayFinder->get();
} | Add an option and associated value to the base Config
@param {String} the name of the option to be added
@param {String} the value of the option to be added
@return {Boolean} whether the set was successful | entailment |
public static function setExposedOption($optionName = "") {
if (!empty($optionName) && isset(self::$options[$optionName])) {
if (!in_array($optionName,self::$options["exposedOptions"])) {
self::$options["exposedOptions"][] = $optionName;
}
return true;
}
return false;
} | Add an option to the exposedOptions array so it can be exposed on the front-end
@param {String} the name of the option to be added to the exposedOption arrays
@return {Boolean} whether the set was successful | entailment |
public static function updateConfigOption($optionName,$optionValue, $force = false) {
if (is_string($optionValue) && strpos($optionValue,"<prompt>") !== false) {
// prompt for input using the supplied query
$options = "";
$default = "";
$prompt = str_replace("</prompt>","",str_replace("<prompt>","",$optionValue));
if (strpos($prompt, "<default>") !== false) {
$default = explode("<default>",$prompt);
$default = explode("</default>",$default[1]);
$default = $default[0];
}
$input = Console::promptInput($prompt,$options,$default,false);
self::writeUpdateConfigOption($optionName,$input);
Console::writeTag("ok","config option ".$optionName." updated...", false, true);
} else if (!isset(self::$options[$optionName]) || (self::$options["overrideConfig"] == "a") || $force) {
// if the option isn't set or the config is always to override update the config
self::writeUpdateConfigOption($optionName,$optionValue);
} else if (self::$options["overrideConfig"] == "q") {
// standardize the values for comparison
$currentOption = self::getOption($optionName);
$currentOptionValue = $currentOption;
$newOptionValue = $optionValue;
$optionNameOutput = $optionName;
// dive into plugins to do a proper comparison to
if ($optionName == "plugins") {
// replace the data in anticipation of it being used
$optionValue = array_replace_recursive($currentOption, $newOptionValue);
// get the key of the plugin that is being added/updated
reset($newOptionValue);
$newOptionKey = key($newOptionValue);
if (!array_key_exists($newOptionKey, $currentOptionValue)) {
// if the key doesn't exist just write out the new config and move on
self::writeUpdateConfigOption($optionName,$optionValue);
return;
} else {
// see if the existing configs for the plugin exists. if so just return with no changes
if ($newOptionValue[$newOptionKey] == $currentOptionValue[$newOptionKey]) {
return;
} else {
$optionNameOutput = $optionName.".".$newOptionKey;
}
}
}
if ($currentOptionValue != $newOptionValue) {
// prompt for input
if (is_array($currentOptionValue)) {
$prompt = "update the config option <desc>".$optionNameOutput."</desc> with the value from the package install?";
} else {
$prompt = "update the config option <desc>".$optionNameOutput." (".$currentOptionValue.")</desc> with the value <desc>".$newOptionValue."</desc>?";
}$options = "Y/n";
$input = Console::promptInput($prompt,$options,"Y");
if ($input == "y") {
// update the config option
self::writeUpdateConfigOption($optionName,$optionValue);
Console::writeInfo("config option ".$optionNameOutput." updated...", false, true);
} else {
Console::writeWarning("config option <desc>".$optionNameOutput."</desc> not updated...", false, true);
}
}
}
} | Update a single config option based on a change in composer.json
@param {String} the name of the option to be changed
@param {String} the new value of the option to be changed
@param {Boolean} whether to force the update of the option | entailment |
protected static function writeUpdateConfigOption($optionName,$optionValue) {
// parse the YAML options
try {
$options = Yaml::parse(file_get_contents(self::$userConfigPath));
} catch (ParseException $e) {
Console::writeError("Config parse error in <path>".self::$userConfigPath."</path>: ".$e->getMessage());
}
// set this option for the current running of the app
self::setOption($optionName, $optionValue);
// modify the yaml file results
$arrayFinder = new ArrayFinder($options);
$arrayFinder->set($optionName, $optionValue);
$options = $arrayFinder->get();
// dump the YAML
$configOutput = Yaml::dump($options, 3);
// write out the new config file
file_put_contents(self::$userConfigPath,$configOutput);
} | Write out the new config option value
@param {String} the name of the option to be changed
@param {String} the new value of the option to be changed | entailment |
protected static function writeNewConfigFile($oldOptions,$defaultOptions) {
// iterate over the old config and replace values in the new config
foreach ($oldOptions as $key => $value) {
if ($key != "v") {
$defaultOptions[$key] = $value;
}
}
// dump the YAML
$configOutput = Yaml::dump($defaultOptions, 3);
// write out the new config file
file_put_contents(self::$userConfigPath,$configOutput);
return $defaultOptions;
} | Use the default config as a base and update it with old config options. Write out a new user config.
@param {Array} the old configuration file options
@param {Array} the default configuration file options
@return {Array} the new configuration | entailment |
public function say() {
// set a color
$colors = array("ok","options","info","warning");
$randomNumber = rand(0,count($colors)-1);
$color = (isset($colors[$randomNumber])) ? $colors[$randomNumber] : "desc";
// set a 1 in 3 chance that a saying is printed
$randomNumber = rand(0,(count($this->sayings)-1)*3);
if (isset($this->sayings[$randomNumber])) {
Console::writeLine("<".$color.">".$this->sayings[$randomNumber]."...</".$color.">");
}
} | Randomly prints a saying after the generate is complete | entailment |
public function fetchStarterKit($starterkit = "") {
// double-checks options was properly set
if (empty($starterkit)) {
Console::writeError("please provide a path for the starterkit before trying to fetch it...");
}
// figure out the options for the GH path
list($org,$repo,$tag) = $this->getPackageInfo($starterkit);
// set default attributes
$sourceDir = Config::getOption("sourceDir");
$tempDir = sys_get_temp_dir().DIRECTORY_SEPARATOR."pl-sk";
$tempDirSK = $tempDir.DIRECTORY_SEPARATOR."pl-sk-archive";
$tempDirDist = $tempDirSK.DIRECTORY_SEPARATOR.$repo."-".$tag.DIRECTORY_SEPARATOR."dist";
$tempComposerFile = $tempDirSK.DIRECTORY_SEPARATOR.$repo."-".$tag.DIRECTORY_SEPARATOR."composer.json";
//get the path to the GH repo and validate it
$tarballUrl = "https://github.com/".$org."/".$repo."/archive/".$tag.".tar.gz";
Console::writeInfo("downloading the starterkit. this may take a few minutes...");
// try to download the given package
if (!$package = @file_get_contents($tarballUrl)) {
$error = error_get_last();
Console::writeError("the starterkit wasn't downloaded because:\n\n ".$error["message"]);
}
// Create temp directory if doesn't exist
$fs = new Filesystem();
try {
$fs->mkdir($tempDir, 0775);
} catch (IOExceptionInterface $e) {
Console::writeError("Error creating temporary directory at " . $e->getPath());
}
// write the package to the temp directory
$tempFile = tempnam($tempDir, "pl-sk-archive.tar.gz");
file_put_contents($tempFile, $package);
Console::writeInfo("finished downloading the starterkit...");
// make sure the temp dir exists before copying into it
if (!is_dir($tempDirSK)) {
mkdir($tempDirSK);
}
// extract, if the zip is supposed to be unpacked do that (e.g. stripdir)
try {
$zippy = Zippy::load();
$zippy->addStrategy(new UnpackFileStrategy());
$zippy->getAdapterFor('tar.gz')->open($tempFile)->extract($tempDirSK);
} catch(\RuntimeException $e) {
Console::writeError("failed to extract the starterkit. easiest solution is to manually download it and copy <path>./dist</path to <path>./source/</path>...");
}
if (!is_dir($tempDirDist)) {
// try without repo dir
$tempDirDist = $tempDirSK.DIRECTORY_SEPARATOR."dist";
}
// thrown an error if temp/dist/ doesn't exist
if (!is_dir($tempDirDist)) {
Console::writeError("the starterkit needs to contain a dist/ directory before it can be installed...");
}
// check for composer.json. if it exists use it for determining things. otherwise just mirror dist/ to source/
if (file_exists($tempComposerFile)) {
$tempComposerJSON = json_decode(file_get_contents($tempComposerFile), true);
// see if it has a patternlab section that might define the files to move
if (isset($tempComposerJSON["extra"]) && isset($tempComposerJSON["extra"]["patternlab"])) {
Console::writeInfo("installing the starterkit...");
InstallerUtil::parseComposerExtraList($tempComposerJSON["extra"]["patternlab"], $starterkit, $tempDirDist);
Console::writeInfo("installed the starterkit...");
} else {
$this->mirrorDist($sourceDir, $tempDirDist);
}
} else {
$this->mirrorDist($sourceDir, $tempDirDist);
}
// remove the temp files
Console::writeInfo("cleaning up the temp files...");
$fs = new Filesystem();
$fs->remove($tempFile);
$fs->remove($tempDirSK);
Console::writeInfo("the starterkit installation is complete...");
return true;
} | Fetch a package from GitHub
@param {String} the command option to provide the rule for
@param {String} the path to the package to be downloaded
@return {String} the modified file contents | entailment |
protected function getPackageInfo($package) {
$org = "";
$repo = "";
$tag = "master";
if (strpos($package, "#") !== false) {
list($package,$tag) = explode("#",$package);
}
if (strpos($package, "/") !== false) {
list($org,$repo) = explode("/",$package);
} else {
Console::writeError("please provide a real path to a package...");
}
return array($org,$repo,$tag);
} | Break up the package path
@param {String} path of the GitHub repo
@return {Array} the parts of the package path | entailment |
protected function mirrorDist($sourceDir, $tempDirDist) {
// set default vars
$fsOptions = array();
$emptyDir = true;
$validFiles = array("README",".gitkeep",".DS_Store","styleguide","patternlab-components");
// see if the source directory is empty
if (is_dir($sourceDir)) {
$objects = new \DirectoryIterator($sourceDir);
foreach ($objects as $object) {
if (!$object->isDot() && !in_array($object->getFilename(),$validFiles)) {
$emptyDir = false;
break;
}
}
}
// if source directory isn't empty ask if it's ok to nuke what's there
if (!$emptyDir) {
$prompt = "a starterkit is already installed. merge the new files with it or replace it?";
$options = "M/r";
$input = Console::promptInput($prompt,$options,"M");
$fsOptions = ($input == "r") ? array("delete" => true, "override" => true) : array("delete" => false, "override" => false);
}
// mirror dist to source
Console::writeInfo("installing the starterkit files...");
$fs = new Filesystem();
$fs->mirror($tempDirDist, $sourceDir, null, $fsOptions);
Console::writeInfo("starterkit files have been installed...");
} | Force mirror the dist/ folder to source/
@param {String} path to the source directory
@param {String} path to the temp dist directory | entailment |
public static function convertYAML($text) {
try {
$yaml = YAML::parse($text);
} catch (ParseException $e) {
printf("unable to parse documentation: %s..\n", $e->getMessage());
}
// single line of text won't throw a YAML error. returns as string
if (gettype($yaml) == "string") {
$yaml = array();
}
return $yaml;
} | Parse YAML data into an array
@param {String} the text to be parsed
@return {Array} the parsed content | entailment |
public static function parse($text) {
self::setLineEndings();
// set-up defaults
$yaml = array();
$markdown = "";
// read in the content
// based on: https://github.com/mnapoli/FrontYAML/blob/master/src/Parser.php
$lines = explode(PHP_EOL, $text);
if (count($lines) <= 1) {
$markdown = self::convertMarkdown($text);
return array($yaml,$markdown);
}
if (rtrim($lines[0]) !== '---') {
$markdown = self::convertMarkdown($text);
return array($yaml,$markdown);
}
$head = array();
unset($lines[0]);
$i = 1;
foreach ($lines as $line) {
if ($line === '---') {
break;
}
$head[] = $line;
$i++;
}
$head = implode(PHP_EOL, $head);
$body = implode(PHP_EOL, array_slice($lines, $i));
$yaml = self::convertYAML($head);
$markdown = self::convertMarkdown($body);
return array($yaml,$markdown);
} | Find and convert YAML and markdown in Pattern Lab documention files
@param {String} the text to be chunked for YAML and markdown
@return {Array} array containing both the YAML and converted markdown | entailment |
public function handleQuery(HTTPRequest $request)
{
//get requested model(s) details
$model = $request->param('ModelReference');
$modelMap = Config::inst()->get(self::class, 'models');
if (array_key_exists($model, $modelMap)) {
$model = $modelMap[$model];
}
$id = $request->param('ID');
$response = false;
$queryParams = $this->parseQueryParameters($request->getVars());
//validate Model name + store
if ($model) {
$model = $this->deSerializer->unformatName($model);
if (!class_exists($model)) {
return new RESTfulAPIError(400,
"Model does not exist. Received '$model'."
);
} else {
//store requested model data and query data
$this->requestedData['model'] = $model;
}
} else {
//if model missing, stop + return blank object
return new RESTfulAPIError(400,
"Missing Model parameter."
);
}
//check API access rules on model
if (!RESTfulAPI::api_access_control($model, $request->httpMethod())) {
return new RESTfulAPIError(403,
"API access denied."
);
}
//validate ID + store
if (($request->isPUT() || $request->isDELETE()) && !is_numeric($id)) {
return new RESTfulAPIError(400,
"Invalid or missing ID. Received '$id'."
);
} elseif ($id !== null && !is_numeric($id)) {
return new RESTfulAPIError(400,
"Invalid ID. Received '$id'."
);
} else {
$this->requestedData['id'] = $id;
}
//store query parameters
if ($queryParams) {
$this->requestedData['params'] = $queryParams;
}
//map HTTP word to module method
switch ($request->httpMethod()) {
case 'GET':
return $this->findModel($model, $id, $queryParams, $request);
break;
case 'POST':
return $this->createModel($model, $request);
break;
case 'PUT':
return $this->updateModel($model, $id, $request);
break;
case 'DELETE':
return $this->deleteModel($model, $id, $request);
break;
default:
return new RESTfulAPIError(403,
"HTTP method mismatch."
);
break;
}
} | All requests pass through here and are redirected depending on HTTP verb and params
@param HTTPRequest $request HTTP request
@return DataObjec|DataList DataObject/DataList result or stdClass on error | entailment |
public function parseQueryParameters(array $params)
{
$parsedParams = array();
$searchFilterModifiersSeparator = Config::inst()->get(self::class, 'searchFilterModifiersSeparator');
foreach ($params as $key__mod => $value) {
// skip url, flush, flushtoken
if (in_array(strtoupper($key__mod), Config::inst()->get(self::class, 'skipedQueryParameters'))) {
continue;
}
$param = array();
$key__mod = explode(
$searchFilterModifiersSeparator,
$key__mod
);
$param['Column'] = $this->deSerializer->unformatName($key__mod[0]);
$param['Value'] = $value;
if (isset($key__mod[1])) {
$param['Modifier'] = $key__mod[1];
} else {
$param['Modifier'] = null;
}
array_push($parsedParams, $param);
}
return $parsedParams;
} | Parse the query parameters to appropriate Column, Value, Search Filter Modifiers
array(
array(
'Column' => ColumnName,
'Value' => ColumnValue,
'Modifier' => ModifierType
)
)
@param array $params raw GET vars array
@return array formatted query parameters | entailment |
public function findModel($model, $id = false, $queryParams, HTTPRequest $request)
{
if ($id) {
$return = DataObject::get_by_id($model, $id);
if (!$return) {
return new RESTfulAPIError(404,
"Model $id of $model not found."
);
} elseif (!RESTfulAPI::api_access_control($return, $request->httpMethod())) {
return new RESTfulAPIError(403,
"API access denied."
);
}
} else {
$return = DataList::create($model);
$singletonModel = singleton($model);
if (count($queryParams) > 0) {
foreach ($queryParams as $param) {
if ($param['Column'] && $singletonModel->hasDatabaseField($param['Column'])) {
// handle sorting by column
if ($param['Modifier'] === 'sort') {
$return = $return->sort(array(
$param['Column'] => $param['Value'],
));
}
// normal modifiers / search filters
elseif ($param['Modifier']) {
$return = $return->filter(array(
$param['Column'] . ':' . $param['Modifier'] => $param['Value'],
));
}
// no modifier / search filter
else {
$return = $return->filter(array(
$param['Column'] => $param['Value'],
));
}
} else {
// random
if ($param['Modifier'] === 'rand') {
// rand + seed
if ($param['Value']) {
$return = $return->sort('RAND(' . $param['Value'] . ')');
}
// rand only >> FIX: gen seed to avoid random result on relations
else {
$return = $return->sort('RAND(' . time() . ')');
}
}
// limits
elseif ($param['Modifier'] === 'limit') {
// range + offset
if (is_array($param['Value'])) {
$return = $return->limit($param['Value'][0], $param['Value'][1]);
}
// range only
else {
$return = $return->limit($param['Value']);
}
}
}
}
}
//sets default limit if none given
$limits = $return->dataQuery()->query()->getLimit();
$limitConfig = Config::inst()->get(self::class, 'max_records_limit');
if (is_array($limits) && !array_key_exists('limit', $limits) && $limitConfig >= 0) {
$return = $return->limit($limitConfig);
}
}
return $return;
} | Finds 1 or more objects of class $model
Handles column modifiers: :StartsWith, :EndsWith,
:PartialMatch, :GreaterThan, :LessThan, :Negation
and query modifiers: sort, rand, limit
@param string $model Model(s) class to find
@param boolean|integr $id The ID of the model to find or false
@param array $queryParams Query parameters and modifiers
@param HTTPRequest $request The original HTTP request
@return DataObject|DataList Result of the search (note: DataList can be empty) | entailment |
public function createModel($model, HTTPRequest $request)
{
if (!RESTfulAPI::api_access_control($model, $request->httpMethod())) {
return new RESTfulAPIError(403,
"API access denied."
);
}
$newModel = Injector::inst()->create($model);
return $this->updateModel($newModel, $newModel->ID, $request);
} | Create object of class $model
@param string $model
@param HTTPRequest $request
@return DataObject | entailment |
public function updateModel($model, $id, $request)
{
if (is_string($model)) {
$model = DataObject::get_by_id($model, $id);
}
if (!$model) {
return new RESTfulAPIError(404,
"Record not found."
);
}
if (!RESTfulAPI::api_access_control($model, $request->httpMethod())) {
return new RESTfulAPIError(403,
"API access denied."
);
}
$rawJson = $request->getBody();
// Before deserialize hook
if (method_exists($model, 'onBeforeDeserialize')) {
$model->onBeforeDeserialize($rawJson);
}
$model->extend('onBeforeDeserialize', $rawJson);
$payload = $this->deSerializer->deserialize($rawJson);
if ($payload instanceof RESTfulAPIError) {
return $payload;
}
// After deserialize hook
if (method_exists($model, 'onAfterDeserialize')) {
$model->onAfterDeserialize($payload);
}
$model->extend('onAfterDeserialize', $payload);
if ($model && $payload) {
$has_one = Config::inst()->get(get_class($model), 'has_one');
$has_many = Config::inst()->get(get_class($model), 'has_many');
$many_many = Config::inst()->get(get_class($model), 'many_many');
$belongs_many_many = Config::inst()->get(get_class($model), 'belongs_many_many');
$many_many_extraFields = array();
if (isset($payload['ManyManyExtraFields'])) {
$many_many_extraFields = $payload['ManyManyExtraFields'];
unset($payload['ManyManyExtraFields']);
}
$hasChanges = false;
$hasRelationChanges = false;
foreach ($payload as $attribute => $value) {
if (!is_array($value)) {
if (is_array($has_one) && array_key_exists($attribute, $has_one)) {
$relation = $attribute . 'ID';
$model->$relation = $value;
$hasChanges = true;
} elseif ($model->{$attribute} != $value) {
$model->{$attribute} = $value;
$hasChanges = true;
}
} else {
//has_many, many_many or $belong_many_many
if ((is_array($has_many) && array_key_exists($attribute, $has_many))
|| (is_array($many_many) && array_key_exists($attribute, $many_many))
|| (is_array($belongs_many_many) && array_key_exists($attribute, $belongs_many_many))
) {
$hasRelationChanges = true;
$ssList = $model->{$attribute}();
$ssList->removeAll(); //reset list
foreach ($value as $id) {
// check if there is extraFields
if (array_key_exists($attribute, $many_many_extraFields)) {
if (isset($many_many_extraFields[$attribute][$id])) {
$ssList->add($id, $many_many_extraFields[$attribute][$id]);
continue;
}
}
$ssList->add($id);
}
}
}
}
if ($hasChanges || !$model->ID) {
try {
$id = $model->write(false, false, false, $hasRelationChanges);
} catch (ValidationException $exception) {
$error = $exception->getResult();
$messages = [];
foreach ($error->getMessages() as $message) {
$fieldName = $message['fieldName'];
if ($fieldName) {
$messages[] = "{$fieldName}: {$message['message']}";
} else {
$messages[] = $message['message'];
}
}
return new RESTfulAPIError(400,
implode("\n", $messages)
);
}
if (!$id) {
return new RESTfulAPIError(500,
"Error writting data."
);
} else {
return DataObject::get_by_id($model->ClassName, $id);
}
} else {
return $model;
}
} else {
return new RESTfulAPIError(400,
"Missing model or payload."
);
}
} | Update databse record or $model
@param String|DataObject $model the model or class to update
@param Integer $id The ID of the model to update
@param HTTPRequest the original request
@return DataObject The updated model | entailment |
public function deleteModel($model, $id, HTTPRequest $request)
{
if ($id) {
$object = DataObject::get_by_id($model, $id);
if ($object) {
if (!RESTfulAPI::api_access_control($object, $request->httpMethod())) {
return new RESTfulAPIError(403,
"API access denied."
);
}
$object->delete();
} else {
return new RESTfulAPIError(404,
"Record not found."
);
}
} else {
//shouldn't happen but just in case
return new RESTfulAPIError(400,
"Invalid or missing ID. Received '$id'."
);
}
return null;
} | Delete object of Class $model and ID $id
@todo Respond with a 204 status message on success?
@param string $model Model class
@param integer $id Model ID
@param HTTPRequest $request Model ID
@return NULL|array NULL if successful or array with error detail | entailment |
public function middleware($middleware) : ControllerMiddlewareOptions
{
if (!is_array($middleware)) {
$middleware = [$middleware];
}
$options = new ControllerMiddlewareOptions;
foreach ($middleware as $m) {
$this->middleware[] = new ControllerMiddleware($m, $options);
}
return $options;
} | Add Middleware
@param Psr\Http\Server\MiddlewareInterface|array $middleware
@return Rareloop\Router\ControllerMiddlewareOptions | entailment |
public function getCommand()
{
$options = $this->getOptions();
$arguments = $this->getArguments();
$to = null;
$from = $arguments['from'];
if (true === isset($arguments['to'])) {
$to = $arguments['to'];
}
array_walk($options, function (&$option) {
$option = '--' . $option;
});
array_walk($arguments, function (&$value, $argument) {
$value = '--' . $argument . '=' . $value;
});
return trim(sprintf('%s %s %s', $this->getBaseCommand(), $this->getRange($from, $to), join(' ', $options)));
} | Returns the compiled VCS log command.
@return string | entailment |
public function setHeaders(array $headers)
{
$this->headerRemove();
foreach ($headers as $name => $values) {
foreach ((array)$values as $value) {
$this->header("$name: $value", false);
}
}
} | Set the headers
@param array $headers | entailment |
protected function splitHeader($header)
{
list($name, $value) = explode(':', $header, 2);
return [trim($name), trim($value), strtolower(trim($name))];
} | Split a header string in name and value
@param string $header
@return array [name, value, key] | entailment |
public function getHeaders()
{
$names = [];
$values = [];
$list = $this->headersList();
foreach ($list as $header) {
list($name, $value, $key) = $this->splitHeader($header);
if (!isset($names[$key])) {
$names[$key] = $name;
$values[$key] = [];
}
$values[$key][] = $value;
}
$headers = [];
foreach ($names as $key => $name) {
$headers[$name] = $values[$key];
}
return $headers;
} | Retrieves all message header values.
The keys represent the header name as it will be sent over the wire, and
each value is an array of strings associated with the header.
// Represent the headers as a string
foreach ($message->getHeaders() as $name => $values) {
echo $name.': '.implode(', ', $values);
}
// Emit headers iteratively:
foreach ($message->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
@return string[][] Returns an associative array of the message's headers.
Each key is a header name, and each value is an array of strings for
that header. | entailment |
public function hasHeader($name)
{
$this->assertHeaderName($name);
$find = strtolower($name);
$found = false;
foreach ($this->headersList() as $header) {
list(, , $key) = $this->splitHeader($header);
if ($key === $find) {
$found = true;
break;
}
}
return $found;
} | Checks if a header exists by the given case-insensitive name.
@param string $name
Case-insensitive header field name.
@return bool Returns true if any header names match the given header
name using a case-insensitive string comparison. Returns false if
no matching header name is found in the message. | entailment |
public function getHeader($name)
{
$this->assertHeaderName($name);
$find = strtolower($name);
$values = [];
foreach ($this->headersList() as $header) {
list(, $value, $key) = $this->splitHeader($header);
if ($key === $find) {
$values[] = $value;
}
}
return $values;
} | Retrieves a message header value by the given case-insensitive name.
This method returns an array of all the header values of the given
case-insensitive header name.
@param string $name
Case-insensitive header field name.
@return string[] An array of string values as provided for the given
header. If the header does not appear in the message, this method MUST
return an empty array. | entailment |
protected function withHeaderLogic($name, $value, $add)
{
$this->assertHeaderName($name);
$this->assertHeaderValue($value);
$this->assertHeadersNotSent();
foreach ((array)$value as $val) {
$this->header("{$name}: {$val}", !$add);
}
return $this;
} | Abstraction for `withHeader` and `withAddedHeader`
@param string $name Case-insensitive header field name.
@param string|string[] $value Header value(s).
@param boolean $add
@return static
@throws \InvalidArgumentException for invalid header names or values.
@throws \RuntimeException if headers are already sent | entailment |
public function withoutHeader($name)
{
$this->assertHeaderName($name);
if (!$this->hasHeader($name)) {
return $this;
}
$this->assertHeadersNotSent();
$this->headerRemove($name);
return $this;
} | Return an instance without the specified header.
@param string $name Case-insensitive header field name to remove.
@return static | entailment |
protected function reset()
{
$this->protocolVersion = null;
$this->headers = null;
$this->requestTarget = null;
$this->method = null;
$this->uri = null;
} | Remove all set and cached values | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.