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'; ...
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])) { $th...
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. ...
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, $...
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); retur...
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_...
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 ...
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["ca...
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"); ...
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["patternSpec...
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"][$optionNa...
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...
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/cl...
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."&&".$propVa...
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)...
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, '_'); $w...
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 se...
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($...
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))) { $th...
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 ...
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) { ...
Get a ruleset, and merge it with saving if required. @deprecated watson/validating@0.10.9 @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...
Add rules to the existing rules or ruleset, overriding any existing. @deprecated watson/validating@0.10.9 @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 {...
Remove rules from the existing rules or ruleset. @deprecated watson/validating@0.10.9 @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/validating@0.10.9 @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/validating@0.10.9) @param bool $mergeWithSaving (@deprecated watson/validating@0.10.9) @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/validating@0.10.9 @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...
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...
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) $comman...
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 rule...
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 n...
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->...
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>. not...
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...
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::write...
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."/patte...
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',$f...
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); ...
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])) { $patter...
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("-"...
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(strrc...
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 ...
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 $ins...
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((mem...
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(); // clea...
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...
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[$patternS...
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...
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[...
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 {Boole...
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; }...
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 = ...
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 d...
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>","...
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...
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($defaultO...
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($thi...
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...
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("ple...
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 \Directo...
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(); ...
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 =...
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]; } ...
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...
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." ); ...
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...
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 ...
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_acce...
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, ...
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, ...
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)...
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...
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 hea...
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) { ...
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) { ...
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 ...
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...
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