sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function generateSignature()
{
$signature = $this->getMerchantPassword();
$signature .= $this->getMerchantId();
$signature .= $this->getAcquirerId();
$signature .= $this->getTransactionId();
$signature .= $this->formatAmount();
$signature .= $this->getCurrencyNumeric();
return base64_encode( sha1($signature, true) );
} | Returns the signature for the request.
@return string base64 encoded sha1 hash of the merchantPassword, merchantId,
acquirerId, transactionId, amount and currency code. | entailment |
public function getData()
{
$this->validate('merchantId', 'merchantPassword', 'acquirerId', 'transactionId', 'amount', 'currency', 'card');
// Check for AVS and require billingAddress1 and billingPostcode
if ( $this->getRequireAvsCheck() )
{
$this->getCard()->validate('billingAddress1', 'billingPostcode');
}
// Tokenized cards require the CVV and nothing else, token replaces the card number
if ( $this->getCardReference() )
{
$this->validate('cardReference');
$this->getCard()->validate('cvv', 'expiryMonth', 'expiryYear');
$cardDetails = [
'CardCVV2' => $this->getCard()->getCvv(),
'CardExpiryDate' => $this->getCard()->getExpiryDate('my'),
'CardNumber' => $this->getCardReference()
];
}
else
{
$this->getCard()->validate();
$cardDetails = [
'CardCVV2' => $this->getCard()->getCvv(),
'CardExpiryDate' => $this->getCard()->getExpiryDate('my'),
'CardNumber' => $this->getCard()->getNumber(),
'IssueNumber' => $this->getCard()->getIssueNumber()
];
}
// Only pass the StartDate if year/month are set otherwise it returns 1299
if ( $this->getCard()->getStartYear() && $this->getCard()->getStartMonth() )
{
$cardDetails['StartDate'] = $this->getCard()->getStartDate('my');
}
$transactionDetails = [
'AcquirerId' => $this->getAcquirerId(),
'Amount' => $this->formatAmount(),
'Currency' => $this->getCurrencyNumeric(),
'CurrencyExponent' => $this->getCurrencyDecimalPlaces(),
'IPAddress' => $this->getClientIp(),
'MerchantId' => $this->getMerchantId(),
'OrderNumber' => $this->getTransactionId(),
'Signature' => $this->generateSignature(),
'SignatureMethod' => 'SHA1',
'TransactionCode' => $this->getTransactionCode()
];
$billingDetails = [
'BillToAddress' => $this->getCard()->getAddress1(),
'BillToZipPostCode' => $this->getCard()->formatPostcode(),
'BillToFirstName' => $this->getCard()->getFirstName(),
'BillToLastName' => $this->getCard()->getLastName(),
'BillToCity' => $this->getCard()->getCity(),
'BillToCountry' => $this->getCard()->getNumericCountry(),
'BillToEmail' => $this->getCard()->getEmail(),
'BillToTelephone' => $this->getCard()->getPhone(),
'BillToFax' => $this->getCard()->getFax()
];
// FAC only accepts two digit state abbreviations from the USA
if ( $billingDetails['BillToCountry'] == 840 )
{
$billingDetails['BillToState'] = $this->getCard()->validateState();
}
$data = [
'TransactionDetails' => $transactionDetails,
'CardDetails' => $cardDetails,
'BillingDetails' => $billingDetails
];
return $data;
} | Validate and construct the data for the request
@return array | entailment |
protected function getTransactionCode()
{
$transactionCode = $this->transactionCode;
if($this->getRequireAvsCheck()) {
$transactionCode += 1;
}
if($this->getCreateCard()) {
$transactionCode += 128;
}
return $transactionCode;
} | Returns the transaction code based on the AVS check requirement
@return int Transaction Code | entailment |
public function validate()
{
$parameters = func_get_args();
if ( count($parameters) == 0 )
{
$parameters = ['number', 'cvv', 'expiryMonth', 'expiryYear'];
}
foreach ($parameters as $key)
{
$value = $this->parameters->get($key);
if ( empty($value) )
{
throw new InvalidCreditCardException("The $key parameter is required");
}
}
if ( isset($parameters['expiryMonth']) && isset($parameters['expiryYear']) )
{
if ( $this->getExpiryDate('Ym') < gmdate('Ym') )
{
throw new InvalidCreditCardException('Card has expired');
}
}
if ( isset($parameters['number']) )
{
if ( !Helper::validateLuhn( $this->getNumber() ) )
{
throw new InvalidCreditCardException('Card number is invalid');
}
if ( !is_null( $this->getNumber() ) && !preg_match( '/^\d{12,19}$/i', $this->getNumber() ) )
{
throw new InvalidCreditCardException('Card number should have 12 to 19 digits');
}
}
if ( isset($parameters['cvv']) )
{
if ( !is_null( $this->getCvv() ) && !preg_match( '/^\d{3,4}$/i', $this->getCvv() ) )
{
throw new InvalidCreditCardException('Card CVV should have 3 to 4 digits');
}
}
} | Validate this credit card. If the card is invalid, InvalidCreditCardException is thrown.
This method is called internally by gateways to avoid wasting time with an API call
when the credit card is clearly invalid.
Falls back to validating number, cvv, expiryMonth, expiryYear if no parameters are present.
@param string ... Optional variable length list of required parameters
@throws InvalidCreditCardException | entailment |
public function getNumericCountry()
{
$country = $this->getCountry();
if ( !is_null($country) && !is_numeric($country) )
{
$iso3166 = new ISO3166();
if ( strlen($country) == 2 )
{
$country = $iso3166->getByAlpha2($country)['numeric'];
}
elseif ( strlen($country) == 3 )
{
$country = $iso3166->getByAlpha3($country)['numeric'];
}
else
{
throw new InvalidRequestException("The country parameter must be ISO 3166-1 numeric, aplha2 or alpha3.");
}
}
return $country;
} | Returns the country as the numeric ISO 3166-1 code
@throws InvalidRequestException
@return int ISO 3166-1 numeric country | entailment |
public function requireCheck($requiredCheck)
{
if (!$this->checkRepository->has($requiredCheck)) {
throw new InvalidArgumentException(sprintf('Check: "%s" does not exist', $requiredCheck));
}
$check = $this->checkRepository->getByClass($requiredCheck);
if ($check instanceof SimpleCheckInterface) {
switch ($check->getPosition()) {
case SimpleCheckInterface::CHECK_BEFORE:
$this->checksToRunBefore[] = $check;
break;
case SimpleCheckInterface::CHECK_AFTER:
$this->checksToRunAfter[] = $check;
break;
default:
throw InvalidArgumentException::notValidParameter(
'position',
[SimpleCheckInterface::CHECK_BEFORE, SimpleCheckInterface::CHECK_AFTER],
$check->getPosition()
);
}
return;
}
if (!$check instanceof ListenableCheckInterface) {
throw new InvalidArgumentException(sprintf('Check: "%s" is not a listenable check', $requiredCheck));
}
$check->attach($this->eventDispatcher);
} | Queue a specific check to be run when the exercise is verified. When the exercise is verified
the check specified as the first argument will also be executed. Throws an `InvalidArgumentException`
if the check does not exist in the `CheckRepository`.
@param string $requiredCheck The name of the required check.
@throws InvalidArgumentException If the check does not exist. | entailment |
public function verify(ExerciseInterface $exercise, Input $input)
{
$exercise->configure($this);
$runner = $this->runnerManager->getRunner($exercise);
foreach ($runner->getRequiredChecks() as $requiredCheck) {
$this->requireCheck($requiredCheck);
}
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('verify.start', $exercise, $input));
$this->validateChecks($this->checksToRunBefore, $exercise);
$this->validateChecks($this->checksToRunAfter, $exercise);
foreach ($this->checksToRunBefore as $check) {
$this->results->add($check->check($exercise, $input));
if (!$this->results->isSuccessful()) {
return $this->results;
}
}
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('verify.pre.execute', $exercise, $input));
try {
$this->results->add($runner->verify($input));
} finally {
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('verify.post.execute', $exercise, $input));
}
foreach ($this->checksToRunAfter as $check) {
$this->results->add($check->check($exercise, $input));
}
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('verify.post.check', $exercise, $input));
$exercise->tearDown();
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('verify.finish', $exercise, $input));
return $this->results;
} | Verify a students solution against a specific exercise. Runs queued checks based on their position. Invokes the
correct runner for the exercise based on the exercise type. Various events are triggered throughout the process.
@param ExerciseInterface $exercise The exercise instance.
@param Input $input The command line arguments passed to the command.
@return ResultAggregator Contains all the results injected via the runner, checks and events.
@throws CheckNotApplicableException If the check is not applicable to the exercise type.
@throws ExerciseNotConfiguredException If the exercise does not implement the correct interface based on
the checks required. | entailment |
public function run(ExerciseInterface $exercise, Input $input, OutputInterface $output)
{
$exercise->configure($this);
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('run.start', $exercise, $input));
try {
$exitStatus = $this->runnerManager
->getRunner($exercise)
->run($input, $output);
} finally {
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('run.finish', $exercise, $input));
}
return $exitStatus;
} | Run a student's solution against a specific exercise. Does not invoke checks. Invokes the
correct runner for the exercise based on the exercise type. Various events are triggered throughout the process.
The output of the solution is written directly to the `OutputInterface` instance.
@param ExerciseInterface $exercise The exercise instance.
@param Input $input The command line arguments passed to the command.
@param OutputInterface $output An output instance capable of writing to stdout.
@return bool Whether the solution ran successfully or not. | entailment |
public function request(callable $fn, array $arguments = [])
{
$result = call_user_func_array($fn, $arguments);
if ($result instanceof MatcherInterface) {
return $this->assert($result);
}
return $result;
} | A request to an Assertion will attempt to resolve
the result as an assertion before returning the result.
@param callable $fn
@return mixed | entailment |
public function extend($fn)
{
if (is_string($fn) && file_exists($fn)) {
$fn = include $fn;
}
if (is_callable($fn)) {
return call_user_func($fn, $this);
}
throw new \InvalidArgumentException('Assertion::extend requires a callable or a file that returns one');
} | Extend calls the given callable - or file that returns a callable - and passes the current Assertion instance
to it. Assertion can be extended via the ->addMethod(), ->flag(), and ->addProperty()
methods.
@param callable $fn | entailment |
public function assert(MatcherInterface $matcher)
{
if ($this->flag('not')) {
$matcher->invert();
}
$match = $matcher
->setAssertion($this)
->match($this->getActual());
$message = $this->flag('message');
$this->clearFlags();
$this->responder->respond($match, $matcher->getTemplate(), $message);
return $this;
} | Assert against the given matcher.
@param $result
@return $this | entailment |
public function getImageCode($appKey) {
try{
if (empty($appKey))
throw new Exception('Paramer "appKey" is required');
$params = array (
'appKey' => $appKey
);
$ret = $this->SendRequest->curl('/getImgCode.json',$params,'urlencoded','sms','GET');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 获取图片验证码方法
@param appKey:应用Id
@return $json | entailment |
public function sendCode($mobile, $templateId, $region, $verifyId = '', $verifyCode = '') {
try{
if (empty($mobile))
throw new Exception('Paramer "mobile" is required');
if (empty($templateId))
throw new Exception('Paramer "templateId" is required');
if (empty($region))
throw new Exception('Paramer "region" is required');
$params = array (
'mobile' => $mobile,
'templateId' => $templateId,
'region' => $region,
'verifyId' => $verifyId,
'verifyCode' => $verifyCode
);
$ret = $this->SendRequest->curl('/sendCode.json',$params,'urlencoded','sms','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 发送短信验证码方法。
@param mobile:接收短信验证码的目标手机号,每分钟同一手机号只能发送一次短信验证码,同一手机号 1 小时内最多发送 3 次。(必传)
@param templateId:短信模板 Id,在开发者后台->短信服务->服务设置->短信模版中获取。(必传)
@param region:手机号码所属国家区号,目前只支持中图区号 86)
@param verifyId:图片验证标识 Id ,开启图片验证功能后此参数必传,否则可以不传。在获取图片验证码方法返回值中获取。
@param verifyCode:图片验证码,开启图片验证功能后此参数必传,否则可以不传。
@return $json | entailment |
public function verifyCode($sessionId, $code) {
try{
if (empty($sessionId))
throw new Exception('Paramer "sessionId" is required');
if (empty($code))
throw new Exception('Paramer "code" is required');
$params = array (
'sessionId' => $sessionId,
'code' => $code
);
$ret = $this->SendRequest->curl('/verifyCode.json',$params,'urlencoded','sms','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 验证码验证方法
@param sessionId:短信验证码唯一标识,在发送短信验证码方法,返回值中获取。(必传)
@param code:短信验证码内容。(必传)
@return $json | entailment |
public function serialize(UserState $state)
{
$saveFile = sprintf('%s/%s', $this->path, static::SAVE_FILE);
$data = file_exists($saveFile)
? $this->readJson($saveFile)
: [];
$data[$this->workshopName] = [
'completed_exercises' => $state->getCompletedExercises(),
'current_exercise' => $state->getCurrentExercise(),
];
return file_put_contents($saveFile, json_encode($data));
} | Save the students state for this workshop to disk.
@param UserState $state
@return int | entailment |
public function deSerialize()
{
$legacySaveFile = sprintf('%s/%s', $this->path, static::LEGACY_SAVE_FILE);
if (file_exists($legacySaveFile)) {
$userState = $this->migrateData($legacySaveFile);
if ($userState instanceof UserState) {
return $userState;
}
}
$json = $this->readJson(sprintf('%s/%s', $this->path, static::SAVE_FILE));
if (null === $json) {
$this->wipeFile();
return new UserState();
}
if (!isset($json[$this->workshopName])) {
return new UserState();
}
$json = $json[$this->workshopName];
if (!array_key_exists('completed_exercises', $json)) {
return new UserState();
}
if (!array_key_exists('current_exercise', $json)) {
return new UserState();
}
if (!is_array($json['completed_exercises'])) {
$json['completed_exercises'] = [];
}
foreach ($json['completed_exercises'] as $i => $exercise) {
if (!is_string($exercise)) {
unset($json['completed_exercises'][$i]);
}
}
if (null !== $json['current_exercise'] && !is_string($json['current_exercise'])) {
$json['current_exercise'] = null;
}
return new UserState(
$json['completed_exercises'],
$json['current_exercise']
);
} | Read a students state for this workshop from the disk.
@return UserState | entailment |
private function migrateData($legacySaveFile)
{
$data = $this->readJson($legacySaveFile);
if (null === $data) {
unlink($legacySaveFile);
return null;
}
//lets check if the data is in the old format
if (!isset($data['completed_exercises']) || !isset($data['current_exercise'])) {
unlink($legacySaveFile);
return null;
}
$completedExercises = $data['completed_exercises'];
$availableExercises = $this->exerciseRepository->getAllNames();
//check to see if this old data represents THIS workshop
//if not we bail
foreach ($completedExercises as $completedExercise) {
if (!in_array($completedExercise, $availableExercises)) {
return null;
}
}
$userState = new UserState($data['completed_exercises'], $data['current_exercise']);
$this->serialize($userState);
unlink($legacySaveFile);
return $userState;
} | On early versions of the workshop the save data was not namespaced
and therefore it was impossible to have data for more than one workshop
at the same time. Therefore we must try to migrate that data in to the new namespaced
format in order to preserve users save data.
We can only migrate data when using the workshop the data was originally saved from.
@param string $legacySaveFile
@return null|UserState | entailment |
protected function doMatch($actual)
{
if (!is_string($actual)) {
throw new \InvalidArgumentException('SubStringMatcher requires string value');
}
return strpos($actual, $this->expected) !== false;
} | Match that actual value has the expected sub string.
@param string $actual
@return mixed | entailment |
public function getMessage()
{
return isset($this->data['ErrorMsg']) && !empty($this->data['ErrorMsg']) ? $this->data['ErrorMsg'] : null;
} | Return the response's reason message
@return string | entailment |
public function getTemplate()
{
if ($this->expectedMessage) {
return $this->getMessageTemplate();
}
if (!isset($this->template)) {
return $this->getDefaultTemplate();
}
return $this->template;
} | {@inheritdoc}
If the expected message has been set, the message template will be used.
@return TemplateInterface | entailment |
public function match($actual)
{
$this->validateCallable($actual);
list($exception, $message) = $this->callableException($actual);
$this->setMessage($message);
return $this->matchMessage($actual, $exception, $message);
} | Executes the callable and matches the exception type and exception message.
@param $actual
@return Match | entailment |
public function set($key, $value)
{
return $this->memcache->set($key, $value, 0, $this->lifetime);
} | adds a cache key for a specific lifetime into the cache
@param string $key
@param mixed $value
@return bool | entailment |
public function isSuccessful()
{
return count(
array_filter($this->results, function ($result) {
if ($result instanceof ResultGroupInterface) {
return !$result->isSuccessful();
}
return $result instanceof FailureInterface;
})
) === 0;
} | Computes whether the results are considered a success. If there are any results which implement
`FailureInterface` then the combined result is considered as a fail.
@return bool | entailment |
public function loadPluginConfiguration(): void
{
$builder = $this->getContainerBuilder();
$global = $this->compiler->getExtension()->getConfig();
$config = $this->getConfig();
if ($config['tracy'] === true) {
$builder->addDefinition($this->prefix('tracy'))
->setFactory(TracyMiddleware::class . '::factory', [$global['debug']])
->addTag(MiddlewaresExtension::MIDDLEWARE_TAG, ['priority' => 100]);
}
if ($config['autobasepath'] === true) {
$builder->addDefinition($this->prefix('autobasepath'))
->setFactory(AutoBasePathMiddleware::class)
->addTag(MiddlewaresExtension::MIDDLEWARE_TAG, ['priority' => 200]);
}
$builder->addDefinition($this->prefix('api'))
->setFactory(ApiMiddleware::class)
->addTag(MiddlewaresExtension::MIDDLEWARE_TAG, ['priority' => 500]);
} | Register services (middlewares wrappers) | entailment |
public function getCount()
{
if (is_string($this->countable)) {
return strlen($this->countable);
}
return count($this->countable);
} | Get the count of the countable value.
@return int | entailment |
protected function doMatch($actual = null)
{
if (isset($this->countable)) {
$actual = $this->getCount();
}
if (!is_numeric($actual)) {
throw new \InvalidArgumentException(get_class($this) . ' requires a numeric value');
}
return $this->matchNumeric($actual);
} | {@inheritdoc}
@param $actual
@return mixed | entailment |
protected function map($mapping, \SimpleXMLElement $xml, $objekt)
{
foreach ($mapping as $key) {
if (isset($xml->$key)) {
$setter = $this->mapper->getSetter($key);
$objekt->$setter($this->cast($xml->$key, $this->mapper->getType($key)));
}
}
} | maps an mapping array between a SimpleXML and Objekt
@param $mapping
@param \SimpleXMLElement $xml
@param $objekt | entailment |
protected function cast(\SimpleXMLElement $xml, $type = 'string')
{
switch ($type) {
case 'string':
return (string) $xml;
case 'int':
return (int) $xml;
case 'double':
return (double) $xml;
case 'boolean' :
return (bool) ((string) $xml);
case 'datetime':
$date = (string) $xml;
if (empty($date)) {
return null;
}
return new \DateTime($date);
default:
return $xml;
}
} | casts a simple xml element to a type
@param $xml
@param string $type
@return float|int|null|string|\DateTime | entailment |
protected function mapAttachmentGroup(\SimpleXMLElement $xml, $attachmentAware, $type = null, $forceGroup = null)
{
foreach ($xml as $anhang) {
$data = (array) $anhang->daten;
$attributes = $this->attributesToArray($anhang);
$group = $forceGroup ?: (array_key_exists('gruppe', $attributes) ? $attributes['gruppe'] : null);
if (array_key_exists('pfad', $data)) {
$attachment = new Attachment($data['pfad'], $type, $group);
$attachment->mergeData($data);
if (isset($anhang->vorschaubild)) {
$attachment->mergeData(array('vorschaubild' => $this->cast($anhang->vorschaubild)));
}
$attachment->setTitle($this->cast($anhang->anhangtitel));
$attachment->setOriginalFilename($this->cast($anhang->original_dateiname));
$attachmentAware->addAttachment($attachment);
} elseif (isset($anhang->pfad)) {
if (isset($anhang->gruppe)) {
$group = strtoupper($this->cast($anhang->gruppe));
}
$attachment = new Attachment($this->cast($anhang->pfad), $type, $group);
if (isset($anhang->vorschaubild)) {
$attachment->mergeData(array('vorschaubild' => $this->cast($anhang->vorschaubild)));
}
$attachment->setTitle($this->cast($anhang->titel));
$attachment->setOriginalFilename($this->cast($anhang->original_dateiname));
$attachmentAware->addAttachment($attachment);
}
}
} | @param \SimpleXMLElement $xml
@param \Justimmo\Model\Realty|\Justimmo\Model\Employee|\Justimmo\Model\Project $attachmentAware
@param null $type
@param null $forceGroup
@internal param array $data | entailment |
public function check(ExerciseInterface $exercise, Input $input)
{
$code = file_get_contents($input->getArgument('program'));
try {
$this->parser->parse($code);
} catch (Error $e) {
return Failure::fromCheckAndCodeParseFailure($this, $e, $input->getArgument('program'));
}
return Success::fromCheck($this);
} | This check grabs the contents of the student's solution and
attempts to parse it with `nikic/php-parser`. If any exceptions are thrown
by the parser, it is treated as a failure.
@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 canRun(ExerciseType $exerciseType)
{
return in_array($exerciseType->getValue(), [ExerciseType::CGI, ExerciseType::CLI]);
} | This check can run on any exercise type.
@param ExerciseType $exerciseType
@return bool | entailment |
private function createHttpHeader() {
$nonce = mt_rand();
$timeStamp = time();
$sign = sha1($this->appSecret.$nonce.$timeStamp);
return array(
'RC-App-Key:'.$this->appKey,
'RC-Nonce:'.$nonce,
'RC-Timestamp:'.$timeStamp,
'RC-Signature:'.$sign,
);
} | 创建http header参数
@param array $data
@return bool | entailment |
public function render(ResultsRenderer $renderer)
{
return sprintf(
" %s\n%s\n\n %s\n%s\n",
$renderer->style('YOUR OUTPUT:', ['bold', 'yellow']),
$this->indent($renderer->style(sprintf('"%s"', $this->result->getActualOutput()), 'red')),
$renderer->style('EXPECTED OUTPUT:', ['bold', 'yellow']),
$this->indent($renderer->style(sprintf('"%s"', $this->result->getExpectedOutput()), 'green'))
);
} | Print the actual and expected output.
@param ResultsRenderer $renderer
@return string | entailment |
public function getMessage(TemplateInterface $template)
{
$vars = $this->getTemplateVars($template);
$tpl = $this->match->isNegated()
? $template->getNegatedTemplate()
: $template->getDefaultTemplate();
foreach ($vars as $name => $value) {
$tpl = str_replace('{{' . $name . '}}', $this->objectToString($value), $tpl);
}
return $tpl;
} | {@inheritdoc}
@param TemplateInterface $template
@return mixed|string | entailment |
public function objectToString($obj)
{
switch (gettype($obj)) {
case 'boolean':
return var_export($obj, true);
case 'NULL':
return 'null';
case 'string':
return '"' . $obj . '"';
}
return rtrim(print_r($obj, true));
} | {@inheritdoc}
@param mixed $obj
@return string | entailment |
protected function getTemplateVars(TemplateInterface $template)
{
$vars = [
'expected' => $this->match->getExpected(),
'actual' => $this->match->getActual(),
];
if ($tplVars = $template->getTemplateVars()) {
$vars = array_merge($vars, $tplVars);
}
return $vars;
} | Applies match results to other template variables.
@param TemplateInterface $template
@return array | entailment |
public function getParameter($name)
{
if (!array_key_exists($name, $this->parameters)) {
throw new InvalidArgumentException(sprintf('Parameter: "%s" does not exist', $name));
}
return $this->parameters[$name];
} | Get a parameter by it's name.
@param string $name The name of the parameter.
@return mixed The value.
@throws InvalidArgumentException If the parameter by name does not exist. | entailment |
public static function fromCheckAndExercise(CheckInterface $check, ExerciseInterface $exercise)
{
return new static(
sprintf(
'Check: "%s" cannot process exercise: "%s" with type: "%s"',
$check->getName(),
$exercise->getName(),
$exercise->getType()
)
);
} | Static constructor to create an instance from the check & exercise.
@param CheckInterface $check The check Instance.
@param ExerciseInterface $exercise The exercise Instance.
@return static | entailment |
public function setUserPushTag($userTag) {
try{
if (empty($userTag))
throw new Exception('Paramer "userTag" is required');
$params = json_decode($userTag,TRUE);
$ret = $this->SendRequest->curl('/user/tag/set.json',$params,'json','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 添加 Push 标签方法
@param userTag:用户标签。
@return $json | entailment |
public function broadcastPush($pushMessage) {
try{
if (empty($pushMessage))
throw new Exception('Paramer "pushMessage" is required');
$params = json_decode($pushMessage,TRUE);
$ret = $this->SendRequest->curl('/push.json',$params,'json','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 广播消息方法(fromuserid 和 message为null即为不落地的push)
@param pushMessage:json数据
@return $json | entailment |
public function delete($word) {
try{
if (empty($word))
throw new Exception('Paramer "word" is required');
$params = array (
'word' => $word
);
$ret = $this->SendRequest->curl('/wordfilter/delete.json',$params,'urlencoded','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 移除敏感词方法(从敏感词列表中,移除某一敏感词。)
@param word:敏感词,最长不超过 32 个字符。(必传)
@return $json | entailment |
public function patch(ExerciseInterface $exercise, $code)
{
if (null !== $this->defaultPatch) {
$code = $this->applyPatch($this->defaultPatch, $code);
}
if ($exercise instanceof SubmissionPatchable) {
$code = $this->applyPatch($exercise->getPatch(), $code);
}
return $code;
} | Accepts an exercise and a string containing the students solution to the exercise.
If there is a default patch, the students solution is patched with that.
If the exercise implements `SubmissionPatchable` then the patch is pulled from it and applied to
the students solution.
@param ExerciseInterface $exercise
@param string $code
@return string | entailment |
public function setCapture($capture)
{
switch ($capture) {
case 'c':
$this->capture = 'c';
break;
case 'a':
$this->capture = 'a';
break;
default:
$this->capture = 'p';
break;
}
return $this;
} | @param string $capture
@return self | entailment |
public function check(ExerciseInterface $exercise, Input $input)
{
if (!$exercise instanceof FunctionRequirementsExerciseCheck) {
throw new \InvalidArgumentException;
}
$requiredFunctions = $exercise->getRequiredFunctions();
$bannedFunctions = $exercise->getBannedFunctions();
$code = file_get_contents($input->getArgument('program'));
try {
$ast = $this->parser->parse($code);
} catch (Error $e) {
return Failure::fromCheckAndCodeParseFailure($this, $e, $input->getArgument('program'));
}
$visitor = new FunctionVisitor($requiredFunctions, $bannedFunctions);
$traverser = new NodeTraverser;
$traverser->addVisitor($visitor);
$traverser->traverse($ast);
$bannedFunctions = [];
if ($visitor->hasUsedBannedFunctions()) {
$bannedFunctions = array_map(function (FuncCall $node) {
return ['function' => $node->name->__toString(), 'line' => $node->getLine()];
}, $visitor->getBannedUsages());
}
$missingFunctions = [];
if (!$visitor->hasMetFunctionRequirements()) {
$missingFunctions = $visitor->getMissingRequirements();
}
if (!empty($bannedFunctions) || !empty($missingFunctions)) {
return new FunctionRequirementsFailure($this, $bannedFunctions, $missingFunctions);
}
return Success::fromCheck($this);
} | Parse the students solution and check that there are usages of
required functions and that banned functions are not used. The requirements
are pulled from the exercise.
@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 |
private function createDocumentFieldsTables(): void
{
// Text types
$this->createDocumentFieldsTable(Types::TEXT, 'text');
$this->createDocumentFieldsTable(Types::KEYWORD, 'text');
// Numeric types
$this->createDocumentFieldsTable(TYPES::FLOAT, 'float');
$this->createDocumentFieldsTable(TYPES::INTEGER, 'bigint');
// Date types
$this->createDocumentFieldsTable(Types::DATE, 'datetime');
// Boolean types
$this->createDocumentFieldsTable(Types::BOOLEAN, 'boolean');
} | Create table per mapping type.
@see https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html | entailment |
protected function getData(): array
{
if ($this->dataFile === false || $this->dataFile === null) {
return [];
}
$dataFile = $this->resolveDataFilePath();
if (is_file($dataFile)) {
return require($dataFile);
} else {
throw new InvalidConfigException("Fixture data file does not exist: {$this->dataFile}");
}
} | Returns the fixture data.
The default implementation will try to return the fixture data by including the external file specified by [[dataFile]].
The file should return the data array that will be stored in [[data]] after inserting into the database.
@throws InvalidConfigException if the specified data file does not exist
@return array the data to be put into the database | entailment |
private function _compareMac($a, $b) {
$result = "\x00";
for ($i = 0; $i < $this->_macByteCount; $i++) {
$result |= substr($a, $i, 1) ^ substr($b, $i, 1);
}
/* \x00 if equal, nonzero otherwise */
return ($result === "\x00");
} | Constant-time comparison function
Stolen and adapted from:
https://cryptocoding.net/index.php/Coding_rules#Compare_secret_strings_in_constant_time
DON'T MESS WITH THIS FUNCTION
returns boolean true on match, otherwise, false | entailment |
public function run(Input $input, OutputInterface $output)
{
$message = 'Nothing to run here. This exercise does not require a code solution, ';
$message .= 'so there is nothing to execute.';
$output->writeLine($message);
return true;
} | Running a custom verifying exercise does nothing. There is no program required, therefore there is nothing
to run.
@param Input $input The command line arguments passed to the command.
@param OutputInterface $output A wrapper around STDOUT.
@return bool If the solution was successfully executed, eg. exit code was 0. | entailment |
public function connect($host, $port, $persistent = false){
$this->addServer($host, $port, $persistent);
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 string|boolean This should be the id of any persistent connection or set to false if it should not be persistent
@return $this | entailment |
public function addServer($host, $port, $persistent = false){
$this->cache = new \Memcached($persistent);
$this->cache->addServer($host, intval($port));
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 string|boolean This should be the id of any persistent connection or set to false if it should not be persistent
@return $this | entailment |
public function save($key, $value, $time = 0){
return $this->cache->set($key, $value, intval($time));
} | Adds a value to be stored on the server
@param string $key This should be the key for the value you wish to add
@param mixed $value The value you wish to be stored with the given key
@param int $time How long should the value be stored for in seconds (0 = never expire) (max set value = 2592000 (30 Days))
@return boolean Returns true if successfully added or false on failure | entailment |
public function replace($key, $value, $time = 0){
return $this->cache->replace($key, $value, intval($time));
} | Replaces a stored value for a given key
@param string $key This should be the key for the value you wish to replace
@param mixed $value The new value that you wish to give to that key
@param int $time How long should the value be stored for in seconds (0 = never expire) (max set value = 2592000 (30 Days))
@return boolean Returns true if successfully replaced or false on failure | entailment |
public function prependArg($arg)
{
Assertion::string($arg);
$this->args = $this->args->prepend($arg);
} | Prepend an argument to the list of arguments to be passed to the program.
@param string $arg | entailment |
public function appendArg($arg)
{
Assertion::string($arg);
$this->args = $this->args->append($arg);
} | Append an argument to the list of arguments to be passed to the program.
@param string $arg | entailment |
public function typeOf($actual, $expected, $message = '')
{
$this->assertion->setActual($actual);
return $this->assertion->to->be->a($expected, $message);
} | Performs a type assertion.
@param mixed $actual
@param string $expected
@param string $message | entailment |
public function notTypeOf($actual, $expected, $message = '')
{
$this->assertion->setActual($actual);
return $this->assertion->to->not->be->a($expected, $message);
} | Performs a negated type assertion.
@param mixed $actual
@param string $expected
@param string $message | entailment |
public function isTrue($value, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->be->true($message);
} | Perform a true assertion.
@param mixed $value
@param string $message | entailment |
public function isFalse($value, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->be->false($message);
} | Perform a false assertion.
@param mixed $value
@param string $message | entailment |
public function isNull($value, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->be->null($message);
} | Perform a null assertion.
@param mixed $value
@param string $message | entailment |
public function isNotNull($value, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->not->be->null($message);
} | Perform a negated null assertion.
@param mixed $value
@param string $message | entailment |
public function isCallable($value, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->satisfy('is_callable', $message);
} | Performs a predicate assertion to check if actual
value is callable.
@param mixed $value
@param string $message | entailment |
public function isNotCallable($value, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->not->satisfy('is_callable', $message);
} | Performs a negated predicate assertion to check if actual
value is not a callable.
@param mixed $value
@param string $message | entailment |
public function isNumeric($value, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->satisfy('is_numeric', $message);
} | Performs a predicate assertion to check if actual
value is numeric.
@param mixed $value
@param string $message | entailment |
public function render(ResultsRenderer $renderer)
{
return sprintf(
" %s\n%s\n\n %s\n%s\n",
$renderer->style('YOUR OUTPUT:', ['bold', 'yellow']),
$this->indent($renderer->style(sprintf('"%s"', $this->result->getActualValue()), 'red')),
$renderer->style('EXPECTED OUTPUT:', ['bold', 'yellow']),
$this->indent($renderer->style(sprintf('"%s"', $this->result->getExpectedValue()), 'green'))
);
} | Print the actual and expected output.
@param ResultsRenderer $renderer
@return string | entailment |
private function getElements(array $queries, StorageInterface $storage)
{
$elements = [];
foreach ($queries as $query) {
$elements[] = $this->getInterpreter($query)->visit($query, $storage);
}
return $elements;
} | Interprets given queries into elements.
@param QueryInterface[] $queries
@param StorageInterface $storage
@return ElementInterface[] | entailment |
public function match($actual = '')
{
$isMatch = $this->doMatch($actual);
$isNegated = $this->isNegated();
return new Match($isMatch xor $isNegated, $this->expected, $actual, $isNegated);
} | {@inheritdoc}
@param mixed $actual
@return Match | entailment |
public static function typeMisMatch($expected, $actual)
{
return new static(
sprintf(
'Expected: "%s" Received: "%s"',
$expected,
is_object($actual) ? get_class($actual) : gettype($actual)
)
);
} | Static constructor to create from the expected type & the actual value.
@param string $expected
@param mixed $actual
@return static | entailment |
public static function notValidParameter($parameterName, array $allowedValues, $actualValue)
{
return new static(
sprintf(
'Parameter: "%s" can only be one of: "%s" Received: "%s"',
$parameterName,
static::stringify($allowedValues),
static::stringify($actualValue)
)
);
} | Static constructor to create from when a parameter should be one of a set of allowed values, but was not.
@param string $parameterName
@param mixed[] $allowedValues
@param mixed $actualValue
@return static | entailment |
public function request($function_name, array $arguments = [], array $options = null, $input_headers = null)
{
return $this->soap->request($function_name, $arguments, $options, $input_headers);
} | Interpret the given method and arguments to a SOAP request message.
@param string $function_name The name of the SOAP function to interpret.
@param array $arguments An array of the arguments to $function_name.
@param array $options An associative array of options.
The location option is the URL of the remote Web service.
The uri option is the target namespace of the SOAP service.
The soapaction option is the action to call.
@param mixed $input_headers An array of headers to be interpreted along with the SOAP request.
@return SoapRequest | entailment |
public function response($response, $function_name, array &$output_headers = null)
{
return $this->soap->response($response, $function_name, $output_headers);
} | Interpret a SOAP response message to PHP values.
@param string $response The SOAP response message.
@param string $function_name The name of the SOAP function to interpret.
@param array $output_headers If supplied, this array will be filled with the headers from the SOAP response.
@return mixed
@throws \SoapFault | entailment |
protected function deleteModels(): void
{
$model = app($this->modelClass);
// determine if the model uses `SoftDeletes` trait
$usesSoftDeletes = in_array(SoftDeletes::class, class_uses($model));
foreach ($model->all() as $value) {
try {
if ($usesSoftDeletes) {
$value->forceDelete();
} else {
$value->delete();
}
} catch (Exception $exception) {
Log::warning(sprintf('Error during deleting models. Table: %s. Error: %s', $model->getTable(), $exception->getMessage()));
}
}
} | Removes all existing models.
@throws Exception | entailment |
public function setResponse($response)
{
$xml = simplexml_load_string($response);
if (!empty($xml->error)) {
$this->message = (string) $xml->error;
}
} | set exception message from response
@param string $response | entailment |
public function getToken($userId, $name, $portraitUri) {
try{
if (empty($userId))
throw new Exception('Paramer "userId" is required');
if (empty($name))
throw new Exception('Paramer "name" is required');
if (empty($portraitUri))
throw new Exception('Paramer "portraitUri" is required');
$params = array (
'userId' => $userId,
'name' => $name,
'portraitUri' => $portraitUri
);
$ret = $this->SendRequest->curl('/user/getToken.json',$params,'urlencoded','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 获取 Token 方法
@param userId:用户 Id,最大长度 64 字节.是用户在 App 中的唯一标识码,必须保证在同一个 App 内不重复,重复的用户 Id 将被当作是同一用户。(必传)
@param name:用户名称,最大长度 128 字节.用来在 Push 推送时显示用户的名称.用户名称,最大长度 128 字节.用来在 Push 推送时显示用户的名称。(必传)
@param portraitUri:用户头像 URI,最大长度 1024 字节.用来在 Push 推送时显示用户的头像。(必传)
@return $json | entailment |
public function unBlock($userId) {
try{
if (empty($userId))
throw new Exception('Paramer "userId" is required');
$params = array (
'userId' => $userId
);
$ret = $this->SendRequest->curl('/user/unblock.json',$params,'urlencoded','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 解除用户封禁方法(每秒钟限 100 次)
@param userId:用户 Id。(必传)
@return $json | entailment |
public function queryBlock() {
try{
$params = array (
);
$ret = $this->SendRequest->curl('/user/block/query.json',$params,'urlencoded','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 获取被封禁用户方法(每秒钟限 100 次)
@return $json | entailment |
public function addBlacklist($userId, $blackUserId) {
try{
if (empty($userId))
throw new Exception('Paramer "userId" is required');
if (empty($blackUserId))
throw new Exception('Paramer "blackUserId" is required');
$params = array (
'userId' => $userId,
'blackUserId' => $blackUserId
);
$ret = $this->SendRequest->curl('/user/blacklist/add.json',$params,'urlencoded','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 添加用户到黑名单方法(每秒钟限 100 次)
@param userId:用户 Id。(必传)
@param blackUserId:被加到黑名单的用户Id。(必传)
@return $json | entailment |
public function userinfo($userid){
try{
if (empty($userId))
throw new Exception('Paramer "userId" is required');
$params = array (
'userId' => $userId,
);
$ret = $this->SendRequest->curl('/user/info.json',$params,'urlencoded','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 检测用户信息
@param userId:用户 Id。(必传)
@return $json | entailment |
protected function formatAmount()
{
$amount = $this->getAmount();
$amount = str_replace('.', '', $amount);
$amount = str_pad($amount, 12, '0', STR_PAD_LEFT);
return $amount;
} | Returns the amount formatted to match FAC's expectations.
@return string The amount padded with zeros on the left to 12 digits and no decimal place. | entailment |
public function sendData($data)
{
$httpResponse = $this->httpClient->post(
$this->getEndpoint(),
['Content-Type' => 'text/xml; charset=utf-8'],
$this->xmlSerialize($data)
)->send();
return $this->response = $this->newResponse( $httpResponse->xml() );
} | Send the request payload
@param array $data Request payload
@return ResponseInterface | entailment |
protected function xmlSerialize($data, $xml = null)
{
if ( !$xml instanceof SimpleXMLElement )
{
$xml = new SimpleXMLElement('<'. $this->requestName .' xmlns="'. $this->namespace .'" />');
}
foreach ($data as $key => $value)
{
if ( !isset($value) )
{
continue;
}
if ( is_array($value) )
{
$node = $xml->addChild($key);
$this->xmlSerialize($value, $node);
}
else
{
$xml->addChild($key, $value);
}
}
return $xml->asXML();
} | Serializes an array into XML
@param array $data Array to serialize into XML.
@param \SimpleXMLElement $xml SimpleXMLElement object.
@return string XML | entailment |
public function verify(Input $input)
{
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('cgi.verify.start', $this->exercise, $input));
$result = new CgiResult(
array_map(
function (RequestInterface $request) use ($input) {
return $this->checkRequest($request, $input->getArgument('program'));
},
$this->exercise->getRequests()
)
);
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('cgi.verify.finish', $this->exercise, $input));
return $result;
} | Verifies a solution by invoking PHP via the `php-cgi` binary, populating all the super globals with
the information from the request objects returned from the exercise. The exercise can return multiple
requests so the solution will be invoked for however many requests there are.
Events dispatched (for each request):
* cgi.verify.reference-execute.pre
* cgi.verify.reference.executing
* cgi.verify.reference-execute.fail (if the reference solution fails to execute)
* cgi.verify.student-execute.pre
* cgi.verify.student.executing
* cgi.verify.student-execute.fail (if the student's solution fails to execute)
@param Input $input The command line arguments passed to the command.
@return CgiResult The result of the check. | entailment |
public function run(Input $input, OutputInterface $output)
{
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('cgi.run.start', $this->exercise, $input));
$success = true;
foreach ($this->exercise->getRequests() as $i => $request) {
$event = $this->eventDispatcher->dispatch(
new CgiExecuteEvent('cgi.run.student-execute.pre', $request)
);
$process = $this->getProcess($input->getArgument('program'), $event->getRequest());
$output->writeTitle("Request");
$output->emptyLine();
$output->write($this->requestRenderer->renderRequest($request));
$output->writeTitle("Output");
$output->emptyLine();
$process->start();
$this->eventDispatcher->dispatch(
new CgiExecuteEvent('cgi.run.student.executing', $request, ['output' => $output])
);
$process->wait(function ($outputType, $outputBuffer) use ($output) {
$output->write($outputBuffer);
});
$output->emptyLine();
if (!$process->isSuccessful()) {
$success = false;
}
$output->lineBreak();
}
$this->eventDispatcher->dispatch(new ExerciseRunnerEvent('cgi.run.finish', $this->exercise, $input));
return $success;
} | Runs a student's solution by invoking PHP via the `php-cgi` binary, populating all the super globals with
the information from the request objects returned from the exercise. The exercise can return multiple
requests so the solution will be invoked for however many requests there are.
Running only runs the student's solution, the reference solution is not run and no verification is performed,
the output of the student's solution is written directly to the output.
Events dispatched (for each request):
* cgi.run.student-execute.pre
* cgi.run.student.executing
@param Input $input The command line arguments passed to the command.
@param OutputInterface $output A wrapper around STDOUT.
@return bool If the solution was successfully executed, eg. exit code was 0. | entailment |
public function lengthOf($countable, $length, $message = '')
{
$this->assertion->setActual($countable);
return $this->assertion->to->have->length($length, $message);
} | Perform a length assertion.
@param string|array|Countable $countable
@param $length
@param string $message | entailment |
public function isIncluded($haystack, $needle, $message = '')
{
$this->assertion->setActual($haystack);
return $this->assertion->to->include($needle, $message);
} | Perform an inclusion assertion.
@param array|string $haystack
@param mixed $needle
@param string $message | entailment |
public function notInclude($haystack, $needle, $message = '')
{
$this->assertion->setActual($haystack);
return $this->assertion->to->not->include($needle, $message);
} | Perform a negated inclusion assertion.
@param array|string $haystack
@param mixed $needle
@param string $message | entailment |
public function getTemplate($key, $language_id)
{
if ($template = EmailTemplateTranslation::findOne([
'template_id' => EmailTemplate::getIdByKey($key),
'language_id' => $language_id
])) {
return Template::buildTemplate($template);
}
return null;
} | Getting email template model by key
@param string $key
@param integer $language_id
@return null|Template | entailment |
public function getTemplates($key)
{
/** @var EmailTemplateTranslation[] $templates */
if ($templates = EmailTemplateTranslation::findAll([
'template_id' => EmailTemplate::getIdByKey($key)
])) {
return Template::buildTemplates($templates);
}
return null;
} | Getting email template models by key
@param string $key
@return null|Template[] | entailment |
public function getByLangOrFirst($key, $languageId)
{
$templateId = EmailTemplate::getIdByKey($key);
if ($template = EmailTemplateTranslation::findOne([
'template_id' => $templateId,
'language_id' => $languageId
])) {
return Template::buildTemplate($template);
}
elseif ($templates = EmailTemplateTranslation::findAll([
'template_id' => $templateId
])) {
return Template::buildTemplate($templates[0]);
}
return null;
} | Get template
@param string $key
@param $languageId
@return Template|null | entailment |
public function collapse()
{
$results = [];
foreach ($this->array as $item) {
if (!is_array($item)) {
continue;
}
$results = array_merge($results, $item);
}
return new static($results);
} | Collapse an array of arrays into a single array returning a new instance of `ArrayObject`
with the collapsed items.
@return static | entailment |
public function inverseDocumentFrequency(string $field, string $term): float
{
return $this->calculateInverseDocumentFrequency($this->documentCount($field, $term));
} | {@inheritdoc} | entailment |
protected function doMatch($actual)
{
if ($this->isCountable($actual)) {
$this->count = count($actual);
}
if (is_string($actual)) {
$this->count = strlen($actual);
}
if (isset($this->count)) {
return $this->expected === $this->count;
}
throw new InvalidArgumentException('Length matcher requires a string, array, or Countable');
} | Match the length of the countable interface or string against
the expected value.
@param string|array|Countable $actual
@return mixed | entailment |
public function create($chatRoomInfo) {
try{
if (empty($chatRoomInfo))
throw new Exception('Paramer "chatRoomInfo" is required');
$params = array();
foreach ($chatRoomInfo as $key => $value) {
$params['chatroom[' . $key . ']'] = $value;
}
$ret = $this->SendRequest->curl('/chatroom/create.json',$params,'urlencoded','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 创建聊天室方法
@param chatRoomInfo:id:要创建的聊天室的id;name:要创建的聊天室的name。(必传)
@return $json | entailment |
public function join($userId, $chatroomId) {
try{
if (empty($userId))
throw new Exception('Paramer "userId" is required');
if (empty($chatroomId))
throw new Exception('Paramer "chatroomId" is required');
$params = array (
'userId' => $userId,
'chatroomId' => $chatroomId
);
$ret = $this->SendRequest->curl('/chatroom/join.json',$params,'urlencoded','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 加入聊天室方法
@param userId:要加入聊天室的用户 Id,可提交多个,最多不超过 50 个。(必传)
@param chatroomId:要加入的聊天室 Id。(必传)
@return $json | entailment |
public function query($chatroomId) {
try{
if (empty($chatroomId))
throw new Exception('Paramer "chatroomId" is required');
$params = array (
'chatroomId' => $chatroomId
);
$ret = $this->SendRequest->curl('/chatroom/query.json',$params,'urlencoded','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 查询聊天室信息方法
@param chatroomId:要查询的聊天室id(必传)
@return $json | entailment |
public function queryUser($chatroomId, $count, $order) {
try{
if (empty($chatroomId))
throw new Exception('Paramer "chatroomId" is required');
if (empty($count))
throw new Exception('Paramer "count" is required');
if (empty($order))
throw new Exception('Paramer "order" is required');
$params = array (
'chatroomId' => $chatroomId,
'count' => $count,
'order' => $order
);
$ret = $this->SendRequest->curl('/chatroom/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 chatroomId:要查询的聊天室 ID。(必传)
@param count:要获取的聊天室成员数,上限为 500 ,超过 500 时最多返回 500 个成员。(必传)
@param order:加入聊天室的先后顺序, 1 为加入时间正序, 2 为加入时间倒序。(必传)
@return $json | entailment |
public function addPriority($objectName) {
try{
if (empty($objectName))
throw new Exception('Paramer "objectName" is required');
$params = array (
'objectName' => $objectName
);
$ret = $this->SendRequest->curl('/chatroom/message/priority/add.json',$params,'urlencoded','im','POST');
if(empty($ret))
throw new Exception('bad request');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | 添加聊天室消息优先级方法
@param objectName:低优先级的消息类型,每次最多提交 5 个,设置的消息类型最多不超过 20 个。(必传)
@return $json | entailment |
public function getPathParts($path)
{
$path = preg_replace('/\[/', '->[', $path);
if (preg_match('/^->/', $path)) {
$path = substr($path, 2);
}
return explode('->', $path);
} | Breaks a path expression into an array used
for navigating a path.
@param $path
@return array | entailment |
protected function getPathValue($key, $properties)
{
if (!array_key_exists($key, $properties)) {
return null;
}
return new ObjectPathValue($key, $properties[$key]);
} | Given a key and a collection of properties, this method
will return an ObjectPathValue if possible.
@param $key
@param $properties
@return null|ObjectPathValue | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$treeBuilder->root('pucene')
->children()
->enumNode('adapter')->isRequired()->values(['elasticsearch', 'pucene'])->end()
->append($this->getAdaptersNode())
->append($this->getIndexNode())
->end();
return $treeBuilder;
} | {@inheritdoc} | entailment |
public function renderRequest(RequestInterface $request)
{
$return = '';
$return .= sprintf("URL: %s\n", $request->getUri());
$return .= sprintf("METHOD: %s\n", $request->getMethod());
if ($request->getHeaders()) {
$return .= 'HEADERS:';
}
$indent = false;
foreach ($request->getHeaders() as $name => $values) {
if ($indent) {
$return .= str_repeat(' ', 8);
}
$return .= sprintf(" %s: %s\n", $name, implode(', ', $values));
$indent = true;
}
if ($body = (string) $request->getBody()) {
$return .= 'BODY: ';
switch ($request->getHeaderLine('Content-Type')) {
case 'application/json':
$return .= json_encode(json_decode($body, true), JSON_PRETTY_PRINT);
break;
default:
$return .= $body;
break;
}
$return .= "\n";
}
return $return;
} | Render a PSR-7 request.
@param RequestInterface $request
@return string | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.