sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function buildTemplates($models) { $result = []; foreach($models as $model) { $result[] = self::buildTemplate($model); } return $result; }
Builder for array of Template from Active Record model @param EmailTemplateTranslation[] $models @return array
entailment
public function addMethod($name, callable $method) { $this->methods[$name] = \Closure::bind($method, $this, $this); return $this; }
Add a method identified by the given name. @param string $name @param callable $method the body of the method @return $this
entailment
public function addProperty($name, callable $factory, $memoize = false) { $this->properties[$name] = ['factory' => \Closure::bind($factory, $this, $this), 'memoize' => $memoize]; return $this; }
Adds a lazy property identified by the given name. The property is lazy because it is not evaluated until asked for via __get(). @param string $name @param callable $factory @param bool $memoize @return $this
entailment
public function flag() { $args = func_get_args(); $num = count($args); if ($num > 1) { $this->flags[$args[0]] = $args[1]; return $this; } if (array_key_exists($args[0], $this->flags)) { return $this->flags[$args[0]]; } }
A simple mechanism for storing arbitrary flags. Flags are useful for tweaking behavior based on their presence. @return $this|mixed
entailment
protected function getTable(): string { if ($this->modelClass === null && $this->table === null) { throw new InvalidConfigException('Either "modelClass" or "table" must be set.'); } if ($this->table === null) { $this->table = with(new $this->modelClass())->getTable(); } if (!Schema::hasTable($this->table)) { throw new InvalidConfigException("Table does not exist: {$this->table}"); } return $this->table; }
Returns the table name for [[modelClass]] @throws Exception @return string
entailment
public function getData() { $this->validate('merchantId', 'merchantPassword', 'acquirerId', 'transactionId', 'amount'); $data = [ 'AcquirerId' => $this->getAcquirerId(), 'Amount' => $this->formatAmount(), 'CurrencyExponent' => $this->getCurrencyDecimalPlaces(), 'MerchantId' => $this->getMerchantId(), 'ModificationType' => $this->getModificationType(), 'OrderNumber' => $this->getTransactionId(), 'Password' => $this->getMerchantPassword() ]; return $data; }
Validate and construct the data for the request @return array
entailment
public function loadFixtures($fixtures = null): void { if ($fixtures === null) { $fixtures = $this->getFixtures(); } /* @var $fixture Fixture */ foreach ($fixtures as $fixture) { $fixture->beforeLoad(); } foreach ($fixtures as $fixture) { $fixture->load(); } foreach (array_reverse($fixtures) as $fixture) { $fixture->afterLoad(); } }
Loads the specified fixtures. This method will call [[Fixture::load()]] for every fixture object. @param Fixture[] $fixtures the fixtures to be loaded. If this parameter is not specified, the return value of [[getFixtures()]] will be used. @throws InvalidConfigException
entailment
public function unloadFixtures($fixtures = null): void { if ($fixtures === null) { $fixtures = $this->getFixtures(); } /* @var $fixture Fixture */ foreach ($fixtures as $fixture) { $fixture->beforeUnload(); } $fixtures = array_reverse($fixtures); foreach ($fixtures as $fixture) { $fixture->unload(); } foreach ($fixtures as $fixture) { $fixture->afterUnload(); } }
Unloads the specified fixtures. This method will call [[Fixture::unload()]] for every fixture object. @param Fixture[] $fixtures the fixtures to be loaded. If this parameter is not specified, the return value of [[getFixtures()]] will be used. @throws InvalidConfigException
entailment
public function getFixtures() { if ($this->_fixtures === null) { $this->_fixtures = $this->createFixtures($this->fixtures()); } return $this->_fixtures; }
Returns the fixture objects as specified in [[globalFixtures()]] and [[fixtures()]]. @throws InvalidConfigException @return Fixture[] the loaded fixtures for the current test case
entailment
public function getFixture(string $name): Fixture { if ($this->_fixtures === null) { $this->_fixtures = $this->createFixtures($this->fixtures()); } $name = ltrim($name, '\\'); return $this->_fixtures[$name] ?? null; }
Returns the named fixture. @param $name @return Fixture|null the fixture object, or null if the named fixture does not exist @throws InvalidConfigException
entailment
protected function createFixtures(array $fixtures) { // normalize fixture configurations $config = []; // configuration provided in test case $aliases = []; // class name => alias or class name foreach ($fixtures as $name => $fixture) { if (!is_array($fixture)) { $class = ltrim($fixture, '\\'); $fixtures[$name] = ['class' => $class]; $aliases[$class] = is_int($name) ? $class : $name; } elseif (isset($fixture['class'])) { $class = ltrim($fixture['class'], '\\'); $config[$class] = $fixture; $aliases[$class] = $name; } else { throw new InvalidConfigException("You must specify 'class' for the fixture '$name'."); } } // create fixture instances $instances = []; $stack = array_reverse($fixtures); while (($fixture = array_pop($stack)) !== null) { if ($fixture instanceof Fixture) { $class = get_class($fixture); $name = isset($aliases[$class]) ? $aliases[$class] : $class; unset($instances[$name]); // unset so that the fixture is added to the last in the next line $instances[$name] = $fixture; } else { $class = ltrim($fixture['class'], '\\'); $name = isset($aliases[$class]) ? $aliases[$class] : $class; if (!isset($instances[$name])) { $instances[$name] = false; $stack[] = $fixture = app()->make($fixture['class']); foreach ($fixture->depends as $dep) { // need to use the configuration provided in test case $stack[] = isset($config[$dep]) ? $config[$dep] : ['class' => $dep]; } } elseif ($instances[$name] === false) { throw new InvalidConfigException("A circular dependency is detected for fixture '$class'."); } } } return $instances; }
Creates the specified fixture instances. All dependent fixtures will also be created. @param array $fixtures the fixtures to be created. You may provide fixture names or fixture configurations. If this parameter is not provided, the fixtures specified in [[globalFixtures()]] and [[fixtures()]] will be created. @throws InvalidConfigException if fixtures are not properly configured or if a circular dependency among the fixtures is detected @return Fixture[] the created fixture instances
entailment
public function check(ExerciseInterface $exercise, Input $input) { $process = new Process(sprintf('%s -l %s', PHP_BINARY, $input->getArgument('program'))); $process->run(); if ($process->isSuccessful()) { return Success::fromCheck($this); } return Failure::fromCheckAndReason($this, $process->getErrorOutput()); }
Simply check the student's solution can be linted with `php -l`. @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 getSimilarity() { if (!$this->calculated) { $this->setupMatrix(); } return $this->matrix[mb_strlen($this->compOne, 'UTF-8')][mb_strlen($this->compTwo, 'UTF-8')]; }
Returns similarity of strings, absolute number = Damerau Levenshtein distance. @return int
entailment
private function setupMatrix() { $cost = -1; $del = 0; $sub = 0; $ins = 0; $trans = 0; $this->matrix = [[]]; $oneSize = mb_strlen($this->compOne, 'UTF-8'); $twoSize = mb_strlen($this->compTwo, 'UTF-8'); for ($i = 0; $i <= $oneSize; $i += 1) { $this->matrix[$i][0] = $i > 0 ? $this->matrix[$i - 1][0] + $this->delCost : 0; } for ($i = 0; $i <= $twoSize; $i += 1) { // Insertion actualy $this->matrix[0][$i] = $i > 0 ? $this->matrix[0][$i - 1] + $this->insCost : 0; } for ($i = 1; $i <= $oneSize; $i += 1) { // Curchar for the first string $cOne = mb_substr($this->compOne, $i - 1, 1, 'UTF-8'); for ($j = 1; $j <= $twoSize; $j += 1) { // Curchar for the second string $cTwo = mb_substr($this->compTwo, $j - 1, 1, 'UTF-8'); // Compute substitution cost if ($this->compare($cOne, $cTwo) == 0) { $cost = 0; $trans = 0; } else { $cost = $this->subCost; $trans = $this->transCost; } // Deletion cost $del = $this->matrix[$i - 1][$j] + $this->delCost; // Insertion cost $ins = $this->matrix[$i][$j - 1] + $this->insCost; // Substitution cost, 0 if same $sub = $this->matrix[$i - 1][$j - 1] + $cost; // Compute optimal $this->matrix[$i][$j] = min($del, $ins, $sub); // Transposition cost if ($i > 1 && $j > 1) { // Last two $ccOne = mb_substr($this->compOne, $i - 2, 1, 'UTF-8'); $ccTwo = mb_substr($this->compTwo, $j - 2, 1, 'UTF-8'); if ($this->compare($cOne, $ccTwo) == 0 && $this->compare($ccOne, $cTwo) == 0) { // Transposition cost is computed as minimal of two $this->matrix[$i][$j] = min($this->matrix[$i][$j], $this->matrix[$i - 2][$j - 2] + $trans); } } } } $this->calculated = true; }
Procedure to compute matrix for given input strings. @return void
entailment
public function getMaximalDistance() { $oneSize = mb_strlen($this->compOne, 'UTF-8'); $twoSize = mb_strlen($this->compTwo, 'UTF-8'); // Is substitution cheaper that delete + insert? $subCost = min($this->subCost, $this->delCost + $this->insCost); // Get common size $minSize = min($oneSize, $twoSize); $maxSize = max($oneSize, $twoSize); $extraSize = $maxSize - $minSize; // On common size perform substitution / delete + insert, what is cheaper $maxCost = $subCost * $minSize; // On resulting do insert/delete if ($oneSize > $twoSize) { // Delete extra characters $maxCost += $extraSize * $this->delCost; } else { // Insert extra characters $maxCost += $extraSize * $this->insCost; } return $maxCost; }
Returns maximal possible edit Damerau Levenshtein distance between texts. On common substring of same length perform substitution / insert + delete (depends on what is cheaper), then on extra characters perform insertion / deletion @return int
entailment
public function displayMatrix() { $this->setupMatrix(); $oneSize = mb_strlen($this->compOne, 'UTF-8'); $twoSize = mb_strlen($this->compTwo, 'UTF-8'); $out = ' ' . $this->compOne . PHP_EOL; for ($y = 0; $y <= $twoSize; $y += 1) { if ($y - 1 < 0) { $out .= ' '; } else { $out .= mb_substr($this->compTwo, $y - 1, 1, 'UTF-8'); } for ($x = 0; $x <= $oneSize; $x += 1) { $out .= $this->matrix[$x][$y]; } $out .= PHP_EOL; } return $out; }
Returns computed matrix for given input strings (For debugging purposes). @return string
entailment
public function setInsCost($insCost) { $this->calculated = $insCost == $this->insCost ? $this->calculated : false; $this->insCost = $insCost; }
Sets cost of insertion operation (insert characters to first string to match second string). @param int $insCost Cost of character insertion @return void
entailment
public function setDelCost($delCost) { $this->calculated = $delCost == $this->delCost ? $this->calculated : false; $this->delCost = $delCost; }
Sets cost of deletion operation (delete characters from first string to match second string). @param int $delCost Cost of character deletion @return void
entailment
public function setSubCost($subCost) { $this->calculated = $subCost == $this->subCost ? $this->calculated : false; $this->subCost = $subCost; }
Sets cost of substitution operation. @param int $subCost Cost of character substitution @return void
entailment
public function setTransCost($transCost) { $this->calculated = $transCost == $this->transCost ? $this->calculated : false; $this->transCost = $transCost; }
Sets cost of transposition operation. @param int $transCost Cost of character transposition @return void
entailment
public function attach(EventDispatcher $eventDispatcher) { if (file_exists($this->databaseDirectory)) { throw new \RuntimeException( sprintf('Database directory: "%s" already exists', $this->databaseDirectory) ); } mkdir($this->databaseDirectory, 0777, true); try { $db = new PDO($this->userDsn); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (\PDOException $e) { rmdir($this->databaseDirectory); throw $e; } $eventDispatcher->listen('verify.start', function (Event $e) use ($db) { $e->getParameter('exercise')->seed($db); //make a copy - so solution can modify without effecting database user has access to copy($this->userDatabasePath, $this->solutionDatabasePath); }); $eventDispatcher->listen('run.start', function (Event $e) use ($db) { $e->getParameter('exercise')->seed($db); }); $eventDispatcher->listen('cli.verify.reference-execute.pre', function (CliExecuteEvent $e) { $e->prependArg($this->solutionDsn); }); $eventDispatcher->listen( ['cli.verify.student-execute.pre', 'cli.run.student-execute.pre'], function (CliExecuteEvent $e) { $e->prependArg($this->userDsn); } ); $eventDispatcher->insertVerifier('verify.finish', function (Event $e) use ($db) { $verifyResult = $e->getParameter('exercise')->verify($db); if (false === $verifyResult) { return Failure::fromNameAndReason($this->getName(), 'Database verification failed'); } return new Success('Database Verification Check'); }); $eventDispatcher->listen( [ 'cli.verify.reference-execute.fail', 'verify.finish', 'run.finish' ], function (Event $e) use ($db) { unset($db); @unlink($this->userDatabasePath); @unlink($this->solutionDatabasePath); rmdir($this->databaseDirectory); } ); }
Here we attach to various events to seed, verify and inject the DSN's to the student & reference solution programs's CLI arguments. @param EventDispatcher $eventDispatcher
entailment
public function render( ResultAggregator $results, ExerciseInterface $exercise, UserState $userState, OutputInterface $output ) { $successes = []; $failures = []; foreach ($results as $result) { if ($result instanceof SuccessInterface || ($result instanceof ResultGroupInterface && $result->isSuccessful()) ) { $successes[] = sprintf(' ✔ Check: %s', $result->getCheckName()); } else { $failures[] = [$result, sprintf(' ✗ Check: %s', $result->getCheckName())]; } } $output->emptyLine(); $output->writeLine($this->center($this->style('*** RESULTS ***', ['magenta', 'bold']))); $output->emptyLine(); $messages = array_merge($successes, array_column($failures, 1)); $longest = max(array_map('mb_strlen', $messages)) + 4; foreach ($successes as $success) { $output->writeLine($this->center($this->style(str_repeat(' ', $longest), ['bg_green']))); $output->writeLine( $this->center($this->style(mb_str_pad($success, $longest), ['bg_green', 'white', 'bold'])) ); $output->writeLine($this->center($this->style(str_repeat(' ', $longest), ['bg_green']))); $output->emptyLine(); } if ($results->isSuccessful()) { return $this->renderSuccessInformation($exercise, $userState, $output); } $this->renderErrorInformation($failures, $longest, $exercise, $output); }
Render the result set to the output and statistics on the number of exercises completed and remaining. @param ResultAggregator $results The result set. @param ExerciseInterface $exercise The exercise instance that was just attempted. @param UserState $userState The current state of the student's progress. @param OutputInterface $output The output instance.
entailment
public function style($string, $colourOrStyle) { if (is_array($colourOrStyle)) { $this->color->__invoke($string); while ($style = array_shift($colourOrStyle)) { $this->color->apply($style); } return $this->color->__toString(); } return $this->color->__invoke($string)->apply($colourOrStyle, $string); }
Style/colour a string. Can be any of: black, red, green, yellow, blue, magenta, cyan, white, bold, italic, underline. @param string $string @param array|string $colourOrStyle A single style as a string or multiple styles as an array. @return string
entailment
public function lineBreak() { return $this->style(str_repeat('─', $this->terminal->getWidth()), 'yellow'); }
Draw a line break across the terminal. @return string
entailment
private function doFilter(TokenFilterInterface $filter, array $tokens): array { $result = []; foreach ($tokens as $token) { $result = array_merge($result, $filter->filter($token)); } return $result; }
@param Token[] $tokens @return Token[]
entailment
public function render(ResultsRenderer $renderer) { $output = ''; if ($this->result->headersDifferent()) { $output .= sprintf( "%s %s\n%s %s", $renderer->style('YOUR HEADERS:', ['bold', 'yellow']), $this->headers($this->result->getActualHeaders(), $renderer), $renderer->style('EXPECTED HEADERS:', ['bold', 'yellow']), $this->headers($this->result->getExpectedHeaders(), $renderer, false) ); } if ($this->result->bodyDifferent()) { if ($this->result->headersAndBodyDifferent()) { $output .= "\n" . $renderer->style('- - - - - - - - -', ['default', 'bold']) . "\n\n"; } $output .= sprintf( "%s %s\n\n%s %s\n", $renderer->style('YOUR OUTPUT:', ['bold', 'yellow']), $renderer->style(sprintf('"%s"', $this->result->getActualOutput()), 'red'), $renderer->style('EXPECTED OUTPUT:', ['bold', 'yellow']), $renderer->style(sprintf('"%s"', $this->result->getExpectedOutput()), 'green') ); } return $output; }
Print the actual and expected output. @param ResultsRenderer $renderer @return string
entailment
public function sync($userId, $groupInfo) { try{ if (empty($userId)) throw new Exception('Paramer "userId" is required'); if (empty($groupInfo)) throw new Exception('Paramer "groupInfo" is required'); $params = array(); $params['userId'] = $userId; foreach ($groupInfo as $key => $value) { $params['group[' . $key . ']'] = $value; } $ret = $this->SendRequest->curl('/group/sync.json',$params,'urlencoded','im','POST'); if(empty($ret)) throw new Exception('bad request'); return $ret; }catch (Exception $e) { print_r($e->getMessage()); } }
同步用户所属群组方法(当第一次连接融云服务器时,需要向融云服务器提交 userId 对应的用户当前所加入的所有群组,此接口主要为防止应用中用户群信息同融云已知的用户所属群信息不同步。) @param userId:被同步群信息的用户 Id。(必传) @param groupInfo:该用户的群信息,如群 Id 已经存在,则不会刷新对应群组名称,如果想刷新群组名称请调用刷新群组信息方法。 @return $json
entailment
public function queryUser($groupId) { try{ if (empty($groupId)) throw new Exception('Paramer "groupId" is required'); $params = array ( 'groupId' => $groupId ); $ret = $this->SendRequest->curl('/group/user/query.json',$params,'urlencoded','im','POST'); if(empty($ret)) throw new Exception('bad request'); return $ret; }catch (Exception $e) { print_r($e->getMessage()); } }
查询群成员方法 @param groupId:群组Id。(必传) @return $json
entailment
public function paginate($page = 1, $maxPerPage = 10) { $this ->setLimit($maxPerPage) ->setOffset(($page - 1) * $maxPerPage); $pager = $this->find(); $pager->setPage($page); $pager->setMaxPerPage($maxPerPage); return $pager; }
@param int $page @param int $maxPerPage @return \Justimmo\Pager\ListPager
entailment
public function findPk($pk) { $method = $this->getDetailCall(); $response = $this->api->$method($pk); $return = $this->wrapper->transformSingle($response); $this->clear(); return $return; }
@param int $pk @return \Justimmo\Model\Realty|\Justimmo\Model\Employee
entailment
public function findIds() { $method = $this->getIdsCall(); $response = $this->api->$method($this->params); return json_decode($response); }
Get a array of realty, employee or project ids @return array
entailment
public function orderBy($column, $direction = 'asc') { return $this->order($this->mapper->getFilterPropertyName($column), $direction); }
translates and sets the order of a call @param string $column @param string $direction @return $this
entailment
public function order($column, $direction = 'asc') { $this->set('orderby', $column); $this->set('ordertype', $direction); return $this; }
sets order for a call @param string $column @param string $direction @return $this
entailment
public function filter($key, $value = null) { if ($value === null) { return $this; } if (is_array($value)) { if (array_key_exists('min', $value)) { $this->params['filter'][$key . '_von'] = $value['min']; } if (array_key_exists('max', $value)) { $this->params['filter'][$key . '_bis'] = $value['max']; } if (array_key_exists('min', $value) || array_key_exists('max', $value)) { return $this; } } $this->params['filter'][$key] = $value; return $this; }
adds a filter column @param $key @param null $value @return $this
entailment
public function getAttachmentsByType($type, $group = false) { $attachments = array(); /** @var \Justimmo\Model\Attachment $attachment */ foreach ($this->attachments as $attachment) { if ($attachment->getType() == $type && ($group === false || $group == $attachment->getGroup())) { $attachments[] = $attachment; } } return $attachments; }
@param $type @param null|string|boolean $group @return array
entailment
public function respond(Match $match, TemplateInterface $template, $message = '') { if ($match->isMatch()) { return; } $this->formatter->setMatch($match); $message = ($message) ? $message : $this->formatter->getMessage($template); throw new AssertionException($message); }
{@inheritdoc} Throws an exception containing the formatted message. @param Match $match @param TemplateInterface $template @param string $message @return void @throws Exception
entailment
public function getDefaultTemplate() { $subject = 'key'; if (count($this->expected) > 1) { $subject = 'keys'; } $template = new ArrayTemplate([ 'default' => "Expected {{actual}} to {$this->verb} $subject {{keys}}", 'negated' => "Expected {{actual}} to not {$this->verb} $subject {{keys}}", ]); return $template->setTemplateVars(['keys' => $this->getKeyString()]); }
{@inheritdoc} @return TemplateInterface
entailment
protected function doMatch($actual) { $actual = $this->getArrayValue($actual); if ($this->assertion->flag('contain')) { $this->verb = 'contain'; return $this->matchInclusion($actual); } $keys = array_keys($actual); return $keys == $this->expected; }
Assert that the actual value is an array or object with the expected keys. @param $actual @return mixed
entailment
protected function getArrayValue($actual) { if (is_object($actual)) { return get_object_vars($actual); } if (is_array($actual)) { return $actual; } throw new \InvalidArgumentException('KeysMatcher expects object or array'); }
Normalize the actual value into an array, whether it is an object or an array. @param object|array $actual
entailment
protected function getKeyString() { $expected = $this->expected; $keys = ''; $tail = array_pop($expected); if (!empty($expected)) { $keys = implode('","', $expected) . '", and "'; } $keys .= $tail; return $keys; }
Returns a formatted string of expected keys. @return string keys
entailment
protected function matchInclusion($actual) { foreach ($this->expected as $key) { if (!array_key_exists($key, $actual)) { return false; } } return true; }
Used when the 'contain' flag exists on the Assertion. Checks if the expected keys are included in the object or array. @param array $actual @return true
entailment
public function getValidUntil($format = 'Y-m-d') { if ($this->validUntil instanceof \DateTime && $format !== null) { return $this->validUntil->format($format); } return $this->validUntil; }
@param string $format formats the date to the specific format, null returns DateTime @return \DateTime|null
entailment
private function writeContributors(array $contributors) { $nameColumnSize = max(array_map('strlen', array_values($contributors))); $columns = sprintf('%s GitHub Username', str_pad('Name', $nameColumnSize)); $this->output->writeLine($columns); $this->output->writeLine(str_repeat('-', strlen($columns))); foreach ($contributors as $gitHubUser => $name) { $this->output->writeLine(sprintf("%s %s", str_pad($name, $nameColumnSize), $gitHubUser)); } }
Output contributors in columns @param array $contributors
entailment
public function getInfo($key) { if (!array_key_exists($key, $this->infos)) { throw new CurlException('Information ' . $key . ' not found in CurlRequest'); } return $this->infos[$key]; }
retrieve an info about this curl request @param $key @return mixed @throws CurlException
entailment
public function getOption($key) { if (!array_key_exists($key, $this->options)) { throw new CurlException('The Options ' . $key . ' is not registered in this CurlRequest'); } return $this->options[$key]; }
gets the value of an option in this curl request @param $key @return mixed @throws CurlException
entailment
public function post($parameters = null) { $this->setOption(CURLOPT_POST, true); if ($parameters !== null) { $this->setParameters($parameters); } return $this->execute(); }
executes a post request @param null $parameters @return mixed
entailment
public function put($parameters = null) { $this->setOption(CURLOPT_PUT, true); if ($parameters !== null) { $this->setParameters($parameters); } return $this->execute(); }
executes a put request @param null $parameters @return mixed
entailment
protected function execute() { if ($this->url === null) { throw new CurlException('You have to provide an URL for the CurlRequest'); } $ch = curl_init($this->url); curl_setopt_array($ch, $this->options); $this->content = curl_exec($ch); $this->infos = curl_getinfo($ch); $this->error = curl_error($ch); curl_close($ch); return $this->content; }
executes the curl request and fills in the information @return mixed @throws CurlException
entailment
public function publishPrivate($fromUserId, $toUserId, $objectName, $content, $pushContent = '', $pushData = '', $count = '', $verifyBlacklist, $isPersisted, $isCounted, $isIncludeSender) { try{ if (empty($fromUserId)) throw new Exception('Paramer "fromUserId" is required'); if (empty($toUserId)) throw new Exception('Paramer "toUserId" is required'); if (empty($objectName)) throw new Exception('Paramer "$objectName" is required'); if (empty($content)) throw new Exception('Paramer "$content" is required'); $params = array ( 'fromUserId' => $fromUserId, 'toUserId' => $toUserId, 'objectName' => $objectName, 'content' => $content, 'pushContent' => $pushContent, 'pushData' => $pushData, 'count' => $count, 'verifyBlacklist' => $verifyBlacklist, 'isPersisted' => $isPersisted, 'isCounted' => $isCounted, 'isIncludeSender' => $isIncludeSender ); $ret = $this->SendRequest->curl('/message/private/publish.json',$params,'urlencoded','im','POST'); if(empty($ret)) throw new Exception('bad request'); return $ret; }catch (Exception $e) { print_r($e->getMessage()); } }
发送单聊消息方法(一个用户向另外一个用户发送消息,单条消息最大 128k。每分钟最多发送 6000 条信息,每次发送用户上限为 1000 人,如:一次发送 1000 人时,示为 1000 条消息。) @param fromUserId:发送人用户 Id。(必传) @param toUserId:接收用户 Id,可以实现向多人发送消息,每次上限为 1000 人。(必传) @param voiceMessage:消息。 @param pushContent:定义显示的 Push 内容,如果 objectName 为融云内置消息类型时,则发送后用户一定会收到 Push 信息。如果为自定义消息,则 pushContent 为自定义消息显示的 Push 内容,如果不传则用户不会收到 Push 通知。(可选) @param pushData:针对 iOS 平台为 Push 通知时附加到 payload 中,Android 客户端收到推送消息时对应字段名为 pushData。(可选) @param count:针对 iOS 平台,Push 时用来控制未读消息显示数,只有在 toUserId 为一个用户 Id 的时候有效。(可选) @param verifyBlacklist:是否过滤发送人黑名单列表,0 表示为不过滤、 1 表示为过滤,默认为 0 不过滤。(可选) @param isPersisted:当前版本有新的自定义消息,而老版本没有该自定义消息时,老版本客户端收到消息后是否进行存储,0 表示为不存储、 1 表示为存储,默认为 1 存储消息。(可选) @param isCounted:当前版本有新的自定义消息,而老版本没有该自定义消息时,老版本客户端收到消息后是否进行未读消息计数,0 表示为不计数、 1 表示为计数,默认为 1 计数,未读消息数增加 1。(可选) @param isIncludeSender:发送用户自已是否接收消息,0 表示为不接收,1 表示为接收,默认为 0 不接收。(可选) @return $json
entailment
public function PublishSystem($fromUserId, $toUserId, $objectName, $content, $pushContent = '', $pushData = '', $isPersisted, $isCounted) { try{ if (empty($fromUserId)) throw new Exception('Paramer "fromUserId" is required'); if (empty($toUserId)) throw new Exception('Paramer "toUserId" is required'); if (empty($objectName)) throw new Exception('Paramer "$objectName" is required'); if (empty($content)) throw new Exception('Paramer "$content" is required'); $params = array ( 'fromUserId' => $fromUserId, 'toUserId' => $toUserId, 'objectName' => $objectName, 'content' => $content, 'pushContent' => $pushContent, 'pushData' => $pushData, 'isPersisted' => $isPersisted, 'isCounted' => $isCounted ); $ret = $this->SendRequest->curl('/message/system/publish.json',$params,'urlencoded','im','POST'); if(empty($ret)) throw new Exception('bad request'); return $ret; }catch (Exception $e) { print_r($e->getMessage()); } }
发送系统消息方法(一个用户向一个或多个用户发送系统消息,单条消息最大 128k,会话类型为 SYSTEM。每秒钟最多发送 100 条消息,每次最多同时向 100 人发送,如:一次发送 100 人时,示为 100 条消息。) @param fromUserId:发送人用户 Id。(必传) @param toUserId:接收用户 Id,提供多个本参数可以实现向多人发送消息,上限为 1000 人。(必传) @param txtMessage:发送消息内容(必传) @param pushContent:如果为自定义消息,定义显示的 Push 内容,内容中定义标识通过 values 中设置的标识位内容进行替换.如消息类型为自定义不需要 Push 通知,则对应数组传空值即可。(可选) @param pushData:针对 iOS 平台为 Push 通知时附加到 payload 中,Android 客户端收到推送消息时对应字段名为 pushData。如不需要 Push 功能对应数组传空值即可。(可选) @param isPersisted:当前版本有新的自定义消息,而老版本没有该自定义消息时,老版本客户端收到消息后是否进行存储,0 表示为不存储、 1 表示为存储,默认为 1 存储消息。(可选) @param isCounted:当前版本有新的自定义消息,而老版本没有该自定义消息时,老版本客户端收到消息后是否进行未读消息计数,0 表示为不计数、 1 表示为计数,默认为 1 计数,未读消息数增加 1。(可选) @return $json
entailment
public function publishSystemTemplate($templateMessage) { try{ if (empty($templateMessage)) throw new Exception('Paramer "templateMessage" is required'); $params = json_decode($templateMessage,TRUE); $ret = $this->SendRequest->curl('/message/system/publish_template.json',$params,'json','im','POST'); if(empty($ret)) throw new Exception('bad request'); return $ret; }catch (Exception $e) { print_r($e->getMessage()); } }
发送系统模板消息方法(一个用户向一个或多个用户发送系统消息,单条消息最大 128k,会话类型为 SYSTEM.每秒钟最多发送 100 条消息,每次最多同时向 100 人发送,如:一次发送 100 人时,示为 100 条消息。) @param templateMessage:系统模版消息。 @return $json
entailment
public function publishGroup($fromUserId, $toGroupId, $objectName, $content, $pushContent = '', $pushData = '', $isPersisted, $isCounted, $isIncludeSender) { try{ if (empty($fromUserId)) throw new Exception('Paramer "fromUserId" is required'); if (empty($toGroupId)) throw new Exception('Paramer "toGroupId" is required'); if (empty($objectName)) throw new Exception('Paramer "$objectName" is required'); if (empty($content)) throw new Exception('Paramer "$content" is required'); $params = array ( 'fromUserId' => $fromUserId, 'toGroupId' => $toGroupId, 'objectName' => $objectName, 'content' => $content, 'pushContent' => $pushContent, 'pushData' => $pushData, 'isPersisted' => $isPersisted, 'isCounted' => $isCounted, 'isIncludeSender' => $isIncludeSender ); $ret = $this->SendRequest->curl('/message/group/publish.json',$params,'urlencoded','im','POST'); if(empty($ret)) throw new Exception('bad request'); return $ret; }catch (Exception $e) { print_r($e->getMessage()); } }
发送群组消息方法(以一个用户身份向群组发送消息,单条消息最大 128k.每秒钟最多发送 20 条消息,每次最多向 3 个群组发送,如:一次向 3 个群组发送消息,示为 3 条消息。) @param fromUserId:发送人用户 Id 。(必传) @param toGroupId:接收群Id,提供多个本参数可以实现向多群发送消息,最多不超过 3 个群组。(必传) @param txtMessage:发送消息内容(必传) @param pushContent:定义显示的 Push 内容,如果 objectName 为融云内置消息类型时,则发送后用户一定会收到 Push 信息. 如果为自定义消息,则 pushContent 为自定义消息显示的 Push 内容,如果不传则用户不会收到 Push 通知。(可选) @param pushData:针对 iOS 平台为 Push 通知时附加到 payload 中,Android 客户端收到推送消息时对应字段名为 pushData。(可选) @param isPersisted:当前版本有新的自定义消息,而老版本没有该自定义消息时,老版本客户端收到消息后是否进行存储,0 表示为不存储、 1 表示为存储,默认为 1 存储消息。(可选) @param isCounted:当前版本有新的自定义消息,而老版本没有该自定义消息时,老版本客户端收到消息后是否进行未读消息计数,0 表示为不计数、 1 表示为计数,默认为 1 计数,未读消息数增加 1。(可选) @param isIncludeSender:发送用户自已是否接收消息,0 表示为不接收,1 表示为接收,默认为 0 不接收。(可选) @return $json
entailment
public function broadcast($fromUserId, $objectName, $content, $pushContent = '', $pushData = '', $os = '') { try{ if (empty($fromUserId)) throw new Exception('Paramer "fromUserId" is required'); if (empty($objectName)) throw new Exception('Paramer "$objectName" is required'); if (empty($content)) throw new Exception('Paramer "$content" is required'); $params = array ( 'fromUserId' => $fromUserId, 'objectName' => $objectName, 'content' => $content, 'pushContent' => $pushContent, 'pushData' => $pushData, 'os' => $os ); $ret = $this->SendRequest->curl('/message/broadcast.json',$params,'urlencoded','im','POST'); if(empty($ret)) throw new Exception('bad request'); return $ret; }catch (Exception $e) { print_r($e->getMessage()); } }
发送广播消息方法(发送消息给一个应用下的所有注册用户,如用户未在线会对满足条件(绑定手机终端)的用户发送 Push 信息,单条消息最大 128k,会话类型为 SYSTEM。每小时只能发送 1 次,每天最多发送 3 次。) @param fromUserId:发送人用户 Id。(必传) @param txtMessage:文本消息。 @param pushContent:定义显示的 Push 内容,如果 objectName 为融云内置消息类型时,则发送后用户一定会收到 Push 信息. 如果为自定义消息,则 pushContent 为自定义消息显示的 Push 内容,如果不传则用户不会收到 Push 通知.(可选) @param pushData:针对 iOS 平台为 Push 通知时附加到 payload 中,Android 客户端收到推送消息时对应字段名为 pushData。(可选) @param os:针对操作系统发送 Push,值为 iOS 表示对 iOS 手机用户发送 Push ,为 Android 时表示对 Android 手机用户发送 Push ,如对所有用户发送 Push 信息,则不需要传 os 参数。(可选) @return $json
entailment
public function getHistory($date) { try{ if (empty($date)) throw new Exception('Paramer "date" is required'); $params = array ( 'date' => $date ); $ret = $this->SendRequest->curl('/message/history.json',$params,'urlencoded','im','POST'); if(empty($ret)) throw new Exception('bad request'); return $ret; }catch (Exception $e) { print_r($e->getMessage()); } }
消息历史记录下载地址获取 方法消息历史记录下载地址获取方法。获取 APP 内指定某天某小时内的所有会话消息记录的下载地址。(目前支持二人会话、讨论组、群组、聊天室、客服、系统通知消息历史记录下载) @param date:指定北京时间某天某小时,格式为2014010101,表示:2014年1月1日凌晨1点。(必传) @return $json
entailment
public function setCookie() { $language = current($this->getLanguages()); if ($language !== Yii::$app->language) { $this->cookie->value = Yii::$app->language; $this->response->getCookies()->add($this->cookie); } }
Sets the cookie.
entailment
public function registerDependencies() { if(empty($this->languageProvider)) { throw new InvalidConfigException("Invalid configuration of '$this->id' module"); } Yii::$container->set('bl\emailTemplates\providers\LanguageProviderInterface', $this->languageProvider); }
Add language provider to DI container
entailment
public function render(ResultsRenderer $renderer) { $output = ''; if (count($bannedFunctions = $this->result->getBannedFunctions())) { $output .= sprintf( " %s\n%s\n", $renderer->style( "Some functions were used which should not be used in this exercise", ['bold', 'underline', 'yellow'] ), implode("\n", array_map(function (array $call) { return sprintf(' %s on line %s', $call['function'], $call['line']); }, $bannedFunctions)) ); } if (count($missingFunctions = $this->result->getMissingFunctions())) { $output .= sprintf( " %s\n%s\n", $renderer->style( "Some function requirements were missing. You should use the functions", ['bold', 'underline', 'yellow'] ), implode("\n", array_map(function ($function) { return sprintf(' %s', $function); }, $missingFunctions)) ); } return $output; }
Print a list of the missing, required functions & print a list of used but banned functions. @param ResultsRenderer $renderer @return string
entailment
public function actionList() { $templates = EmailTemplate::find()->all(); return $this->render('list', [ 'templates' => $templates, 'language' => $this->_languageProvider->getDefault() ]); }
Rendering list of templates @return string
entailment
protected function renderForm($form, $view) { $errors = []; if(Yii::$app->request->isPost) { $form->load(Yii::$app->request->post()); if(!$form->save()) { $errors = $form->getErrors(); } return $this->redirect('list'); } $currentLanguage = [ $form->languageId => $this->_languageProvider->getNameByID($form->languageId) ]; return $this->render($view, [ 'model' => $form, 'errors' => $errors, 'currentLanguage' => $currentLanguage ]); }
Method for rendering form for create and edit of template @param TemplateForm $form @param string $view @return string
entailment
public function actionEdit($templateId, $languageId = null) { $editForm = new EditForm([ 'templateId' => $templateId, 'languageId' => $languageId ]); return $this->renderForm($editForm, 'edit'); }
Editing of template @param integer $templateId @param null|integer $languageId @return string @throws Exception
entailment
public function actionDelete($templateId) { if($template = EmailTemplate::findOne($templateId)) { $template->delete(); } return $this->redirect(Url::toRoute('list')); }
Removing of template @param integer $templateId @return Response
entailment
public function throws(callable $fn, $exceptionType, $exceptionMessage = '', $message = '') { $this->assertion->setActual($fn); return $this->assertion->to->throw($exceptionType, $exceptionMessage, $message); }
Performs a throw assertion. @param callable $fn @param $exceptionType @param string $exceptionMessage @param string $message
entailment
public function doesNotThrow(callable $fn, $exceptionType, $exceptionMessage = '', $message = '') { $this->assertion->setActual($fn); return $this->assertion->not->to->throw($exceptionType, $exceptionMessage, $message); }
Performs a negated throw assertion. @param callable $fn @param $exceptionType @param string $exceptionMessage @param string $message
entailment
public function ok($object, $message = '') { $this->assertion->setActual($object); return $this->assertion->to->be->ok($message); }
Perform an ok assertion. @param mixed $object @param string $message
entailment
public function strictEqual($actual, $expected, $message = '') { $this->assertion->setActual($actual); return $this->assertion->to->equal($expected, $message); }
Perform a strict equality assertion. @param mixed $actual @param mixed $expected @param string $message
entailment
public function notStrictEqual($actual, $expected, $message = '') { $this->assertion->setActual($actual); return $this->assertion->to->not->equal($expected, $message); }
Perform a negated strict equality assertion. @param mixed $actual @param mixed $expected @param string $message
entailment
public function match($value, $pattern, $message = '') { $this->assertion->setActual($value); return $this->assertion->to->match($pattern, $message); }
Perform a pattern assertion. @param string $value @param string $pattern @param string $message
entailment
public function operator($left, $operator, $right, $message = '') { if (!isset(static::$operators[$operator])) { throw new \InvalidArgumentException("Invalid operator $operator"); } $this->assertion->setActual($left); return $this->assertion->{static::$operators[$operator]}($right, $message); }
Compare two values using the given operator. @param mixed $left @param string $operator @param mixed $right @param string $message
entailment
protected function generateSignature() { $signature = $this->getMerchantPassword(); $signature .= $this->getMerchantId(); $signature .= $this->getAcquirerId(); return base64_encode( sha1($signature, true) ); }
Returns the signature for the request. @return string base64 encoded sha1 hash of the merchantPassword, merchantId, and acquirerId.
entailment
public function getData() { $this->validate('merchantId', 'merchantPassword', 'acquirerId', 'customerReference', 'cardReference', 'card'); $this->getCard()->validate(); $data = [ 'CustomerReference' => $this->getCustomerReference(), 'ExpiryDate' => $this->getCard()->getExpiryDate('my'), 'MerchantNumber' => $this->getMerchantId(), 'Signature' => $this->generateSignature(), 'TokenPAN' => $this->getCardReference() ]; return $data; }
Validate and construct the data for the request @return array
entailment
public function verifySignature() { if ( isset($this->data['CreditCardTransactionResults']['ResponseCode']) && ( '1' == $this->data['CreditCardTransactionResults']['ResponseCode'] || '2' == $this->data['CreditCardTransactionResults']['ResponseCode']) ) { $signature = $this->request->getMerchantPassword(); $signature .= $this->request->getMerchantId(); $signature .= $this->request->getAcquirerId(); $signature .= $this->request->getTransactionId(); $signature = base64_encode( sha1($signature, true) ); if ( $signature !== $this->data['Signature'] ) { throw new InvalidResponseException('Signature verification failed'); } } }
Verifies the signature for the response. @throws InvalidResponseException if the signature doesn't match @return void
entailment
public function hasInstalledPackage($packageName) { foreach ($this->contents['packages'] as $packageDetails) { if ($packageName === $packageDetails['name']) { return true; } } return false; }
Check if a package name has been installed in any version. @param string $packageName @return bool
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 requests to your solution produced incorrect output!\n"); } foreach ($results as $key => $request) { $output .= $renderer->lineBreak(); $output .= "\n"; $output .= $renderer->style(sprintf('Request %d', $key + 1), ['bold', 'underline', 'blue']); $output .= ' ' . $renderer->style(' FAILED ', ['bg_red', 'bold']) . "\n\n"; $output .= "Request Details:\n\n"; $output .= $this->requestRenderer->renderRequest($request->getRequest()) . "\n"; $output .= $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 static function fromProcess(Process $process) { $message = 'PHP Code failed to execute. Error: "%s"'; $processOutput = $process->getErrorOutput() ? $process->getErrorOutput() : $process->getOutput(); return new static(sprintf($message, $processOutput)); }
Static constructor to create an instance from a failed `Symfony\Component\Process\Process` instance. @param Process $process The `Symfony\Component\Process\Process` instance which failed. @return static
entailment
public static function trim(Exception $exception) { $reflector = new ReflectionClass('Exception'); $traceProperty = $reflector->getProperty('trace'); $traceProperty->setAccessible(true); $call = static::traceLeoCall($traceProperty->getValue($exception)); if ($call) { $trace = array($call); list($file, $line) = self::traceCallPosition($call); } else { $trace = array(); $file = null; $line = null; } $traceProperty->setValue($exception, $trace); self::updateExceptionPosition($reflector, $exception, $file, $line); }
Trim the supplied exception's stack trace to only include relevant information. Also replaces the file path and line number. @param Exception $exception The exception.
entailment
public static function traceLeoCall(array $trace) { for ($i = count($trace) - 1; $i >= 0; --$i) { if (self::isLeoTraceEntry($trace[$i])) { return $trace[$i]; } } return null; }
Find the Leo entry point call in a stack trace. @param array $trace The stack trace. @return array|null The call, or null if unable to determine the entry point.
entailment
private function loadPucene(array $config, ContainerBuilder $container): void { $serviceIds = []; foreach ($config['indices'] as $name => $options) { $definition = new Definition( DbalStorage::class, [ $name, new Reference($config['adapters']['pucene']['doctrine_dbal_connection']), new Reference('pucene.pucene.compiler'), new Reference('pucene.pucene.interpreter'), ] ); $serviceIds[$name] = 'pucene.pucene.doctrine_dbal.' . $name; $container->setDefinition($serviceIds[$name], $definition); } $container->getDefinition('pucene.pucene.storage_factory')->replaceArgument(1, $serviceIds); $pass = new CollectorCompilerPass('pucene.pucene.visitor', 'pucene.pucene.visitor_pool', 'query'); $pass->process($container); $pass = new CollectorCompilerPass('pucene.pucene.interpreter', 'pucene.pucene.interpreter_pool', 'element'); $pass->process($container); }
Load specific configuration for pucene.
entailment
private function loadElasticsearch(array $config, ContainerBuilder $container): void { $pass = new CollectorCompilerPass('pucene.elasticsearch.visitor', 'pucene.elasticsearch.visitor_pool', 'query'); $pass->process($container); }
Load specific configuration for elasticsearch.
entailment
public function saveAttribute() { $language = current($this->getLanguages()); if ($language !== Yii::$app->language) { $this->identity->{$this->languageAttribute} = Yii::$app->language; $this->identity->save(true, [$this->languageAttribute]); } }
Saves the language attribute.
entailment
protected function doMatch($actual) { if (!is_string($actual)) { throw new \InvalidArgumentException('PatternMatcher expects a string'); } return (bool) preg_match($this->expected, $actual); }
Match the actual value against a regular expression. @param $actual @return mixed
entailment
public function toKeyValue($keyGetter, $valueGetter) { $return = array(); foreach ($this as $value) { if (!method_exists($value, $keyGetter)) { throw new MethodNotFoundException('Method ' . $keyGetter . ' not found on ' . get_class($value)); } if (!method_exists($value, $valueGetter)) { throw new MethodNotFoundException('Method ' . $valueGetter . ' not found on ' . get_class($value)); } $return[$value->$keyGetter()] = $value->$valueGetter(); } return $return; }
converts the data into a key/value store array @param $keyGetter @param $valueGetter @return array @throws \Justimmo\Exception\MethodNotFoundException
entailment
private function visitQueries(array $queries) { $result = []; foreach ($queries as $query) { $result[] = $this->getInterpreter($query)->visit($query); } return $result; }
Returns visited queries. @param QueryInterface[] $queries @return array
entailment
public function addHeaderToRequest($header, $value) { $this->request = $this->request->withHeader($header, $value); }
Add a header to the request. @param string $header @param string|string[] $value
entailment
public function findByName($name) { foreach ($this->exercises as $exercise) { if ($name === $exercise->getName()) { return $exercise; } } throw new InvalidArgumentException(sprintf('Exercise with name: "%s" does not exist', $name)); }
Find an exercise by it's name. If it does not exist an `InvalidArgumentException` exception is thrown. @param string $name @return ExerciseInterface @throws InvalidArgumentException
entailment
protected function connectToServer($username, $password, $database, $hostname, $persistent = false, $type = 'mysql', $port = 3306, $options = []) { if(!$this->db) { $this->database = $database; $this->db = new PDO(sprintf(self::$connectors[$type], $hostname, $port, $database), $username, $password, array_merge( ($persistent !== false ? array(PDO::ATTR_PERSISTENT => true) : []), ($type === 'mysql' ? array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, PDO::ATTR_EMULATE_PREPARES => true) : []), (is_array($options) ? $options : []) ) ); $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } }
Connect to the database using PDO connection @param string $username This should be the username for the chosen database @param string $password This should be the password for the chosen database @param string $database This should be the database that you wish to connect to @param string $hostname The host for the database @param boolean $persistent If you want a persistent database connection set to true @param string $type The type of connection that you wish to make can be 'mysql', 'cubrid', 'dblib', 'mssql', 'pgsql, or 'sqlite' @param int $port The port number to connect to the MySQL server @param array $options Add any additional PDO connection options here
entailment
public function setCaching($caching) { if(is_object($caching)) { $this->cacheObj = $caching; $this->cacheEnabled = true; } return $this; }
Enables the caching and set the caching object to the one provided @param object $caching This should be class of the type of caching you are using
entailment
public function query($sql, $variables = array(), $cache = true) { if(!empty(trim($sql))){ $this->sql = $sql; $this->key = md5($this->sql.serialize($variables)); if($this->logQueries) {$this->writeQueryToLog();} if($cache && $this->cacheEnabled && $this->getCache($this->key)) { return $this->cacheValue; } try{ $this->query = $this->db->prepare($this->sql); $result = $this->query->execute($variables); if(strpos($this->sql, 'SELECT') !== false) { $result = $this->query->fetchAll(PDO::FETCH_ASSOC); if($cache && $this->cacheEnabled) {$this->setCache($this->key, $result);} } return $result; } catch(\Exception $e) { $this->error($e); } } }
This query function is used for more advanced SQL queries for which non of the other methods fit @param string $sql This should be the SQL query which you wish to run @param array $variables This should be an array of values to execute as the values in a prepared statement @return array|boolean Returns array of results for the query that has just been run if select or returns true and false if executed successfully or not
entailment
public function select($table, $where = array(), $fields = '*', $order = array(), $cache = true) { return $this->selectAll($table, $where, $fields, $order, 1, $cache); }
Returns a single record for a select query for the chosen table @param string $table This should be the table you wish to select the values from @param array $where Should be the field names and values you wish to use as the where query e.g. array('fieldname' => 'value', 'fieldname2' => 'value2', etc). @param string|array $fields This should be the records you wis to select from the table. It should be either set as '*' which is the default or set as an array in the following format array('field', 'field2', 'field3', etc). @param array $order This is the order you wish the results to be ordered in should be formatted as follows array('fieldname' => 'ASC') or array("'fieldname', 'fieldname2'" => 'DESC') @param boolean $cache If the query should be cached or loaded from cache set to true else set to false @return array Returns a single table record as the standard array when running SQL queries
entailment
public function selectAll($table, $where = array(), $fields = '*', $order = array(), $limit = 0, $cache = true) { $this->buildSelectQuery(SafeString::makeSafe($table), $where, $fields, $order, $limit); $result = $this->executeQuery($cache); if(!$result) { if($limit === 1) {$result = $this->query->fetch(PDO::FETCH_ASSOC);} // Reduce the memory usage if only one record and increase performance else{$result = $this->query->fetchAll(PDO::FETCH_ASSOC);} if($cache && $this->cacheEnabled) {$this->setCache($this->key, $result);} } return $result ? $result : false; }
Returns a multidimensional array of the results from the selected table given the given parameters @param string $table This should be the table you wish to select the values from @param array $where Should be the field names and values you wish to use as the where query e.g. array('fieldname' => 'value', 'fieldname2' => 'value2', etc). @param string|array $fields This should be the records you wis to select from the table. It should be either set as '*' which is the default or set as an array in the following format array('field', 'field2', 'field3', etc). @param array $order This is the order you wish the results to be ordered in should be formatted as follows array('fieldname' => 'ASC') or array("'fieldname', 'fieldname2'" => 'DESC') @param integer|array $limit The number of results you want to return 0 is default and returns all results, else should be formated either as a standard integer or as an array as the start and end values e.g. array(0 => 150) @param boolean $cache If the query should be cached or loaded from cache set to true else set to false @return array Returns a multidimensional array with the chosen fields from the table
entailment
public function fetchColumn($table, $where = array(), $fields = '*', $colNum = 0, $order = array(), $cache = true) { $this->buildSelectQuery(SafeString::makeSafe($table), $where, $fields, $order, 1); $result = $this->executeQuery($cache); if(!$result) { $column = $this->query->fetchColumn(intval($colNum)); if($cache && $this->cacheEnabled) {$this->setCache($this->key, $column);} return ($column ? $column : false); } return false; }
Returns a single column value for a given query @param string $table This should be the table you wish to select the values from @param array $where Should be the field names and values you wish to use as the where query e.g. array('fieldname' => 'value', 'fieldname2' => 'value2', etc). @param array $fields This should be the records you wis to select from the table. It should be either set as '*' which is the default or set as an array in the following format array('field', 'field2', 'field3', etc). @param int $colNum This should be the column number you wish to get (starts at 0) @param array $order This is the order you wish the results to be ordered in should be formatted as follows array('fieldname' => 'ASC') or array("'fieldname', 'fieldname2'" => 'DESC') so it can be done in both directions @param boolean $cache If the query should be cached or loaded from cache set to true else set to false @return mixed If a result is found will return the value of the colum given else will return false
entailment
public function insert($table, $records) { unset($this->prepare); $this->sql = sprintf("INSERT INTO `%s` (%s) VALUES (%s);", SafeString::makeSafe($table), $this->fields($records, true), implode(', ', $this->prepare)); $this->executeQuery(false); return $this->numRows() ? true : false; }
Inserts into database using the prepared PDO statements @param string $table This should be the table you wish to insert the values into @param array $records This should be the field names and values in the format of array('fieldname' => 'value', 'fieldname2' => 'value2', etc.) @return boolean If data is inserted returns true else returns false
entailment
public function update($table, $records, $where = array(), $limit = 0) { $this->sql = sprintf("UPDATE `%s` SET %s %s%s;", SafeString::makeSafe($table), $this->fields($records), $this->where($where), $this->limit($limit)); $this->executeQuery(false); return $this->numRows() ? true : false; }
Updates values in a database using the provide variables @param string $table This should be the table you wish to update the values for @param array $records This should be the field names and new values in the format of array('fieldname' => 'newvalue', 'fieldname2' => 'newvalue2', etc.) @param array $where Should be the field names and values you wish to update in the form of an array e.g. array('fieldname' => 'value', 'fieldname2' => 'value2', etc). @param int $limit The number of results you want to return 0 is default and will update all results that match the query, else should be formated as a standard integer @return boolean Returns true if update is successful else returns false
entailment
public function delete($table, $where, $limit = 0) { $this->sql = sprintf("DELETE FROM `%s` %s%s;", SafeString::makeSafe($table), $this->where($where), $this->limit($limit)); $this->executeQuery(false); return $this->numRows() ? true : false; }
Deletes records from the given table based on the variables given @param string $table This should be the table you wish to delete the records from @param array $where This should be an array of for the where statement @param int $limit The number of results you want to return 0 is default and will delete all results that match the query, else should be formated as a standard integer
entailment
public function count($table, $where = array(), $cache = true) { $this->sql = sprintf("SELECT count(*) FROM `%s`%s;", SafeString::makeSafe($table), $this->where($where)); $this->key = md5($this->database.$this->sql.serialize($this->values)); $result = $this->executeQuery($cache); if(!$result) { $result = $this->query->fetchColumn(); if($cache && $this->cacheEnabled) {$this->setCache($this->key, $result);} } return $result; }
Count the number of return results @param string $table The table you wish to count the result of @param array $where Should be the field names and values you wish to use as the where query e.g. array('fieldname' => 'value', 'fieldname2' => 'value2', etc). @param boolean $cache If the query should be cached or loaded from cache set to true else set to false @return int Returns the number of results
entailment
public function truncate($table) { try{ $this->sql = sprintf("TRUNCATE TABLE `%s`", SafeString::makeSafe($table)); $this->executeQuery(false); } catch(\Exception $e) { $this->error($e); } return $this->numRows() ? true : false; }
Truncates a given table from the selected database so there are no values in the table @param string $table This should be the table you wish to truncate @return boolean If the table is emptied returns true else returns false
entailment
public function setLogLocation($location = false) { if($location === false) { $location = dirname(__FILE__).DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR; } $this->logLocation = $location; if (!file_exists($location)) { mkdir($location, 0777, true); } return $this; }
Sets the location of the log files @param string $location This should be where you wish the logs to be stored @return $this
entailment
private function error($error) { if($this->logErrors) { $file = $this->logLocation.'db-errors.txt'; $current = file_get_contents($file); $current .= date('d/m/Y H:i:s')." ERROR: ".$error->getMessage()." on ".$this->sql."\n"; file_put_contents($file, $current); } die($this->displayErrors ? 'ERROR: '.$error->getMessage().' on '.$this->sql : 0); }
Displays the error massage which occurs @param \Exception $error This should be an instance of Exception
entailment
public function writeQueryToLog() { $file = $this->logLocation.'queries.txt'; $current = file_get_contents($file); $current .= "SQL: ".$this->sql.":".serialize($this->values)."\n"; file_put_contents($file, $current); }
Writes all queries to a log file
entailment
protected function buildSelectQuery($table, $where = array(), $fields = '*', $order = array(), $limit = 0) { if(is_array($fields)) { $selectfields = array(); foreach($fields as $field => $value) { $selectfields[] = sprintf("`%s`", SafeString::makeSafe($value)); } $fieldList = implode(', ', $selectfields); } else{$fieldList = '*';} $this->sql = sprintf("SELECT %s FROM `%s`%s%s%s;", $fieldList, SafeString::makeSafe($table), $this->where($where), $this->orderBy($order), $this->limit($limit)); $this->key = md5($this->database.$this->sql.serialize($this->values)); }
Build the SQL query but doesn't execute it @param string $table This should be the table you wish to select the values from @param array $where Should be the field names and values you wish to use as the where query e.g. array('fieldname' => 'value', 'fieldname2' => 'value2', etc). @param string|array $fields This should be the records you wis to select from the table. It should be either set as '*' which is the default or set as an array in the following format array('field', 'field2', 'field3', etc). @param array $order This is the order you wish the results to be ordered in should be formatted as follows array('fieldname' => 'ASC') or array("'fieldname', 'fieldname2'" => 'DESC') so it can be done in both directions @param integer|array $limit The number of results you want to return 0 is default and returns all results, else should be formated either as a standard integer or as an array as the start and end values e.g. array(0 => 150)
entailment
protected function executeQuery($cache = true) { if($this->logQueries) {$this->writeQueryToLog();} if($cache && $this->cacheEnabled && $this->getCache($this->key)) { return $this->cacheValue; } try{ $this->query = $this->db->prepare($this->sql); $this->bindValues($this->values); $this->query->execute(); unset($this->values); $this->values = []; } catch(\Exception $e) { unset($this->values); $this->values = []; $this->error($e); } }
Execute the current query if no cache value is available @param boolean $cache If the cache should be checked for the checked for the values of the query set to true else set to false @return mixed If a cached value exists will be returned else if cache is not checked and query is executed will not return anything
entailment