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...
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 el...
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...
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[] = '?'; } ...
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 ...
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($li...
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)) { ...
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')...
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 F...
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. @...
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("So...
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.'...
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)) { ...
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 $t...
@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); //l...
@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 boolea...
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)) { ret...
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) . s...
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->xmlD...
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 strin...
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, $inpu...
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.stude...
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 CliExecut...
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....
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->res...
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 str...
entailment
public function getSolution() { return SingleFileSolution::fromFile( realpath( sprintf( '%s/../../exercises/%s/solution/solution.php', dirname((new ReflectionClass(static::class))->getFileName()), self::normaliseName($th...
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...
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($...
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 comm...
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) { ...
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, 'bym...
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, 'bym...
entailment
public function getData() { $this->validate('merchantId', 'merchantPassword', 'acquirerId', 'transactionId'); $data = [ 'AcquirerId' => $this->getAcquirerId(), 'MerchantId' => $this->getMerchantId(), 'Password' => $this->getMerchantPassword(), 'O...
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); ...
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( ...
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( ...
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)) { ...
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, $latitudeFieldN...
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] = ...
@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[Item...
@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(); }, ...
@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$/']...
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)); ...
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([...
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, $...
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 @s...
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__, $wi...
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 thum...
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 ca...
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 em...
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) { ...
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 $cal...
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'...
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 $...
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...
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) ) { ...
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' => $invoiceLi...
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, ...
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($chi...
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': ...
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 ...
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 retur...
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 c...
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', ...
@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->encodin...
{@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($v...
{@inheritdoc}
entailment