sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function where($where) { if(is_array($where) && !empty($where)) { $wherefields = array(); foreach($where as $field => $value) { $wherefields[] = $this->formatValues($field, $value); } if(!empty($wherefields)) { return " WHERE ".implode(' AND ', $wherefields); } } return false; }
This outputs the SQL where query based on a given array @param array $where This should be an array that you wish to create the where query for in the for array('field1' => 'test') or array('field1' => array('>=', 0)) @return string|false If the where query is an array will return the where string and set the values else returns false if no array sent
entailment
private function orderBy($order) { if(is_array($order) && !empty(array_filter($order))) { $string = array(); foreach($order as $fieldorder => $fieldvalue) { if(!empty($fieldorder) && !empty($fieldvalue)) { $string[] = sprintf("`%s` %s", SafeString::makeSafe($fieldorder), strtoupper(SafeString::makeSafe($fieldvalue))); } elseif($fieldvalue === 'RAND()') { $string[] = $fieldvalue; } } return sprintf(" ORDER BY %s", implode(", ", $string)); } elseif($order == 'RAND()') { return " ORDER BY RAND()"; } return false; }
Sets the order sting for the SQL query based on an array or string @param array|string $order This should be either set to array('fieldname' => 'ASC/DESC') or RAND() @return string|false If the SQL query has an valid order by will return a string else returns false
entailment
private function fields($records, $insert = false) { $fields = array(); foreach($records as $field => $value) { if($insert === true) { $fields[] = sprintf("`%s`", SafeString::makeSafe($field)); $this->prepare[] = '?'; } else{ $fields[] = sprintf("`%s` = ?", SafeString::makeSafe($field)); } $this->values[] = $value; } return implode(', ', $fields); }
Build the field list for the query @param array $records This should be an array listing all of the fields @param boolean $insert If this is an insert statement should be set to true to create the correct amount of queries for the prepared statement @return string The fields list will be returned as a string to insert into the SQL query
entailment
private function limit($limit = 0) { if(is_array($limit) && !empty(array_filter($limit))) { foreach($limit as $start => $end) { return " LIMIT ".intval($start).", ".intval($end); } } elseif((int)$limit > 0) { return " LIMIT ".intval($limit); } return false; }
Returns the limit SQL for the current query as a string @param integer|array $limit This should either be set as an integer or should be set as an array with a start and end value @return string|false Will return the LIMIT string for the current query if it is valid else returns false
entailment
public function setCache($key, $value) { if($this->cacheEnabled) { $this->cacheObj->save($key, $value); } }
Set the cache with a key and value @param string $key The unique key to store the value against @param mixed $value The value of the MYSQL query
entailment
public function getCache($key) { if($this->modified === true || !$this->cacheEnabled) {return false;} else{ $this->cacheValue = $this->cacheObj->fetch($key); return $this->cacheValue; } }
Get the results for a given key @param string $key The unique key to check for stored variables @return mixed Returned the cached results from
entailment
protected function formatValues($field, $value) { if(!is_array($value) && Operators::isOperatorValid($value) && !Operators::isOperatorPrepared($value)) { return sprintf("`%s` %s", SafeString::makeSafe($field), Operators::getOperatorFormat($value)); } elseif(is_array($value)) { $keys = []; if(!is_array(array_values($value)[0])) { $this->values[] = (isset($value[1]) ? $value[1] : array_values($value)[0]); $operator = (isset($value[0]) ? $value[0] : key($value)); } else{ foreach(array_values($value)[0] as $op => $array_value) { $this->values[] = $array_value; $keys[] = '?'; } $operator = key($value); } return sprintf("`%s` %s", SafeString::makeSafe($field), sprintf(Operators::getOperatorFormat($operator), implode($keys, ', '))); } $this->values[] = $value; return sprintf("`%s` = ?", SafeString::makeSafe($field)); }
Format the where queries and set the prepared values @param string $field This should be the field name in the database @param mixed $value This should be the value which should either be a string or an array if it contains an operator @return string This should be the string to add to the SQL query
entailment
protected function bindValues($values) { if(is_array($values)) { foreach($values as $i => $value) { if(is_numeric($value) && intval($value) == $value && $value[0] != 0) {$type = PDO::PARAM_INT; $value = intval($value);} elseif(is_null($value) || $value === 'NULL') {$type = PDO::PARAM_NULL; $value = NULL;} elseif(is_bool($value)) {$type = PDO::PARAM_BOOL;} else{$type = PDO::PARAM_STR;} $this->query->bindValue(intval($i + 1), $value, $type); } } }
Band values to use in the query @param array $values This should be the values being used in the query
entailment
public function check(ExerciseInterface $exercise, Input $input) { if (!$exercise instanceof ComposerExerciseCheck) { throw new \InvalidArgumentException; } if (!file_exists(sprintf('%s/composer.json', dirname($input->getArgument('program'))))) { return new Failure($this->getName(), 'No composer.json file found'); } if (!file_exists(sprintf('%s/composer.lock', dirname($input->getArgument('program'))))) { return new Failure($this->getName(), 'No composer.lock file found'); } if (!file_exists(sprintf('%s/vendor', dirname($input->getArgument('program'))))) { return new Failure($this->getName(), 'No vendor folder found'); } $lockFile = new LockFileParser(sprintf('%s/composer.lock', dirname($input->getArgument('program')))); $missingPackages = array_filter($exercise->getRequiredPackages(), function ($package) use ($lockFile) { return !$lockFile->hasInstalledPackage($package); }); if (count($missingPackages) > 0) { return new Failure( $this->getName(), sprintf( 'Lockfile doesn\'t include the following packages at any version: "%s"', implode('", "', $missingPackages) ) ); } return new Success($this->getName()); }
This check parses the `composer.lock` file and checks that the student installed a set of required packages. If they did not a failure is returned, otherwise, a success is returned. @param ExerciseInterface $exercise The exercise to check against. @param Input $input The command line arguments passed to the command. @return ResultInterface The result of the check.
entailment
public function getEpcValidUntil($format = 'Y-m-d') { if ($this->epcValidUntil instanceof \DateTime && $format !== null) { return $this->epcValidUntil->format($format); } return $this->epcValidUntil; }
@param string $format formats the date to the specific format, null returns DateTime @return \DateTime|string
entailment
public function setProjectState($projectState) { $this->projectState = $projectState; //BC if ($projectState === self::PROJECT_STATE_BUILDING) { $this->underConstruction = true; } return $this; }
@param string $projectState @return $this
entailment
public function getCompletionDate($format = 'Y-m-d') { if ($this->completionDate instanceof \DateTime && $format !== null) { return $this->completionDate->format($format); } return $this->completionDate; }
@param string $format formats the date to the specific format, null returns DateTime @return \DateTime|string
entailment
public function getSaleStart($format = 'Y-m-d') { if ($this->saleStart instanceof \DateTime && $format !== null) { return $this->saleStart->format($format); } return $this->saleStart; }
@param string $format formats the date to the specific format, null returns DateTime @return \DateTime|string
entailment
public function getCreatedAt($format = 'Y-m-d H:i:s') { if ($this->createdAt instanceof \DateTime && $format !== null) { return $this->createdAt->format($format); } return $this->createdAt; }
@param string $format formats the date time to the specific format, null returns DateTime @return \DateTime|string
entailment
public function convertToDouble($number) { $number = str_replace(',', '.', (string) $number); if (!is_numeric($number)) { throw new \UnexpectedValueException("{$number} não é um número válido"); } return (float) number_format($number, 2, '.', ''); }
@param mixed $number @return float
entailment
public function setRegionalAddition($regionalerZusatz) { //bc compat to old list format if ($this->proximity === null) { $this->proximity = $regionalerZusatz; } $this->regionalAddition = $regionalerZusatz; return $this; }
@param null $regionalerZusatz @return $this
entailment
public function getProcuredAt($format = 'Y-m-d') { if ($this->procuredAt instanceof \DateTime && $format !== null) { return $this->procuredAt->format($format); } return $this->procuredAt; }
@param string $format formats the date to the specific format, null returns DateTime @return \DateTime|string
entailment
public function getUpdatedAt($format = 'Y-m-d H:i:s') { if ($this->updatedAt instanceof \DateTime && $format !== null) { return $this->updatedAt->format($format); } return $this->updatedAt; }
@param string $format formats the date to the specific format, null returns DateTime @return \DateTime|string
entailment
public function render(ResultsRenderer $renderer) { $results = array_filter($this->result->getResults(), function (ResultInterface $result) { return $result instanceof FailureInterface; }); $output = ''; if (count($results)) { $output .= $renderer->center("Some executions of your solution produced incorrect output!\n"); } /** @var FailureInterface $request **/ foreach ($results as $key => $request) { $output .= $renderer->lineBreak(); $output .= "\n"; $output .= $renderer->style(sprintf('Execution %d', $key + 1), ['bold', 'underline', 'blue']); $output .= ' ' . $renderer->style(' FAILED ', ['bg_red', 'bold']) . "\n\n"; $output .= $request->getArgs()->isEmpty() ? "Arguments: None\n" : sprintf("Arguments: \"%s\"\n", $request->getArgs()->implode('", "')); $output .= "\n" . $renderer->renderResult($request) . "\n"; } return $output; }
Render the details of each failed request including the mismatching headers and body. @param ResultsRenderer $renderer @return string
entailment
public function run() { $container = $this->getContainer(); foreach ($this->exercises as $exercise) { if (false === $container->has($exercise)) { throw new \RuntimeException( sprintf('No DI config found for exercise: "%s". Register a factory.', $exercise) ); } } $checkRepository = $container->get(CheckRepository::class); foreach ($this->checks as $check) { if (false === $container->has($check)) { throw new \RuntimeException( sprintf('No DI config found for check: "%s". Register a factory.', $check) ); } $checkRepository->registerCheck($container->get($check)); } if (!empty($this->results)) { $resultFactory = $container->get(ResultRendererFactory::class); foreach ($this->results as $result) { $resultFactory->registerRenderer($result['resultClass'], $result['resultRendererClass']); } } try { $exitCode = $container->get(CommandRouter::class)->route(); } catch (MissingArgumentException $e) { $container ->get(OutputInterface::class) ->printError( sprintf( 'Argument%s: "%s" %s missing!', count($e->getMissingArguments()) > 1 ? 's' : '', implode('", "', $e->getMissingArguments()), count($e->getMissingArguments()) > 1 ? 'are' : 'is' ) ); return 1; } catch (\RuntimeException $e) { $container ->get(OutputInterface::class) ->printError( sprintf( '%s', $e->getMessage() ) ); return 1; } return $exitCode; }
Executes the framework, invoking the specified command. The return value is the exit code. 0 for success, anything else is a failure. @return int The exit code
entailment
protected function determineType() { if (in_array($this->group, static::$linkGroups)) { return 'link'; } if (in_array($this->extension, static::$pictureExtensions)) { return 'picture'; } if (in_array($this->extension, static::$videoExtensions)) { return 'video'; } return 'document'; }
Tries to determine type by extention or group @return string
entailment
public function populate(stdClass $response) { $transaction = $this->transaction($response); $transaction->creditCard = $this->creditCard($response); if (isset($response->id_assinatura)) { $transaction->subscription = $this->subscription($response); } return $transaction; }
@param stdClass $response @return stdClass
entailment
public function transformSingle($data) { $xml = new \SimpleXMLElement($data); if (isset($xml->immobilie)) { $xml = $xml->immobilie; } $objekt = new Realty(); //basic attributes from list view $this->map($this->simpleMapping, $xml, $objekt); //list object attachment mapping if (isset($xml->erstes_bild)) { $objekt->addAttachment(new Attachment((string) $xml->erstes_bild)); } if (isset($xml->zweites_bild)) { $objekt->addAttachment(new Attachment((string) $xml->zweites_bild)); } //detailed attributes from detail view, OpenImmo if (isset($xml->verwaltung_techn)) { $objekt->setId((int) $xml->verwaltung_techn->objektnr_intern); $objekt->setPropertyNumber((string) $xml->verwaltung_techn->objektnr_extern); $objekt->setProjectId((int) $xml->verwaltung_techn->projekt_id); foreach ($xml->verwaltung_techn->user_defined_simplefield as $simpleField) { $this->mapSimpleField($simpleField, $objekt); } } if (isset($xml->verwaltung_objekt)) { $objekt->setStatus($this->cast($xml->verwaltung_objekt->status)); $objekt->setStatusId($this->cast($xml->verwaltung_objekt->status_id)); $objekt->setAvailableFrom($this->cast($xml->verwaltung_objekt->verfuegbar_ab)); if (isset($xml->verwaltung_objekt->max_mietdauer)) { $objekt->setRentDuration($this->cast($xml->verwaltung_objekt->max_mietdauer, 'int')); if ($xml->verwaltung_objekt->max_mietdauer->attributes()->max_dauer == 'JAHR') { $objekt->setRentDurationType('year'); } elseif ($xml->verwaltung_objekt->max_mietdauer->attributes()->max_dauer == 'MONAT') { $objekt->setRentDurationType('month'); } } if (isset($xml->verwaltung_objekt->user_defined_anyfield) && isset($xml->verwaltung_objekt->user_defined_anyfield->justimmo_kategorie)) { foreach ($xml->verwaltung_objekt->user_defined_anyfield->justimmo_kategorie as $category) { $objekt->addCategory((int) $category['id'], (string) $category); } } foreach ($xml->verwaltung_objekt->user_defined_simplefield as $simpleField) { $this->mapSimpleField($simpleField, $objekt); } } if (isset($xml->objektkategorie)) { if (isset($xml->objektkategorie->objektart)) { $objekt->setRealtyType((string) $xml->objektkategorie->objektart->children()->getName()); $objekt->setSubRealtyType((string) $xml->objektkategorie->objektart->children()->attributes()); } if (isset($xml->objektkategorie->nutzungsart)) { $objekt->setOccupancy(filter_var_array($this->attributesToArray($xml->objektkategorie->nutzungsart->attributes()), FILTER_VALIDATE_BOOLEAN)); } if (isset($xml->objektkategorie->vermarktungsart)) { $objekt->setMarketingType(filter_var_array($this->attributesToArray($xml->objektkategorie->vermarktungsart->attributes()), FILTER_VALIDATE_BOOLEAN)); } foreach ($xml->objektkategorie->user_defined_simplefield as $simpleField) { $this->mapSimpleField($simpleField, $objekt); } foreach ($xml->objektkategorie->user_defined_anyfield as $anyField) { foreach ($anyField->ji_kategorie as $kategorie) { $attributes = $this->attributesToArray($kategorie); if (array_key_exists('id', $attributes)) { $objekt->addCategory($attributes['id'], (string)$kategorie); } } } } if (isset($xml->freitexte)) { $objekt->setTitle((string) $xml->freitexte->objekttitel); $objekt->setEquipmentDescription((string) $xml->freitexte->ausstatt_beschr); $objekt->setDescription((string) $xml->freitexte->objektbeschreibung); $objekt->setOtherInformation((string) $xml->freitexte->sonstige_angaben); if (isset($xml->freitexte->lage)) { $objekt->setLocality((string) $xml->freitexte->lage); } if (isset($xml->freitexte->user_defined_anyfield)) { if (isset($xml->freitexte->user_defined_anyfield->justimmo_freitext1)) { $objekt->setFreetext1((string) $xml->freitexte->user_defined_anyfield->justimmo_freitext1); } if (isset($xml->freitexte->user_defined_anyfield->justimmo_freitext2)) { $objekt->setFreetext2((string) $xml->freitexte->user_defined_anyfield->justimmo_freitext2); } if (isset($xml->freitexte->user_defined_anyfield->justimmo_freitext3)) { $objekt->setFreetext3((string) $xml->freitexte->user_defined_anyfield->justimmo_freitext3); } } } if (isset($xml->geo)) { $this->map($this->geoMapping, $xml->geo, $objekt); if (isset($xml->geo->geokoordinaten)) { $coord = $this->attributesToArray($xml->geo->geokoordinaten->attributes()); $objekt->setLatitude((double) $coord['breitengrad']); $objekt->setLongitude((double) $coord['laengengrad']); } if (isset($xml->geo->land)) { $iso = $this->attributesToArray($xml->geo->land->attributes()); if (array_key_exists('iso_land', $iso)) { $objekt->setCountry((string) $iso['iso_land']); } } foreach ($xml->geo->user_defined_simplefield as $simpleField) { $this->mapSimpleField($simpleField, $objekt); } foreach ($xml->geo->user_defined_anyfield as $anyField) { if (isset($anyField->ji_point_of_interest_distance)) { foreach ($anyField->ji_point_of_interest_distance->distance as $distance) { $distanceAttr = $this->attributesToArray($distance->attributes()); $objekt->addPoi($distanceAttr['group'], $distanceAttr['type'], (float)$distance); } } } } if (isset($xml->preise)) { $this->map($this->preisMapping, $xml->preise, $objekt); if (isset($xml->preise->kaufpreis) && $xml->preise->kaufpreis->attributes() != null) { $purchasePriceAttributes = $this->attributesToArray($xml->preise->kaufpreis->attributes()); if (array_key_exists('auf_anfrage', $purchasePriceAttributes)) { $objekt->setBuyOnRequest($purchasePriceAttributes['auf_anfrage']); } } if (isset($xml->preise->warmmiete)) { $objekt->setTotalRent($this->cast($xml->preise->warmmiete, 'double')); } if (isset($xml->preise->kaufpreisnetto) && isset($xml->preise->kaufpreisnetto['kaufpreisust'])) { $objekt->setPurchasePriceVat($this->cast($xml->preise->kaufpreisnetto['kaufpreisust'], 'double')); } if (isset($xml->preise->waehrung)) { $iso = $this->attributesToArray($xml->preise->waehrung->attributes()); if (array_key_exists('iso_waehrung', $iso)) { $objekt->setCurrency((string) $iso['iso_waehrung']); } } foreach ($xml->preise->user_defined_simplefield as $simpleField) { $this->mapSimpleField($simpleField, $objekt); } if (isset($xml->preise->zusatzkosten)) { foreach ($xml->preise->zusatzkosten[0] as $key => $zusatzkosten) { $name = isset($zusatzkosten->name) ? $zusatzkosten->name : $key; $costs = new AdditionalCosts((string) $name, (double) $zusatzkosten->brutto, (double) $zusatzkosten->netto, (double) $zusatzkosten->ust, (string) $zusatzkosten->ust_typ, (double) $zusatzkosten->ust_berechneter_wert, (double) $zusatzkosten->ust_wert); if (isset($zusatzkosten->optional)) { $costs->setOptional(filter_var((string) $zusatzkosten->optional, FILTER_VALIDATE_BOOLEAN)); } $objekt->addAdditionalCosts($key, $costs); } } if (isset($xml->preise->stellplaetze)) { $key = 0; foreach ($xml->preise->stellplaetze[0] as $stellplaetz) { $garage = new Garage((string) $stellplaetz->art, (string) $stellplaetz->name, (int) $stellplaetz->anzahl, (string) $stellplaetz->vermarktungsart, (double) $stellplaetz->brutto, (double) $stellplaetz->netto, (double) $stellplaetz->ust, (string) $stellplaetz->ust_typ, (double) $stellplaetz->ust_wert); $objekt->addGarage($key, $garage); $key++; } } if (isset($xml->preise->nettomieteprom2von)) { $objekt->setRentPerSqmFrom((float) $xml->preise->nettomieteprom2von); $objekt->setRentPerSqm((float) $xml->preise->nettomieteprom2von->attributes()->nettomieteprom2bis); } if (isset($xml->preise->nebenkostenprom2von)) { $objekt->setOperatingCostsPerSqmFrom((float) $xml->preise->nebenkostenprom2von); $objekt->setOperatingCostsPerSqm((float) $xml->preise->nebenkostenprom2von->attributes()->nebenkostenprom2bis); } if (isset($xml->preise->miete)) { $objekt->setRentNet((float) $xml->preise->miete->netto); $objekt->setRentGross((float) $xml->preise->miete->brutto); $objekt->setRentVatType((string) $xml->preise->miete->ust_typ); $objekt->setRentVatInput((float) $xml->preise->miete->ust_wert); $objekt->setRentVat((float) $xml->preise->miete->ust); $objekt->setRentVatValue((float) $xml->preise->miete->ust_berechneter_wert); } } if (isset($xml->anhaenge) && isset($xml->anhaenge->anhang)) { $this->mapAttachmentGroup($xml->anhaenge->anhang, $objekt); } if (isset($xml->videos) && isset($xml->videos->video)) { $this->mapAttachmentGroup($xml->videos->video, $objekt); } if (isset($xml->flaechen)) { $this->map($this->flaechenMapping, $xml->flaechen, $objekt); $objekt->setSurfaceArea($this->cast($xml->flaechen->grundstuecksflaeche)); } if (isset($xml->zustand_angaben)) { $objekt->setYearBuilt($this->cast($xml->zustand_angaben->baujahr, 'int')); $data = $this->attributesToArray($xml->zustand_angaben->zustand); if (array_key_exists('zustand_art', $data)) { $objekt->setCondition($data['zustand_art']); } $data = $this->attributesToArray($xml->zustand_angaben->alter); if (array_key_exists('alter_attr', $data)) { $objekt->setAge($data['alter_attr']); } $data = $this->attributesToArray($xml->zustand_angaben->erschliessung); if (array_key_exists('erschl_attr', $data)) { $objekt->setInfrastructureProvision($data['erschl_attr']); } if (isset($xml->zustand_angaben->energiepass)) { $energiepass = new EnergyPass(); $energiepass ->setEpart($this->cast($xml->zustand_angaben->energiepass->epart)) ->setValidUntil($this->cast($xml->zustand_angaben->energiepass->gueltig_bis, 'datetime')); foreach ($xml->zustand_angaben->user_defined_simplefield as $simpleField) { $this->mapSimpleField($simpleField, $energiepass); } $objekt->setEnergyPass($energiepass); } if (isset($xml->ausstattung[0])) { /** @var \SimpleXMLElement $element */ foreach ($xml->ausstattung[0] as $key => $element) { if ((string) $element === "true" || (int) $element === 1) { $objekt->addEquipment($key, $key); } elseif ($element->attributes()->count()) { $attributes = $this->attributesToArray($element); $value = array(); foreach ($attributes as $k => $v) { if ($v === "true" || $v == 1) { $value[] = $k; } else { $value[$k] = $v; } } $objekt->addEquipment($key, count($value) > 1 || (array_keys($value) !== range(0, count($value) - 1)) ? $value : $value[0]); } else { $objekt->addEquipment($key, (string) $element); } } } } if (isset($xml->kontaktperson)) { $employeeWrapper = new EmployeeWrapper(new EmployeeMapper()); $contact = $employeeWrapper->transformSingle($xml->kontaktperson->asXML()); $objekt->setContact($contact); } return $objekt; }
@param $data @return Realty
entailment
public function lineBreak() { echo $this->color->__invoke(str_repeat('─', $this->terminal->getWidth()))->yellow(); }
Write a line break. @return string
entailment
public function connect($host, $port, $persistent = false){ if($persistent === false){ $this->cache->connect($host, intval($port)); } else{ $this->cache->pconnect($host, intval($port)); } return $this; }
Connect to a server @param string $host This should be the host name or IP address you want to connect to @param int $port The port number where Memcache can be accessed @param boolean $persistent If you want this connection to be persistent set to true else set to false @return $this
entailment
public function addServer($host, $port, $persistent = true){ $this->cache->addServer($host, intval($port), $persistent); return $this; }
Add a server to connection pool @param string $host This should be the host name or IP address you want to add to the Memcache pool @param int $port The port number where Memcache can be accessed @param boolean $persistent If you want this connection to be persistent set to true else set to false @return $this
entailment
public function save($key, $value, $time = 0){ return $this->cache->add($key, $value, 0, intval($time)); }
Adds a value to be stored on the server @param string $key This should be the key for the value you wish to add @param mixed $value The value you wish to be stored with the given key @param int $time How long should the value be stored for in seconds (0 = never expire) (max set value = 2592000 (30 Days)) @return boolean Returns true if successfully added or false on failure
entailment
protected function doMatch($actual) { if ($actual instanceof Traversable) { return $this->matchTraversable($actual); } if (is_array($actual)) { return array_search($this->expected, $actual, true) !== false; } if (is_string($actual)) { return strpos($actual, $this->expected) !== false; } throw new InvalidArgumentException('Inclusion matcher requires a string or array'); }
Matches if an array or string contains the expected value. @param $actual @return mixed @throws InvalidArgumentException
entailment
public function check(ExerciseInterface $exercise, Input $input) { if (file_exists($input->getArgument('program'))) { return Success::fromCheck($this); } return Failure::fromCheckAndReason($this, sprintf('File: "%s" does not exist', $input->getArgument('program'))); }
Simply check that the file exists. @param ExerciseInterface $exercise The exercise to check against. @param Input $input The command line arguments passed to the command. @return ResultInterface The result of the check.
entailment
public static function getFuzzyDistance(string $term, $mode): int { if (self::MODE_1 === $mode) { return 1; } if (self::MODE_2 === $mode) { return 2; } if (strlen($term) < 3) { return 1; } return 2; }
Returns distance for given mode. @param mixed $mode @return int
entailment
public static function getFuzzyTerms(string $term, $mode): array { $distance = self::getFuzzyDistance($term, $mode); if (1 === $distance) { return self::generateFuzzyTerms($term); } return self::generateFuzzyTermsTwice($term); }
Returns fuzzy terms. @param mixed $mode 1, 2, 'AUTO'
entailment
private static function generateFuzzyTermsTwice(string $term): array { $terms = []; foreach (self::generateFuzzyTerms($term) as $term) { $terms[] = $term; $terms = array_merge($terms, self::generateFuzzyTerms($term)); } return $terms; }
Generates fuzzy terms twice.
entailment
private static function generateFuzzyTerms(string $term): array { $terms = [$term . '_']; for ($i = 0; $i < strlen($term); ++$i) { // insertions $terms[] = substr($term, 0, $i) . '_' . substr($term, $i); // deletions $terms[] = substr($term, 0, $i) . substr($term, $i + 1); // substitutions $terms[] = substr($term, 0, $i) . '_' . substr($term, $i + 1); } return $terms; }
Generates fuzzy terms.
entailment
public function pushParser(Useragent\ParserInterface $parser) { $this->parser = $parser; if ($this->ua) { $this->setUA($this->ua); } }
Set the useragent @param string $ua
entailment
public function getSetter($apiPropertyName) { $property = $this->getProperty($apiPropertyName); return 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $property))); }
gets the setter for a api property name @param $apiPropertyName @return mixed
entailment
public function getProperty($apiPropertyName) { $values = $this->getValues($apiPropertyName); return array_key_exists('property', $values) ? $values['property'] : $apiPropertyName; }
@param $apiPropertyName @return string
entailment
protected function getValues($apiPropertyName) { $mapping = $this->getMapping(); return array_key_exists($apiPropertyName, $mapping) ? $mapping[$apiPropertyName] : array(); }
get mapping information of a api property @param $apiPropertyName @return array
entailment
public function match($actual = '') { $match = parent::match($actual); return $match->setActual($this->type); }
{@inheritdoc} @param $actual @return Match
entailment
public function doMatch($actual) { $this->type = gettype($actual); return $this->expected === $this->type; }
Determine if the actual value has the same type as the expected value. Uses the native gettype() function to compare. @param $actual @return bool
entailment
protected function xmlDeserialize($xml) { $array = []; if (!$xml instanceof SimpleXMLElement) { $xml = new SimpleXMLElement($xml); } foreach ($xml->children() as $key => $child) { $value = (string) $child; $_children = $this->xmlDeserialize($child); $_push = ( $_hasChild = ( count($_children) > 0 ) ) ? $_children : $value; if ( $_hasChild && !empty($value) && $value !== '' ) { $_push[] = $value; } $array[$key] = $_push; } return $array; }
Seserializes XML to an array @param \SimpleXMLElement|string $xml SimpleXMLElement object or a well formed xml string. @return array data
entailment
public static function fromCheckAndCodeParseFailure(CheckInterface $check, ParseErrorException $e, $file) { return new static( $check->getName(), sprintf('File: "%s" could not be parsed. Error: "%s"', $file, $e->getMessage()) ); }
Static constructor to create from a `PhpParser\Error` exception. Many checks will need to parse the student's solution, so this serves as a helper to create a consistent failure. @param CheckInterface $check The check that attempted to parse the solution. @param ParseErrorException $e The parse exception. @param string $file The absolute path to the solution. @return static The result.
entailment
public function render($markdown) { $ast = $this->docParser->parse($markdown); return $this->cliRenderer->renderBlock($ast); }
Expects a string of markdown and returns a string which has been formatted for displaying on the console. @param string $markdown @return string
entailment
public function isInstanceOf($object, $class, $message = '') { $this->assertion->setActual($object); return $this->assertion->is->instanceof($class, $message); }
Perform an instanceof assertion. @param object $object @param string $class @param string $message
entailment
public function notInstanceOf($object, $class, $message = '') { $this->assertion->setActual($object); return $this->assertion->is->not->instanceof($class, $message); }
Perform a negated instanceof assertion. @param object $object @param string $class @param string $message
entailment
public function property($object, $property, $message = '') { $this->assertion->setActual($object); return $this->assertion->to->have->property($property, null, $message); }
Perform a property assertion. @param array|object $object @param string $property @param string $message
entailment
public function notDeepProperty($object, $property, $message = '') { $this->assertion->setActual($object); return $this->assertion->to->not->have->deep->property($property, null, $message); }
Perform a negated deep property assertion. @param array|object $object @param string $property @param string $message
entailment
public function propertyVal($object, $property, $value, $message = '') { $this->assertion->setActual($object); return $this->assertion->to->have->property($property, $value, $message); }
Perform a property value assertion. @param array|object $object @param string $property @param mixed $value @param string $message
entailment
public function propertyNotVal($object, $property, $value, $message = '') { $this->assertion->setActual($object); return $this->assertion->to->not->have->property($property, $value, $message); }
Perform a negated property value assertion. @param array|object $object @param string $property @param mixed $value @param string $message
entailment
public function deepPropertyVal($object, $property, $value, $message = '') { $this->assertion->setActual($object); return $this->assertion->to->have->deep->property($property, $value, $message); }
Perform a deep property value assertion. @param array|object $object @param string $property @param mixed $value @param string $message
entailment
public function deepPropertyNotVal($object, $property, $value, $message = '') { $this->assertion->setActual($object); return $this->assertion->to->not->have->deep->property($property, $value, $message); }
Perform a negated deep property value assertion. @param array|object $object @param string $property @param mixed $value @param string $message
entailment
private function getPhpProcess($fileName, ArrayObject $args) { $cmd = sprintf('%s %s %s', PHP_BINARY, $fileName, $args->map('escapeshellarg')->implode(' ')); return new Process($cmd, dirname($fileName), null, null, 10); }
@param string $fileName @param ArrayObject $args @return Process
entailment
public function verify(Input $input) { $this->eventDispatcher->dispatch(new ExerciseRunnerEvent('cli.verify.start', $this->exercise, $input)); $result = new CliResult( array_map( function (array $args) use ($input) { return $this->doVerify($args, $input); }, $this->preserveOldArgFormat($this->exercise->getArgs()) ) ); $this->eventDispatcher->dispatch(new ExerciseRunnerEvent('cli.verify.finish', $this->exercise, $input)); return $result; }
Verifies a solution by invoking PHP from the CLI passing the arguments gathered from the exercise as command line arguments to PHP. Events dispatched: * cli.verify.reference-execute.pre * cli.verify.reference.executing * cli.verify.reference-execute.fail (if the reference solution fails to execute) * cli.verify.student-execute.pre * cli.verify.student.executing * cli.verify.student-execute.fail (if the student's solution fails to execute) @param Input $input The command line arguments passed to the command. @return CliResult The result of the check.
entailment
private function preserveOldArgFormat(array $args) { if (isset($args[0]) && !is_array($args[0])) { $args = [$args]; } elseif (empty($args)) { $args = [[]]; } return $args; }
BC - getArgs only returned 1 set of args in v1 instead of multiple sets of args in v2 @param array $args @return array
entailment
public function run(Input $input, OutputInterface $output) { $this->eventDispatcher->dispatch(new ExerciseRunnerEvent('cli.run.start', $this->exercise, $input)); $success = true; foreach ($this->preserveOldArgFormat($this->exercise->getArgs()) as $i => $args) { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( new CliExecuteEvent('cli.run.student-execute.pre', new ArrayObject($args)) ); $args = $event->getArgs(); if (count($args)) { $glue = max(array_map('strlen', $args->getArrayCopy())) > 30 ? "\n" : ', '; $output->writeTitle('Arguments'); $output->write(implode($glue, $args->getArrayCopy())); $output->emptyLine(); } $output->writeTitle("Output"); $process = $this->getPhpProcess($input->getArgument('program'), $args); $process->start(); $this->eventDispatcher->dispatch( new CliExecuteEvent('cli.run.student.executing', $args, ['output' => $output]) ); $process->wait(function ($outputType, $outputBuffer) use ($output) { $output->write($outputBuffer); }); $output->emptyLine(); if (!$process->isSuccessful()) { $success = false; } $output->lineBreak(); } $this->eventDispatcher->dispatch(new ExerciseRunnerEvent('cli.run.finish', $this->exercise, $input)); return $success; }
Runs a student's solution by invoking PHP from the CLI passing the arguments gathered from the exercise as command line arguments to PHP. Running only runs the student's solution, the reference solution is not run and no verification is performed, the output of the student's solution is written directly to the output. Events dispatched: * cli.run.student-execute.pre * cli.run.student.executing @param Input $input The command line arguments passed to the command. @param OutputInterface $output A wrapper around STDOUT. @return bool If the solution was successfully executed, eg. exit code was 0.
entailment
public function dispatch(EventInterface $event) { if (array_key_exists($event->getName(), $this->listeners)) { foreach ($this->listeners[$event->getName()] as $listener) { $listener($event); } } return $event; }
Dispatch an event. Can be any event object which implements `PhpSchool\PhpWorkshop\Event\EventInterface`. @param EventInterface $event @return EventInterface
entailment
public function listen($eventNames, callable $callback) { if (!is_array($eventNames)) { $eventNames = [$eventNames]; } foreach ($eventNames as $eventName) { $this->attachListener($eventName, $callback); } }
Attach a callback to an event name. `$eventNames` can be an array of event names in order to attach the same callback to multiple events or it can just be one event name as a string. @param string|array $eventNames @param callable $callback
entailment
public function insertVerifier($eventName, callable $verifier) { $this->attachListener($eventName, function (EventInterface $event) use ($verifier) { $result = $verifier($event); //return type hints pls if ($result instanceof ResultInterface) { $this->resultAggregator->add($result); } else { //??!! } }); }
Insert a verifier callback which will execute at the given event name much like normal listeners. A verifier should return an object which implements `PhpSchool\PhpWorkshop\Result\FailureInterface` or `PhpSchool\PhpWorkshop\Result\SuccessInterface`. This result object will be added to the result aggregator. @param string|array $eventName @param callable $verifier
entailment
public function getSolution() { return SingleFileSolution::fromFile( realpath( sprintf( '%s/../../exercises/%s/solution/solution.php', dirname((new ReflectionClass(static::class))->getFileName()), self::normaliseName($this->getName()) ) ) ); }
This returns a single file solution named `solution.php` which should exist in `workshop-root/exercises/<exercise-name>/solution/`. This method can be overwritten if the solution consists of multiple files, see [Directory Solution](https://www.phpschool.io/docs/reference/exercise-solutions#directory-solution) for more details. @return SolutionInterface
entailment
public function getProblem() { $name = self::normaliseName($this->getName()); $dir = dirname((new ReflectionClass(static::class))->getFileName()); return sprintf('%s/../../exercises/%s/problem/problem.md', $dir, $name); }
This returns the problem file path, which is assumed to exist in `workshop-root/exercises/<exercise-name>/problem/` as a file named `problem.md`. @return string
entailment
public function route(array $args = null) { if (null === $args) { $args = isset($_SERVER['argv']) ? $_SERVER['argv'] : []; } $appName = array_shift($args); if (empty($args)) { return $this->resolveCallable($this->commands[$this->defaultCommand], new Input($appName)); } $commandName = array_shift($args); if (!isset($this->commands[$commandName])) { $command = $this->findNearestCommand($commandName, $this->commands); if (false === $command) { throw new CliRouteNotExistsException($commandName); } $commandName = $command; } $command = $this->commands[$commandName]; $this->eventDispatcher->dispatch(new Event\Event('route.pre.resolve.args', ['command' => $command])); $input = $this->parseArgs($commandName, $command->getRequiredArgs(), $appName, $args); return $this->resolveCallable($command, $input); }
Attempts to route the command. Parses `$argv` (or a given array), extracting the command name and arguments. Using the command name, the command definition is looked up. The number of arguments are validated against the required arguments for the command (specified by the definition) We get the callable from the command definition, or if it is the name of a service, we lookup the service in the container and validate that it is a callable. Finally, the callable is invoked with the arguments passed from the cli. The return value of callable is returned (if it is an integer, if not zero (success) is returned). @param array $args @return int @throws CliRouteNotExistsException
entailment
private function findNearestCommand($commandName, array $commands) { $distances = []; foreach (array_keys($commands) as $command) { $distances[$command] = levenshtein($commandName, $command); } $distances = array_filter(array_unique($distances), function ($distance) { return $distance <= 3; }); if (empty($distances)) { return false; } return array_search(min($distances), $distances); }
Get the closest command to the one typed, but only if there is 3 or less characters different @param string $commandName @param array $commands @return string|false
entailment
public function setStandard(array $config = array()){ $this->standard = $this->tz->newComponent( "standard" ); foreach($config as $prop => $value){ $this->standard->setProperty($prop, $value); } return $this; }
This function sets the properties for the STANDARD component in the timezone. Configuration example for Europe/Paris: <pre> array( 'dtstart' => '19710101T030000', 'tzoffsetto' => '+0100', 'tzoffsetfrom' => '+0200', 'rrule' => array( 'freq' => 'YEARLY', 'wkst' => 'MO', 'interval' => 1, 'bymonth' => 10, ), 'tzname' => 'CET' ) </pre> @author Florian Steinbauer <[email protected]> @param array $config @return Timezone
entailment
public function setDaylight(array $config = array()){ $this->daylight = $this->tz->newComponent( "daylight" ); foreach($config as $prop => $value){ $this->daylight->setProperty($prop, $value); } return $this; }
This function sets the properties for the STANDARD component in the timezone. Configuration example for Europe/Paris: <pre> array( 'dtstart' => '19710101T030000', 'tzoffsetto' => '+0200', 'tzoffsetfrom' => '+0100', 'rrule' => array( 'freq' => 'YEARLY', 'wkst' => 'MO', 'interval' => 1, 'bymonth' => 10, ), 'tzname' => 'CET' ) </pre> @author Florian Steinbauer <[email protected]> @param array $config @return Timezone
entailment
public function getData() { $this->validate('merchantId', 'merchantPassword', 'acquirerId', 'transactionId'); $data = [ 'AcquirerId' => $this->getAcquirerId(), 'MerchantId' => $this->getMerchantId(), 'Password' => $this->getMerchantPassword(), 'OrderNumber' => $this->getTransactionId() ]; return $data; }
Validate and construct the data for the request @return array
entailment
public function generateUrl($call, array $params = array()) { $url = $this->baseUrl . '/' . $this->version . '/' . $call; if (count($params) > 0) { $queryString = http_build_query($params, null, '&'); $queryString = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $queryString); $url .= '?' . $queryString; } return $url; }
generates a url for an api request @param $call @param array $params @return string
entailment
public function call($call, array $params = array()) { $startTime = microtime(true); if (!array_key_exists('culture', $params)) { $params['culture'] = $this->culture; } $url = $this->generateUrl($call, $params); $this->logger->debug('call start', array( 'url' => $url, )); $key = $this->cache->generateCacheKey($url); $content = $this->cache->get($key); if ($content !== false) { $this->logger->debug('call end', array( 'url' => $url, 'cache' => true, 'time' => microtime(true) - $startTime, 'response' => $content, )); return $content; } $request = $this->createRequest($url); if (!ini_get('open_basedir') && filter_var(ini_get('safe_mode'), FILTER_VALIDATE_BOOLEAN) === false) { $request->setOption(CURLOPT_FOLLOWLOCATION, true); } $response = $request->get(); if ($request->getError()) { $this->throwError('The Api call returned an error: "' . $request->getError() . '"'); } if ($request->getStatusCode() == 401) { $this->throwError('Bad Username / Password ' . $request->getStatusCode(), '\Justimmo\Exception\AuthenticationException'); } if ($request->getStatusCode() == 404) { $this->throwError('Api call not found: ' . $request->getStatusCode(), '\Justimmo\Exception\NotFoundException'); } if ($request->getStatusCode() >= 400 && $request->getStatusCode() < 500) { $exception = new InvalidRequestException('The Api call returned status code ' . $request->getStatusCode()); $exception->setResponse($request->getContent()); $this->logger->error($exception->getMessage()); throw $exception; } if ($request->getStatusCode() != 200) { $this->throwError('The Api call returned status code ' . $request->getStatusCode(), '\Justimmo\Exception\StatusCodeException'); } $this->cache->set($key, $response); $this->logger->debug('call end', array( 'url' => $url, 'cache' => false, 'time' => microtime(true) - $startTime, 'response' => $response, )); return $response; }
Makes a call to the justimmo api @param $call @param array $params @return mixed
entailment
public function setPassword($password) { if (mb_strlen($password) == 0) { $this->throwError('Password not set'); } $this->password = $password; return $this; }
@param string $password @return $this
entailment
public function setUsername($username) { if (mb_strlen($username) == 0) { $this->throwError('Username not set'); } $this->username = $username; return $this; }
@param string $username @return $this
entailment
public function setVersion($version) { if (!in_array($version, $this->supportedVersions)) { $this->throwError('The version ' . $version . ' is not supported by this library'); } $this->version = $version; return $this; }
@param string $version @return $this
entailment
public function bootstrap($app) { if ($app instanceof Application) { if (is_callable($this->languages)) { $this->languages = call_user_func($this->languages); } if (!is_array($this->languages)) { throw new InvalidConfigException( 'The "languages" property must be an array or callable function that returns an array' ); } if (!is_bool($this->appendSetLanguageHandler)) { throw new InvalidConfigException( 'The "appendSetLanguageHandler" property must be a boolean' ); } foreach ($this->handlers as &$handler) { if (is_object($handler) === false) { $handler = Yii::createObject($handler); } if (!$handler instanceof AbstractHandler) { throw new InvalidConfigException(sprintf( 'The handler must be an instance of "%s"', AbstractHandler::className() )); } } $app->on($app::EVENT_BEFORE_ACTION, [$this, 'setLanguage'], $app, $this->appendSetLanguageHandler); } }
Bootstrap method to be called during application bootstrap stage. @param \yii\base\Application $app the application currently running. @throws InvalidConfigException
entailment
public function setLanguage(Event $event) { /** * @var $app Application */ $app = $event->data; foreach ($this->handlers as $handler) { $intersection = array_intersect($this->languages, $handler->getLanguages()); if (!empty($intersection)) { Yii::$app->language = current($intersection); break; } } $app->trigger(self::EVENT_AFTER_SETTING_LANGUAGE); }
Sets the application language. @see Application::$language @param Event $event the event parameter used for an action event.
entailment
public static function addDistance(DataList $list, $fromLatitude, $fromLongitude, $distanceFieldName = 'Distance', $latitudeFieldName = 'Latitude', $longitudeFieldName = 'Longitude') { $list = $list->alterDataQuery(function ($dataQuery) use ($fromLatitude, $fromLongitude, $distanceFieldName, $latitudeFieldName, $longitudeFieldName) { $dataQuery->selectField('111.111 * DEGREES(ACOS(COS(RADIANS('.$latitudeFieldName.')) * COS(RADIANS(' . $fromLatitude . ')) * COS(RADIANS('.$longitudeFieldName.' - ' . $fromLongitude . ')) + SIN(RADIANS('.$latitudeFieldName.')) * SIN(RADIANS(' . $fromLatitude . '))))', $distanceFieldName); return $dataQuery; }); return $list; }
Add a distance column to your list, after this you can use this like any other column for example: ->sort('Distance') @param DataList $list @param $fromLatitude @param $fromLongitude @param string $distanceFieldName @param string $latitudeFieldName @param string $longitudeFieldName @return DataList
entailment
public function addContainer(MutableContainerInterface $container): void { $containerName = get_class($container); if (array_key_exists($containerName, $this->registry)) { throw new ContainerAlreadyRegisteredException($containerName); } $this->registry[$containerName] = $container; }
@param MutableContainerInterface $container @throws ContainerAlreadyRegisteredException
entailment
public function getContainer(string $containerName): MutableContainerInterface { if (false === array_key_exists($containerName, $this->registry)) { throw new ContainerIsNotRegisteredException($containerName); } return $this->registry[$containerName]; }
@param string $containerName @return MutableContainerInterface @throws ContainerIsNotRegisteredException
entailment
public function getBreadcrumbs(): array { if (empty($this->stack)) { $this->getRootItem($this->getCurrent()); $this->stack = array_reverse($this->stack); $this->stack = array_map( function (ItemInterface $item) { return $this->used[ItemHelper::getIdentifier($item)]; }, $this->stack ); } return $this->stack; }
@return ItemInterface[] @throws NoCurrentItemFoundException
entailment
public function isAncestor(ItemInterface $item): bool { $ancestors = $this->getBreadcrumbs(); array_pop($ancestors); return in_array( $item, array_map( function (ParentNode $node) { return $node->getItem(); }, $ancestors ) ); }
@param ItemInterface $item @return bool @throws NoCurrentItemFoundException
entailment
public function getUrl(ItemInterface $item): string { foreach ($this->providers as $provider) { if ($provider->supports($item)) { return $provider->getUrl($item); } } throw new CannotProvideUrlForItemException($item); }
@param ItemInterface $item @return string @throws CannotProvideUrlForItemException
entailment
protected function getDefaultSaveOptions($options, $path = null) { $options += [ 'format' => get_extension($path ?: $this->path), 'quality' => 90, 'target' => false, ]; //Fixes some formats $options['format'] = preg_replace(['/^jpeg$/', '/^tif$/'], ['jpg', 'tiff'], $options['format']); return $options; }
Internal method to get default options for the `save()` method @param array $options Passed options @param string|null $path Path to use @return array Passed options added to the default options @uses $path
entailment
protected function getImageInstance() { //Tries to create the image instance try { $imageInstance = $this->ImageManager->make($this->path); } catch (NotReadableException $e) { $message = __d('thumber', 'Unable to read image from file `{0}`', rtr($this->path)); if ($e->getMessage() == 'Unsupported image type. GD driver is only able to decode JPG, PNG, GIF or WebP files.') { $message = __d('thumber', 'Image type `{0}` is not supported by this driver', mime_content_type($this->path)); } throw new RuntimeException($message); } return $imageInstance; }
Gets an `Image` instance @return \Intervention\Image\Image @throws RuntimeException @uses $ImageManager @uses $path
entailment
public function getUrl($fullBase = true) { is_true_or_fail(!empty($this->target), __d( 'thumber', 'Missing path of the generated thumbnail. Probably the `{0}` method has not been invoked', 'save()' ), InvalidArgumentException::class); return Router::url(['_name' => 'thumb', base64_encode(basename($this->target))], $fullBase); }
Builds and returns the url for the generated thumbnail @param bool $fullBase If `true`, the full base URL will be prepended to the result @return string @since 1.5.1 @throws InvalidArgumentException @uses $target
entailment
public function crop($width = null, $heigth = null, array $options = []) { $heigth = $heigth ?: $width; $width = $width ?: $heigth; //Sets default options $options += ['x' => null, 'y' => null]; //Adds arguments $this->arguments[] = [__FUNCTION__, $width, $heigth, $options]; //Adds the callback $this->callbacks[] = function (Image $imageInstance) use ($width, $heigth, $options) { return $imageInstance->crop($width, $heigth, $options['x'], $options['y']); }; return $this; }
Crops the image, cutting out a rectangular part of the image. You can define optional coordinates to move the top-left corner of the cutout to a certain position. @param int $width Required width @param int $heigth Required heigth @param array $options Options for the thumbnail @return \Thumber\Utility\ThumbCreator @see https://github.com/mirko-pagliai/cakephp-thumber/wiki/How-to-uses-the-ThumbCreator-utility#crop @uses $arguments @uses $callbacks
entailment
public function fit($width = null, $heigth = null, array $options = []) { $heigth = $heigth ?: $width; $width = $width ?: $heigth; //Sets default options $options += ['position' => 'center', 'upsize' => true]; //Adds arguments $this->arguments[] = [__FUNCTION__, $width, $heigth, $options]; //Adds the callback $this->callbacks[] = function (Image $imageInstance) use ($width, $heigth, $options) { return $imageInstance->fit($width, $heigth, function (Constraint $constraint) use ($options) { if ($options['upsize']) { $constraint->upsize(); } }, $options['position']); }; return $this; }
Resizes the image, combining cropping and resizing to format image in a smart way. It will find the best fitting aspect ratio on the current image automatically, cut it out and resize it to the given dimension @param int $width Required width @param int $heigth Required heigth @param array $options Options for the thumbnail @return \Thumber\Utility\ThumbCreator @see https://github.com/mirko-pagliai/cakephp-thumber/wiki/How-to-uses-the-ThumbCreator-utility#fit @uses $arguments @uses $callbacks
entailment
public function resizeCanvas($width, $heigth = null, array $options = []) { //Sets default options $options += ['anchor' => 'center', 'relative' => false, 'bgcolor' => '#ffffff']; //Adds arguments $this->arguments[] = [__FUNCTION__, $width, $heigth, $options]; //Adds the callback $this->callbacks[] = function (Image $imageInstance) use ($width, $heigth, $options) { return $imageInstance->resizeCanvas($width, $heigth, $options['anchor'], $options['relative'], $options['bgcolor']); }; return $this; }
Resizes the boundaries of the current image to given width and height. An anchor can be defined to determine from what point of the image the resizing is going to happen. Set the mode to relative to add or subtract the given width or height to the actual image dimensions. You can also pass a background color for the emerging area of the image @param int $width Required width @param int $heigth Required heigth @param array $options Options for the thumbnail @return \Thumber\Utility\ThumbCreator @see https://github.com/mirko-pagliai/cakephp-thumber/wiki/How-to-uses-the-ThumbCreator-utility#resizecanvas @since 1.3.1 @uses $arguments @uses $callbacks
entailment
public function save(array $options = []) { is_true_or_fail($this->callbacks, __d('thumber', 'No valid method called before the `{0}` method', __FUNCTION__), RuntimeException::class); $options = $this->getDefaultSaveOptions($options); $target = $options['target']; if (!$target) { $this->arguments[] = [$this->driver, $options['format'], $options['quality']]; $target = sprintf('%s_%s.%s', md5($this->path), md5(serialize($this->arguments)), $options['format']); } else { $optionsFromTarget = $this->getDefaultSaveOptions([], $target); $options['format'] = $optionsFromTarget['format']; } $target = Folder::isAbsolute($target) ? $target : $this->getPath($target); $File = new File($target); //Creates the thumbnail, if this does not exist if (!$File->exists()) { $imageInstance = $this->getImageInstance(); //Calls each callback foreach ($this->callbacks as $callback) { call_user_func($callback, $imageInstance); } $content = $imageInstance->encode($options['format'], $options['quality']); $imageInstance->destroy(); is_true_or_fail($File->write($content), __d('thumber', 'Unable to create file `{0}`', rtr($target)), RuntimeException::class); $File->close(); } //Resets arguments and callbacks $this->arguments = $this->callbacks = []; return $this->target = $target; }
Saves the thumbnail and returns its path @param array $options Options for saving @return string Thumbnail path @see https://github.com/mirko-pagliai/cakephp-thumber/wiki/How-to-uses-the-ThumbCreator-utility#save @throws RuntimeException @uses getDefaultSaveOptions() @uses getImageInstance() @uses $arguments @uses $callbacks @uses $driver @uses $path @uses $target
entailment
private function getFilePath() { $fullname = $this->fullName; $rootPath = Yii::getAlias('@webroot'); if (substr($fullname, 0, 1) != '/') { $fullname = '/' . $fullname; } return $rootPath . $fullname; }
获取文件完整路径 这里使用了Yii别名 @return string
entailment
public function xpath() { if (!isset($this->xpath)) { $this->xpath = new \DOMXPath($this); } return $this->xpath; }
Creates a DOMXPath to query this document. @return DOMXPath DOMXPath object.
entailment
protected function runUrlMethod($name, $path, array $params = [], array $options = []) { $name = $this->isUrlMethod($name) ? substr($name, 0, -3) : $name; //Sets default parameters and options $params += ['format' => 'jpg', 'height' => null, 'width' => null]; $options += ['fullBase' => true]; $thumber = new ThumbCreator($path); is_true_or_fail(method_exists($thumber, $name), __d('thumber', 'Method `{0}::{1}()` does not exist', get_class($this), $name), RuntimeException::class); $thumber->$name($params['width'], $params['height'])->save($params); return $thumber->getUrl($options['fullBase']); }
Runs an "Url" method and returns the url generated by the method @param string $name Method name @param string $path Path of the image from which to create the thumbnail. It can be a relative path (to APP/webroot/img), a full path or a remote url @param array $params Parameters for creating the thumbnail @param array $options Array of HTML attributes for the `img` element @return string Thumbnail url @since 1.4.0 @throws RuntimeException @uses isUrlMethod()
entailment
public function add(array $data) { $defaults = array( "description" => null, "price" => null, "discount" => null, "qty" => 1, "unit" => null ); $merged = array_merge($defaults, $data); $line = $this->create($this->invoiceHandle); if( isset($merged['product']) ) { $this->product($line, $merged['product']); unset( $merged['product'] ); } return $this->update($data, $line); }
Add Invoice line @param array $data
entailment
public function update(array $data, $line) { if( is_integer($line) ) { $line = array('Id' => $line); } foreach( $data as $name => $value ) { if( is_null($value) ) continue; switch( strtolower($name) ) { case 'description': $this->description($line, $value); break; case 'price': $this->price($line, $value); break; case 'discount': $this->discount($line, $value); break; case 'qty': $this->qty($line, $value); break; case 'unit': $this->unit($line, $value); break; } } return $this->getArrayFromHandles( array('CurrentInvoiceLineHandle'=>$line) ); }
Update Invoice Line with data @param array $data @param object $line @return object
entailment
public function product($invoiceLineHandle, $product) { $products = new Product($this->client_raw); $productHandle = $products->getHandle($product); $this->client ->CurrentInvoiceLine_SetProduct( array( 'currentInvoiceLineHandle' => $invoiceLineHandle, 'valueHandle' => $productHandle ) ); return true; }
Set Invoice Line product by product number @param mixed $invoiceLineHandle @param integer $product @return boolean
entailment
public function unit($invoiceLineHandle, $unit) { $units = new Unit($this->client_raw); $unitHandle = $units->getHandle($unit); $this->client ->CurrentInvoiceLine_SetUnit( array( 'currentInvoiceLineHandle' => $invoiceLineHandle, 'valueHandle' => $unitHandle ) ); return true; }
Set Quotation Line unit by unit number @param mixed $QuotationLineHandle [description] @param integer $unit @return boolean
entailment
public function itemType() { $itemtype = $this->getAttribute('itemtype'); if (!empty($itemtype)) { return $this->tokenList($itemtype); } // Return NULL instead of the empty string returned by getAttributes so we // can use the function for boolean tests. return NULL; }
Retrieve this item's itemtypes. @return array An array of itemtype tokens.
entailment
public function properties() { $props = array(); if ($this->itemScope()) { $toTraverse = array($this); foreach ($this->itemRef() as $itemref) { $children = $this->ownerDocument->xpath()->query('//*[@id="'.$itemref.'"]'); foreach($children as $child) { $this->traverse($child, $toTraverse, $props, $this); } } while (count($toTraverse)) { $this->traverse($toTraverse[0], $toTraverse, $props, $this); } } return $props; }
Retrieve the properties @return array An array of MicrodataPhpDOMElements which are properties of this element.
entailment
public function itemValue() { $itemprop = $this->itemProp(); if (empty($itemprop)) return null; if ($this->itemScope()) { return $this; } switch (strtoupper($this->tagName)) { case 'META': return $this->getAttribute('content'); case 'AUDIO': case 'EMBED': case 'IFRAME': case 'IMG': case 'SOURCE': case 'TRACK': case 'VIDEO': // @todo Should this test that the URL resolves? return $this->getAttribute('src'); case 'A': case 'AREA': case 'LINK': // @todo Should this test that the URL resolves? return $this->getAttribute('href'); case 'OBJECT': // @todo Should this test that the URL resolves? return $this->getAttribute('data'); case 'DATA': return $this->getAttribute('value'); case 'TIME': $datetime = $this->getAttribute('datetime'); if (!empty($datetime)) return $datetime; default: return $this->textContent; } }
Retrieve the element's value, determined by the element type. @return string The string value if the element is not an item, or $this if it is an item.
entailment
protected function traverse($node, &$toTraverse, &$props, $root) { foreach ($toTraverse as $i => $elem) { if ($elem->isSameNode($node)){ unset($toTraverse[$i]); } } if (!$root->isSameNode($node)) { $names = $node->itemProp(); if (count($names)) { //@todo Add support for property name filtering. $props[] = $node; } if ($node->itemScope()) { return; } } if (isset($node)) { // An xpath expression is used to get children instead of childNodes // because childNodes contains DOMText children as well, which breaks on // the call to getAttributes() in itemProp(). $children = $this->ownerDocument->xpath()->query($node->getNodePath() . '/*'); foreach ($children as $child) { $this->traverse($child, $toTraverse, $props, $root); } } }
Traverse the tree. In MicrodataJS, this is handled using a closure. See comment for MicrodataPhp:getObject() for an explanation of closure use in this library.
entailment
protected function handle($result, $httpCode) { // Check for non-OK statuses $codes = explode(",", static::ACCEPTED_CODES); if (!in_array($httpCode, $codes)) { // Decode JSON if possible, if this can't be decoded...something fatal went wrong // and we will just return the entire body as an exception. if ($error = json_decode($result, true)) { $error = $error['error']; } else { $error = $result; } throw new \Clickatell\ClickatellException($error); } else { return json_decode($result, true); } }
Handle CURL response from Clickatell APIs @param string $result The API response @param int $httpCode The HTTP status code @throws Exception @return array
entailment
protected function curl($uri, $data) { // Force data object to array $data = $data ? (array) $data : $data; $headers = [ 'Content-Type: application/json', 'Accept: application/json', 'Authorization: ' . $this->apiToken ]; // This is the clickatell endpoint. It doesn't really change so // it's safe for us to "hardcode" it here. $endpoint = static::API_URL . "/" . $uri; $curlInfo = curl_version(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_USERAGENT, static::AGENT . ' curl/' . $curlInfo['version'] . ' PHP/' . phpversion()); // Specify the raw post data if ($data) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); } $result = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); return $this->handle($result, $httpCode); }
Abstract CURL usage. @param string $uri The endpoint @param string $data Array of parameters @return Decoder
entailment
public static function parseReplyCallback($callback, $file = STDIN) { $body = file_get_contents($file); $body = json_decode($body, true); $keys = [ 'integrationId', 'messageId', 'replyMessageId', 'apiKey', 'fromNumber', 'toNumber', 'timestamp', 'text', 'charset', 'udh', 'network', 'keyword' ]; if (!array_diff($keys, array_keys($body))) { $callback($body); } return; }
@see https://www.clickatell.com/developers/api-documentation/rest-api-reply-callback/ @param callable $callback The function to trigger with desired parameters @param string $file The stream or file name, default to standard input @return void
entailment
public function init() { parent::init(); if ($this->enableIDN && !function_exists('idn_to_ascii')) { throw new InvalidConfigException( 'In order to use IDN validation intl extension must be installed and enabled.' ); } if (!isset($this->encoding)) { $this->encoding = Yii::$app->charset; } if (!isset($this->i18nBasePath)) { $this->i18nBasePath = dirname(__DIR__) . '/messages'; } Yii::$app->i18n->translations['kdn/yii2/validators/domain'] = [ 'class' => 'yii\i18n\PhpMessageSource', 'basePath' => $this->i18nBasePath, 'fileMap' => ['kdn/yii2/validators/domain' => 'domain.php'], ]; }
{@inheritdoc}
entailment
protected function validateValue($value) { if (!is_string($value)) { return $this->getErrorMessage('messageNotString'); } if (empty($value)) { return $this->getErrorMessage('messageTooShort'); } if ($this->allowURL) { $host = parse_url($value, PHP_URL_HOST); if (isset($host) && $host !== false) { $value = $host; } } if ($this->enableIDN) { $idnaInfo = null; $options = IDNA_CHECK_BIDI | IDNA_CHECK_CONTEXTJ; $asciiValue = idn_to_ascii($value, $options, INTL_IDNA_VARIANT_UTS46, $idnaInfo); if ($asciiValue !== false) { $value = $asciiValue; } else { $idnaErrors = null; if (is_array($idnaInfo) && array_key_exists('errors', $idnaInfo)) { $idnaErrors = $idnaInfo['errors']; } if ($idnaErrors & IDNA_ERROR_DOMAIN_NAME_TOO_LONG) { $errorMessageName = 'messageTooLong'; } elseif ($idnaErrors & IDNA_ERROR_EMPTY_LABEL) { $errorMessageName = 'messageLabelTooShort'; } elseif ($idnaErrors & IDNA_ERROR_LABEL_TOO_LONG) { $errorMessageName = 'messageLabelTooLong'; } elseif ($idnaErrors & IDNA_ERROR_DISALLOWED) { $errorMessageName = 'messageInvalidCharacter'; } elseif ($idnaErrors & IDNA_ERROR_LEADING_HYPHEN || $idnaErrors & IDNA_ERROR_TRAILING_HYPHEN) { $errorMessageName = 'messageLabelStartEnd'; } elseif (empty($idnaInfo)) { // too long domain name caused buffer overflow $errorMessageName = 'messageTooLong'; } else { $errorMessageName = 'message'; } return $this->getErrorMessage($errorMessageName); } } // ignore trailing dot if (mb_substr($value, -1, 1, $this->encoding) == '.') { $value = substr_replace($value, '', -1); } // 253 characters limit is same as 127 levels, // domain name with 127 levels with 1 character per label will be 253 characters long if (mb_strlen($value, $this->encoding) > 253) { return $this->getErrorMessage('messageTooLong'); } $labels = explode('.', $value); $labelsCount = count($labels); if ($labelsCount < $this->labelNumberMin) { return $this->getErrorMessage('messageLabelNumberMin', ['labelNumberMin' => $this->labelNumberMin]); } for ($i = 0; $i < $labelsCount; $i++) { $label = $labels[$i]; $labelLength = mb_strlen($label, $this->encoding); if (empty($label)) { return $this->getErrorMessage('messageLabelTooShort'); } if ($labelLength > 63) { return $this->getErrorMessage('messageLabelTooLong'); } if ($this->allowUnderscore) { $pattern = '/^[a-z\d\-_]+$/i'; } else { $pattern = '/^[a-z\d\-]+$/i'; } if (!preg_match($pattern, $label)) { return $this->getErrorMessage('messageInvalidCharacter'); } if ($i == $labelsCount - 1 && !ctype_alpha($label[0]) || !ctype_alnum($label[0]) || !ctype_alnum($label[$labelLength - 1]) ) { return $this->getErrorMessage('messageLabelStartEnd'); } } if ($this->checkDNS && !checkdnsrr("$value.", 'ANY')) { return $this->getErrorMessage('messageDNS'); } return null; }
{@inheritdoc}
entailment