sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function redirect($url, $view = false)
{
if ($view === false && !preg_match('#^https?\://#i', $url)) {
$_url = (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http://' : 'https://') . $_SERVER['HTTP_HOST'];
$start = substr($url, 0, 1);
if (!empty($start)) {
if ($start === '?') {
$_url .= str_replace('?' . $_SERVER['QUERY_STRING'], '', $_SERVER['REQUEST_URI']);
} elseif ($start !== '/') {
$_url .= '/';
}
}
$_url .= $url;
} else {
$_url = $url;
}
$this->last_selector = null;
if ($view !== false) {
return $this->reset_response()->cmd(8, array(
$_url,
$view
));
} else {
return $this->cmd(8, array(
$_url,
false
));
}
}
|
Creates a redirect
@param string $url Complete url with http:// (according to W3 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30)
@param bool|string $view Internal means that phery will cancel the
current DOM manipulation and commands and will issue another
phery.remote to the location in url, useful if your PHP code is
issuing redirects but you are using AJAX views.
Passing false will issue a browser redirect
@return PheryResponse
|
entailment
|
public function prepend($content, $selector = null)
{
if (is_array($content)) {
$content = join("\n", $content);
}
return $this->cmd('prepend', array(
$this->typecast($content, true, true)
), $selector);
}
|
Prepend string/HTML to target(s)
@param string $content Content to be prepended to the selected element
@param string $selector [optional] Optional jquery selector string
@return PheryResponse
|
entailment
|
public function include_stylesheet(array $path, $replace = false)
{
$this->last_selector = null;
return $this->cmd(10, array(
'c',
$path,
$replace
));
}
|
Include a stylesheet in the head of the page
@param array $path An array of stylesheets, comprising of 'id' => 'path'
@param bool $replace Replace any existing ids
@return PheryResponse
|
entailment
|
public function include_script($path, $replace = false)
{
$this->last_selector = null;
return $this->cmd(10, array(
'j',
$path,
$replace
));
}
|
Include a script in the head of the page
@param array $path An array of scripts, comprising of 'id' => 'path'
@param bool $replace Replace any existing ids
@return PheryResponse
|
entailment
|
protected function typecast($argument, $toString = true, $nested = false, $depth = 4)
{
if ($nested) {
$depth--;
if ($argument instanceof PheryResponse) {
$argument = array('PR' => $argument->process_merged());
} elseif ($argument instanceof PheryFunction) {
$argument = array('PF' => $argument->compile());
} elseif ($depth > 0 && is_array($argument)) {
foreach ($argument as $name => $arg) {
$argument[$name] = $this->typecast($arg, $toString, $nested, $depth);
}
}
}
if ($toString && !empty($argument)) {
if (is_string($argument) && ctype_digit($argument)) {
if ($this->config['convert_integers'] === true) {
$argument = (int)$argument;
}
} elseif (is_object($argument) && $this->config['typecast_objects'] === true) {
$class = get_class($argument);
if ($class !== false) {
$rc = new ReflectionClass(get_class($argument));
if ($rc->hasMethod('__toString')) {
$argument = "{$argument}";
} else {
$argument = json_decode(json_encode($argument), true);
}
} else {
$argument = json_decode(json_encode($argument), true);
}
}
}
return $argument;
}
|
Convert, to a maximum depth, nested responses, and typecast int properly
@param mixed $argument The value
@param bool $toString Call class __toString() if possible, and typecast int correctly
@param bool $nested Should it look for nested arrays and classes?
@param int $depth Max depth
@return mixed
|
entailment
|
protected function process_merged()
{
$data = $this->data;
if (empty($data) && $this->last_selector !== null && !$this->is_special_selector('#')) {
$data[$this->last_selector] = array();
}
foreach ($this->merged as $r) {
foreach ($r as $selector => $response) {
if (!ctype_digit($selector)) {
if (isset($data[$selector])) {
$data[$selector] = array_merge_recursive($data[$selector], $response);
} else {
$data[$selector] = $response;
}
} else {
$selector = (int)$selector;
while (isset($data['0' . $selector])) {
$selector++;
}
$data['0' . $selector] = $response;
}
}
}
return $data;
}
|
Process merged responses
@return array
|
entailment
|
public function unserialize($serialized)
{
$obj = json_decode($serialized, true);
if ($obj && is_array($obj) && json_last_error() === JSON_ERROR_NONE) {
$this->exchangeArray($obj['this']);
$this->data = (array)$obj['data'];
$this->set_response_name((string)$obj['name']);
$this->merged = (array)$obj['merged'];
} else {
throw new PheryException('Invalid data passed to unserialize');
}
return $this;
}
|
Initialize the instance from a serialized state
@param string $serialized
@throws PheryException
@return PheryResponse
|
entailment
|
public function serialize()
{
return json_encode(array(
'data' => $this->data,
'this' => $this->getArrayCopy(),
'name' => $this->name,
'merged' => $this->merged,
));
}
|
Serialize the response in JSON
@return string|bool
|
entailment
|
protected function is_special_selector($type = null, $selector = null)
{
$selector = Phery::coalesce($selector, $this->last_selector);
if ($selector && preg_match('/\{([\D]+)\d+\}/', $selector, $matches)) {
if ($type === null) {
return true;
}
return ($matches[1] === $type);
}
return false;
}
|
Determine if the last selector or the selector provided is an special
@param string $type
@param string $selector
@return boolean
|
entailment
|
private function step4()
{
$length = Utf8::strlen($this->word);
if (!$this->inR1(($length-1))) {
return false;
}
$lastLetter = Utf8::substr($this->word, -1, 1);
if (in_array($lastLetter, self::$vowels)) {
return false;
}
$beforeLastLetter = Utf8::substr($this->word, -2, 1);
if ($lastLetter == $beforeLastLetter) {
$this->word = Utf8::substr($this->word, 0, -1);
}
return true;
}
|
Step 4: undouble
If the word ends with double consonant in R1, remove one of the consonants.
|
entailment
|
protected function r1()
{
list($this->r1Index, $this->r1) = $this->rx($this->word);
}
|
R1 is the region after the first non-vowel following a vowel, or the end of the word if there is no such non-vowel.
|
entailment
|
protected function r2()
{
list($index, $value) = $this->rx($this->r1);
$this->r2 = $value;
$this->r2Index = $this->r1Index + $index;
}
|
R2 is the region after the first non-vowel following a vowel in R1, or the end of the word if there is no such non-vowel.
|
entailment
|
public function stem($word)
{
// we do ALL in UTF-8
if (! Utf8::check($word)) {
throw new \Exception('Word must be in UTF-8');
}
$this->plainVowels = implode('', self::$vowels);
$this->word = Utf8::strtolower($word);
// First, replace all acute accents by grave accents.
$this->word = Utf8::str_replace(array('á', 'é', 'í', 'ó', 'ú'), array('à', 'è', 'ì', 'ò', 'ù'), $this->word);
//And, as in French, put u after q, and u, i between vowels into upper case. (See note on vowel marking.) The vowels are then
$this->word = preg_replace('#([q])u#u', '$1U', $this->word);
$this->word = preg_replace('#(['.$this->plainVowels.'])u(['.$this->plainVowels.'])#u', '$1U$2', $this->word);
$this->word = preg_replace('#(['.$this->plainVowels.'])i(['.$this->plainVowels.'])#u', '$1I$2', $this->word);
$this->rv();
$this->r1();
$this->r2();
$this->step0();
$word = $this->word;
$this->step1();
//Do step 2 if no ending was removed by step 1.
if ($word == $this->word) {
$this->step2();
}
$this->step3a();
$this->step3b();
$this->finish();
return $this->word;
}
|
{@inheritdoc}
|
entailment
|
private function step0()
{
// Search for the longest among the following suffixes
if ( ($position = $this->search(array(
'gliela', 'gliele', 'glieli', 'glielo', 'gliene',
'sene', 'mela', 'mele', 'meli', 'melo', 'mene', 'tela', 'tele', 'teli', 'telo', 'tene', 'cela',
'cele', 'celi', 'celo', 'cene', 'vela', 'vele', 'veli', 'velo', 'vene',
'gli', 'la', 'le', 'li', 'lo', 'mi', 'ne', 'si', 'ti', 'vi', 'ci'))) !== false) {
$suffixe = Utf8::substr($this->word, $position);
// following one of (in RV)
// a
$a = array('ando', 'endo');
$a = array_map(function($item) use ($suffixe) {
return $item . $suffixe;
}, $a);
// In case of (a) the suffix is deleted
if ($this->searchIfInRv($a) !== false) {
$this->word = Utf8::substr($this->word, 0, $position);
}
//b
$b = array('ar', 'er', 'ir');
$b = array_map(function($item) use ($suffixe) {
return $item . $suffixe;
}, $b);
// in case (b) it is replace by e
if ($this->searchIfInRv($b) !== false) {
$this->word = preg_replace('#('.$suffixe.')$#u', 'e', $this->word);
}
return true;
}
return false;
}
|
Step 0: Attached pronoun
|
entailment
|
private function step1()
{
// amente
// delete if in R1
// if preceded by iv, delete if in R2 (and if further preceded by at, delete if in R2), otherwise,
// if preceded by os, ic or abil, delete if in R2
if ( ($position = $this->search(array('amente'))) !== false) {
if ($this->inR1($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
// if preceded by iv, delete if in R2 (and if further preceded by at, delete if in R2), otherwise,
if ( ($position2 = $this->searchIfInR2(array('iv'))) !== false) {
$this->word = Utf8::substr($this->word, 0, $position2);
if ( ($position3 = $this->searchIfInR2(array('at'))) !== false) {
$this->word = Utf8::substr($this->word, 0, $position3);
}
// if preceded by os, ic or ad, delete if in R2
} elseif ( ($position4 = $this->searchIfInR2(array('os', 'ic', 'abil'))) != false) {
$this->word = Utf8::substr($this->word, 0, $position4);
}
return true;
}
// delete if in R2
if ( ($position = $this->search(array(
'ibili', 'atrice', 'abili', 'abile', 'ibile', 'atrici', 'mente',
'anza', 'anze', 'iche', 'ichi', 'ismo', 'ismi', 'ista', 'iste', 'isti', 'istà', 'istè', 'istì', 'ante', 'anti',
'ico', 'ici', 'ica', 'ice', 'oso', 'osi', 'osa', 'ose'
))) !== false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
return true;
}
// azione azioni atore atori
// delete if in R2
// if preceded by ic, delete if in R2
if ( ($position = $this->search(array('azione', 'azioni', 'atore', 'atori'))) !== false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
if ( ($position2 = $this->search(array('ic'))) !== false) {
if ($this->inR2($position2)) {
$this->word = Utf8::substr($this->word, 0, $position2);
}
}
}
return true;
}
// logia logie
// replace with log if in R2
if ( ($position = $this->search(array('logia', 'logie'))) !== false) {
if ($this->inR2($position)) {
$this->word = preg_replace('#(logia|logie)$#u', 'log', $this->word);
}
return true;
}
// uzione uzioni usione usioni
// replace with u if in R2
if ( ($position = $this->search(array('uzione', 'uzioni', 'usione', 'usioni'))) !== false) {
if ($this->inR2($position)) {
$this->word = preg_replace('#(uzione|uzioni|usione|usioni)$#u', 'u', $this->word);
}
return true;
}
// enza enze
// replace with ente if in R2
if ( ($position = $this->search(array('enza', 'enze'))) !== false) {
if ($this->inR2($position)) {
$this->word = preg_replace('#(enza|enze)$#u', 'ente', $this->word);
}
return true;
}
// amento amenti imento imenti
// delete if in RV
if ( ($position = $this->search(array('amento', 'amenti', 'imento', 'imenti'))) !== false) {
if ($this->inRv($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
return true;
}
// ità
// delete if in R2
// if preceded by abil, ic or iv, delete if in R2
if ( ($position = $this->search(array('ità'))) !== false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
if ( ($position2 = $this->searchIfInR2(array('abil', 'ic', 'iv'))) != false) {
$this->word = Utf8::substr($this->word, 0, $position2);
}
return true;
}
// ivo ivi iva ive
// delete if in R2
// if preceded by at, delete if in R2 (and if further preceded by ic, delete if in R2)
if ( ($position = $this->search(array('ivo', 'ivi', 'iva', 'ive'))) !== false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
if ( ($position2 = $this->searchIfInR2(array('at'))) !== false) {
$this->word = Utf8::substr($this->word, 0, $position2);
if ( ($position3 = $this->searchIfInR2(array('ic'))) !== false) {
$this->word = Utf8::substr($this->word, 0, $position3);
}
}
return true;
}
return false;
}
|
Step 1: Standard suffix removal
|
entailment
|
private function step2()
{
if ( ($position = $this->searchIfInRv(array(
'assimo', 'assero', 'eranno', 'erebbero', 'erebbe', 'eremmo', 'ereste', 'eresti', 'essero', 'iranno', 'irebbero', 'irebbe', 'iremmo',
'iscano', 'ireste', 'iresti', 'iscono', 'issero',
'avamo', 'arono', 'avano', 'avate', 'eremo', 'erete', 'erono', 'evamo', 'evano', 'evate', 'ivamo', 'ivano', 'ivate', 'iremo', 'irete', 'irono',
'ammo', 'ando', 'asse', 'assi', 'emmo', 'enda', 'ende', 'endi', 'endo', 'erai', 'erei', 'Yamo', 'iamo', 'immo', 'irà', 'irai', 'irei',
'isca', 'isce', 'isci', 'isco',
'ano', 'are', 'ata', 'ate', 'ati', 'ato', 'ava', 'avi', 'avo', 'erà', 'ere', 'erò', 'ete', 'eva',
'evi', 'evo', 'ire', 'ita', 'ite', 'iti', 'ito', 'iva', 'ivi', 'ivo', 'ono', 'uta', 'ute', 'uti', 'uto', 'irò', 'ar', 'ir'))) !== false) {
$this->word = Utf8::substr($this->word, 0, $position);
}
}
|
Step 2: Verb suffixes
Search for the longest among the following suffixes in RV, and if found, delete.
|
entailment
|
private function step3a()
{
if ($this->searchIfInRv(array('a', 'e', 'i', 'o', 'à', 'è', 'ì', 'ò')) !== false) {
$this->word = Utf8::substr($this->word, 0, -1);
if ($this->searchIfInRv(array('i')) !== false) {
$this->word = Utf8::substr($this->word, 0, -1);
}
return true;
}
return false;
}
|
Step 3a
Delete a final a, e, i, o, à, è, ì or ò if it is in RV, and a preceding i if it is in RV
|
entailment
|
private function step3b()
{
if ($this->searchIfInRv(array('ch')) !== false) {
$this->word = preg_replace('#(ch)$#u', 'c', $this->word);
} elseif ($this->searchIfInRv(array('gh')) !== false) {
$this->word = preg_replace('#(gh)$#u', 'g', $this->word);
}
}
|
Step 3b
Replace final ch (or gh) with c (or g) if in RV (crocch -> crocc)
|
entailment
|
public static function insertIgnore(array $attributes = [])
{
$model = new static();
$driver = $model->GetConnection()->GetDriverName();
switch ($driver) {
case 'sqlite':
return static::executeQuery('insert or ignore', $attributes);
break;
default:
return static::executeQuery('insert ignore', $attributes);
break;
}
}
|
performs an 'insert ignore' query with the data
@param array $attributes
@return bool t/f for success/failure
|
entailment
|
public function execute($command)
{
$this->executeDecorators($command);
$handler = $this->commandTranslator->toCommandHandler($command);
return $this->app->make($handler)->handle($command);
}
|
Execute the command
@param $command
@return mixed
|
entailment
|
protected function executeDecorators($command)
{
foreach ($this->decorators as $className)
{
$instance = $this->app->make($className);
if ( ! $instance instanceof CommandBus)
{
$message = 'The class to decorate must be an implementation of Laracasts\Commander\CommandBus';
throw new InvalidArgumentException($message);
}
$instance->execute($command);
}
}
|
Execute all registered decorators
@param object $command
@return null
|
entailment
|
protected function execute($command, array $input = null, $decorators = [])
{
$input = $input ?: Input::all();
$command = $this->mapInputToCommand($command, $input);
$bus = $this->getCommandBus();
// If any decorators are passed, we'll filter through and register them
// with the CommandBus, so that they are executed first.
foreach ($decorators as $decorator)
{
$bus->decorate($decorator);
}
return $bus->execute($command);
}
|
Execute the command.
@param string $command
@param array $input
@param array $decorators
@return mixed
|
entailment
|
protected function mapInputToCommand($command, array $input)
{
$dependencies = [];
$class = new ReflectionClass($command);
foreach ($class->getConstructor()->getParameters() as $parameter)
{
$name = $parameter->getName();
if (array_key_exists($name, $input))
{
$dependencies[] = $input[$name];
}
elseif ($parameter->isDefaultValueAvailable())
{
$dependencies[] = $parameter->getDefaultValue();
}
else
{
throw new InvalidArgumentException("Unable to map input to command: {$name}");
}
}
return $class->newInstanceArgs($dependencies);
}
|
Map an array of input to a command's properties.
@param string $command
@param array $input
@throws InvalidArgumentException
@author Taylor Otwell
@return mixed
|
entailment
|
public function dispatch(array $events)
{
foreach($events as $event)
{
$eventName = $this->getEventName($event);
$this->event->fire($eventName, $event);
$this->log->info("{$eventName} was fired.");
}
}
|
Dispatch all raised events.
@param array $events
|
entailment
|
public function fire()
{
$path = $this->argument('path');
$properties = $this->option('properties');
$base = $this->option('base');
// Parse the command input.
$commandInput = $this->parser->parse($path, $properties);
$handlerInput = $this->parser->parse($path.'Handler', $properties);
// Actually create the files with the correct boilerplate.
$this->generator->make(
$commandInput,
__DIR__.'/stubs/command.stub',
"{$base}/{$path}.php"
);
$this->generator->make(
$handlerInput,
__DIR__.'/stubs/handler.stub',
"{$base}/{$path}Handler.php"
);
$this->info('All done! Your two classes have now been generated.');
}
|
Execute the console command.
@return mixed
|
entailment
|
public function parse($path, $properties)
{
$segments = explode('\\', str_replace('/', '\\', $path));
$name = array_pop($segments);
$namespace = implode('\\', $segments);
$properties = $this->parseProperties($properties);
return new CommandInput($name, $namespace, $properties);
}
|
Parse the command input.
@param $path
@param $properties
@return CommandInput
|
entailment
|
public function handle($event)
{
$eventName = $this->getEventName($event);
if ($this->listenerIsRegistered($eventName))
{
return call_user_func([$this, 'when'.$eventName], $event);
}
}
|
Handle the event
@param $event
@return mixed
|
entailment
|
public function toCommandHandler($command)
{
$commandClass = get_class($command);
$handler = substr_replace($commandClass, 'CommandHandler', strrpos($commandClass, 'Command'));
if ( ! class_exists($handler))
{
$message = "Command handler [$handler] does not exist.";
throw new HandlerNotRegisteredException($message);
}
return $handler;
}
|
Translate a command to its handler counterpart
@param $command
@return mixed
@throws HandlerNotRegisteredException
|
entailment
|
public function execute($uri)
{
foreach ($this->routes as $pattern => $callback) {
if (preg_match($pattern, $uri, $params) === 1) {
call_user_func_array($this->beforeRouteCallback, $params);
array_shift($params);
return call_user_func_array($callback, array_values($params));
} else {
error_log("$pattern did not match $uri");
}
}
}
|
Match URI to route definition and call it
@param string $uri
@return mixed
|
entailment
|
public function createToken()
{
return $this->generator->generateString($this->tokenBytes, $this->formatMap[$this->tokenFormat]);
}
|
Generate a random, 32-byte Token
@return string
|
entailment
|
public function replaceTriplet($credential, $token, $persistentToken, $expire)
{
$this->cleanTriplet($credential, $persistentToken);
$this->storeTriplet($credential, $token, $persistentToken, $expire);
}
|
Replace current token after successful authentication
@param mixed $credential
@param string $token
@param string $persistentToken
@param int $expire
|
entailment
|
public function cleanExpiredTokens($expiryTime)
{
foreach (glob($this->path.DIRECTORY_SEPARATOR."*".$this->suffix) as $file) {
if (filemtime($file) < $expiryTime) {
unlink($file);
}
}
}
|
Remove all expired triplets of all users.
@param int $expiryTime Timestamp, all tokens before this time will be deleted
@return void
|
entailment
|
public function replaceTriplet($credential, $token, $persistentToken, $expire = 0)
{
try {
$this->connection->beginTransaction();
$this->cleanTriplet($credential, $persistentToken);
$this->storeTriplet($credential, $token, $persistentToken, $expire);
$this->connection->commit();
} catch (\PDOException $e) {
$this->connection->rollBack();
throw $e;
}
}
|
Replace current token after successful authentication
@param mixed $credential
@param string $token
@param string $persistentToken
@param int $expire
|
entailment
|
public function cleanExpiredTokens($expiryTime)
{
$sql = "DELETE FROM {$this->tableName} WHERE {$this->expiresColumn} < ? ";
$query = $this->connection->prepare($sql);
$query->execute(array(date("Y-m-d H:i:s", $expiryTime)));
}
|
Remove all expired triplets of all users.
@param int $expiryTime Timestamp, all tokens before this time will be deleted
@return void
|
entailment
|
public function login()
{
$cookieValue = $this->cookie->getValue();
if (!$cookieValue) {
return LoginResult::newNoCookieResult();
}
$triplet = Triplet::fromString($cookieValue);
if (!$triplet->isValid()) {
return LoginResult::newManipulationResult();
}
if ($this->cleanExpiredTokensOnLogin) {
$this->storage->cleanExpiredTokens(time() - $this->expireTime);
}
$tripletLookupResult = $this->storage->findTriplet(
$triplet->getCredential(),
$triplet->getSaltedOneTimeToken($this->salt),
$triplet->getSaltedPersistentToken($this->salt)
);
switch ($tripletLookupResult) {
case Storage\StorageInterface::TRIPLET_FOUND:
$expire = time() + $this->expireTime;
$newTriplet = new Triplet($triplet->getCredential(), $this->tokenGenerator->createToken(), $triplet->getPersistentToken());
$this->storage->replaceTriplet(
$newTriplet->getCredential(),
$newTriplet->getSaltedOneTimeToken($this->salt),
$newTriplet->getSaltedPersistentToken($this->salt),
$expire
);
$this->cookie->setValue((string) $newTriplet);
return LoginResult::newSuccessResult($triplet->getCredential());
case Storage\StorageInterface::TRIPLET_INVALID:
$this->cookie->deleteCookie();
if ($this->cleanStoredTokensOnInvalidResult) {
$this->storage->cleanAllTriplets($triplet->getCredential());
}
return LoginResult::newManipulationResult();
default:
return LoginResult::newExpiredResult();
}
}
|
Check Credentials from cookie. Returns false if login was not successful, credential string if it was successful
@return LoginResult
|
entailment
|
public function clearCookie()
{
$triplet = Triplet::fromString($this->cookie->getValue());
$this->cookie->deleteCookie();
if (!$triplet->isValid()) {
return false;
}
$this->storage->cleanTriplet($triplet->getCredential(), $triplet->getSaltedPersistentToken($this->salt));
return true;
}
|
Expire the rememberme cookie, unset $_COOKIE[$this->cookieName] value and
remove current login triplet from storage.
@return boolean
|
entailment
|
public function registerClientScript() {
$view = $this->getView();
FancyBoxAsset::register($view);
if ($this->mouse) {
MousewheelAsset::register($view);
}
if ($this->helpers) {
FancyBoxHelpersAsset::register($view);
}
}
|
Registers required script for the plugin to work as DatePicker
|
entailment
|
public function time($time)
{
if ($time instanceof Carbon) {
$time = $time->timestamp;
}
$this->timestamp = $time;
return $this;
}
|
Set the time of the Pushover message.
@param Carbon|int $time
@return $this
|
entailment
|
public function url($url, $title = null)
{
$this->url = $url;
$this->urlTitle = $title;
return $this;
}
|
Set a supplementary url for the Pushover message.
@param string $url
@param string $title
@return $this
|
entailment
|
public function priority($priority, $retryTimeout = null, $expireAfter = null)
{
$this->noEmergencyWithoutRetryOrExpire($priority, $retryTimeout, $expireAfter);
$this->priority = $priority;
$this->retry = $retryTimeout;
$this->expire = $expireAfter;
return $this;
}
|
Set the priority of the Pushover message.
Retry and expire are mandatory when setting the priority to emergency.
@param int $priority
@param int $retryTimeout
@param int $expireAfter
@return $this
|
entailment
|
public function toArray()
{
return [
'message' => $this->content,
'title' => $this->title,
'timestamp' => $this->timestamp,
'priority' => $this->priority,
'url' => $this->url,
'url_title' => $this->urlTitle,
'sound' => $this->sound,
'retry' => $this->retry,
'expire' => $this->expire,
];
}
|
Array representation of Pushover Message.
@return array
|
entailment
|
protected function noEmergencyWithoutRetryOrExpire($priority, $retry, $expire)
{
if ($priority == self::EMERGENCY_PRIORITY && (! isset($retry) || ! isset($expire))) {
throw new EmergencyNotificationRequiresRetryAndExpire();
}
}
|
Ensure an emergency message has an retry and expiry time.
@param int $priority
@param int $retry
@param int $expire
@throws EmergencyNotificationRequiresRetryAndExpire
|
entailment
|
public function send($params)
{
try {
return $this->http->post($this->pushoverApiUrl, [
'form_params' => $this->paramsWithToken($params),
]);
} catch (RequestException $exception) {
if ($exception->getResponse()) {
throw CouldNotSendNotification::serviceRespondedWithAnError($exception->getResponse());
}
throw ServiceCommunicationError::communicationFailed($exception);
} catch (Exception $exception) {
throw ServiceCommunicationError::communicationFailed($exception);
}
}
|
Send Pushover message.
@link https://pushover.net/api
@param array $params
@return \Psr\Http\Message\ResponseInterface
@throws CouldNotSendNotification
|
entailment
|
public function boot()
{
$this->app->when(PushoverChannel::class)
->needs(Pushover::class)
->give(function () {
return new Pushover(new HttpClient(), config('services.pushover.token'));
});
}
|
Bootstrap the application services.
|
entailment
|
public function send($notifiable, Notification $notification)
{
if (! $pushoverReceiver = $notifiable->routeNotificationFor('pushover')) {
return;
}
if (is_string($pushoverReceiver)) {
$pushoverReceiver = PushoverReceiver::withUserKey($pushoverReceiver);
}
$message = $notification->toPushover($notifiable);
try {
$this->pushover->send(array_merge($message->toArray(), $pushoverReceiver->toArray()));
} catch (ServiceCommunicationError $serviceCommunicationError) {
$this->fireFailedEvent($notifiable, $notification, $serviceCommunicationError->getMessage());
}
}
|
Send the given notification.
@param mixed $notifiable
@param \Illuminate\Notifications\Notification $notification
@throws \NotificationChannels\Pushover\Exceptions\CouldNotSendNotification
|
entailment
|
public function toDevice($device)
{
if (is_array($device)) {
$this->devices = array_merge($device, $this->devices);
return $this;
}
$this->devices[] = $device;
return $this;
}
|
Send the message to a specific device.
@param array|string $device
@return PushoverReceiver
|
entailment
|
public function toArray()
{
return array_merge([
'user' => $this->key,
'device' => implode(',', $this->devices),
], $this->token ? ['token' => $this->token] : []);
}
|
Get array representation of Pushover receiver.
@return array
|
entailment
|
public function initialize(array $config) {
$this->config = $config;
$this->controller = $this->_registry->getController();
$registry = new ComponentRegistry();
$this->Acl = new AclComponent($registry, Configure::read('Acl'));
$this->Aco = $this->Acl->Aco;
$this->Aro = $this->Acl->Aro;
return null;
}
|
Initialize all properties we need
@param array $config initialize cake method need $config
@return null
|
entailment
|
public function arosBuilder() {
$newAros = array();
$counter = 0;
$parent = null;
$models = Configure::read('AclManager.aros');
// foreach ($models as $model) {
for($i = 0; $i < count($models); $i++) {
$model = $models[$i];
$this->{$model} = TableRegistry::get($model);
// Build the roles.
$items = $this->{$model}->find('all');
foreach($items as $item) {
if($i > 0 && isset($models[$i-1])) {
$pk = strtolower(Inflector::singularize($models[$i-1])).'_id';
$parent = $this->Aro->find('all',
['conditions' => [
'model' => $models[$i-1],
'foreign_key' => $item->{$pk}
]])->first();
}
// Prepare alias
$alias = null;
if(isset($item->name)) {
$alias = $item->name;
}
if(isset($item->username)) {
$alias = $item->username;
}
// Create aro
$aro = new Aro([
'alias' => $alias,
'foreign_key' => $item->id,
'model' => $model,
'parent_id' => (isset($parent->id)) ? $parent->id : Null
]);
if($this->__findAro($aro) == 0 && $this->Acl->Aro->save($aro)) {
$counter++;
}
}
}
return $counter;
}
|
Create aros
@return bool return true if all aros saved
|
entailment
|
public function checkNodeOrSave($path, $alias, $parentId = null) {
$node = $this->Aco->node($path);
if ($node === false) {
$data = [
'parent_id' => $parentId,
'model' => null,
'alias' => $alias,
];
$entity = $this->Aco->newEntity($data);
$node = $this->Aco->save($entity);
return $node;
}
return $node->first();
}
|
Check if the aco exist and store it if empty
@param string $path the path like App/Admin/Admin/home
@param string $alias the name of the alias like home
@param null $parentId the parent id
@return object
|
entailment
|
private function __findAro($aro) {
if(isset($aro->parent_id)) {
$conditions = [
'parent_id' => $aro->parent_id,
'foreign_key' => $aro->foreign_key,
'model' => $aro->model
];
} else {
$conditions = [
'parent_id IS NULL',
'foreign_key' => $aro->foreign_key,
'model' => $aro->model
];
}
return $this->Acl->Aro->find('all', [
'conditions' => $conditions,
'recursive' => -1
])->count();
}
|
Find aro in database and returns the number of matches
@param object $aro
|
entailment
|
public function initialize(){
parent::initialize();
/**
* Initialize ACLs
*/
$registry = new ComponentRegistry();
$this->Acl = new AclComponent($registry, Configure::read('Acl'));
$this->AclExtras = new AclExtras();
$this->AclExtras->startup($this);
/**
* Loading required Model
*/
$models = Configure::read('AclManager.models');
foreach ($models as $model) {
$this->loadModel($model);
}
$this->loadModel('Acl.Permissions');
$this->loadModel('Acos');
/**
* Pagination
*/
$aros = Configure::read('AclManager.aros');
foreach ($aros as $aro) {
$l = Configure::read("AclManager.{$aro}.limit");
$limit = empty($l) ? 4 : $l;
$this->paginate[$this->{$aro}->alias()] = array(
'recursive' => -1,
'limit' => $limit
);
}
return null;
}
|
Initialize
|
entailment
|
public function permissions($model = NULL) {
if(!$this->Auth->user()){
$this->Flash->error(__('Please sign in'));
$this->redirect(['action' => 'index']);
}
$this->model = $model;
// Saving permissions
if ($this->request->is('post') || $this->request->is('put')) {
$perms = isset($this->request->data['Perms']) ? $this->request->data['Perms'] : array();
foreach ($perms as $aco => $aros) {
$action = str_replace(":", "/", $aco);
foreach ($aros as $node => $perm) {
list($model, $id) = explode(':', $node);
$node = array('model' => $model, 'foreign_key' => $id);
if ($perm == 'allow') {
$this->Acl->allow($node, $action);
} elseif ($perm == 'inherit') {
$this->Acl->inherit($node, $action);
} elseif ($perm == 'deny') {
$this->Acl->deny($node, $action);
}
}
}
}
if (!$model || !in_array($model, Configure::read('AclManager.aros'))) {
$m = Configure::read('AclManager.aros');
$model = $m[0];
}
$Aro = $this->{$model};
$arosRes = $this->paginate($Aro->alias());
$aros = $this->_parseAros($arosRes);
$permKeys = $this->_getKeys();
/**
* Build permissions info
*/
$acosRes = $this->Acl->Aco->find('all', ['order' => 'lft ASC'])->contain(['Aros'])->toArray();
$this->acos = $acos = $this->_parseAcos($acosRes);
$perms = array();
$parents = array();
foreach ($acos as $key => $data) {
$aco = & $acos[$key];
$aco = array('Aco' => $data['Aco'], 'Aro' => $data['Aro'], 'Action' => array());
$id = $aco['Aco']['id'];
// Generate path
if ($aco['Aco']['parent_id'] && isset($parents[$aco['Aco']['parent_id']])) {
$parents[$id] = $parents[$aco['Aco']['parent_id']] . '/' . $aco['Aco']['alias'];
} else {
$parents[$id] = $aco['Aco']['alias'];
}
$aco['Action'] = $parents[$id];
// Fetching permissions per ARO
$acoNode = $aco['Action'];
foreach ($aros as $aro) {
$aroId = $aro[$Aro->alias()]['id'];
$evaluate = $this->_evaluate_permissions($permKeys, array('id' => $aroId, 'alias' => $Aro->alias()), $aco, $key);
$perms[str_replace('/', ':', $acoNode)][$Aro->alias() . ":" . $aroId . '-inherit'] = $evaluate['inherited'];
$perms[str_replace('/', ':', $acoNode)][$Aro->alias() . ":" . $aroId] = $evaluate['allowed'];
}
}
$this->request->data = array('Perms' => $perms);
$this->set('model', $model);
$this->set('manage', Configure::read('AclManager.aros'));
$this->set('hideDenied', Configure::read('AclManager.hideDenied'));
$this->set('aroAlias', $Aro->alias());
$this->set('aroDisplayField', $Aro->displayField());
$this->set(compact('acos', 'aros'));
}
|
Manage Permissions
|
entailment
|
public function updateAcos() {
$this->AclExtras->acoUpdate();
$url = ($this->request->referer() == '/') ? ['plugin' => 'AclManager','controller' => 'Acl','action' => 'index'] : $this->request->referer();
$this->redirect($url);
}
|
Update ACOs
|
entailment
|
public function updateAros() {
$arosCounter = $this->AclManager->arosBuilder();
$this->Flash->success(sprintf(__("%d AROs have been created, updated or deleted"), $arosCounter));
$url = ($this->request->referer() == '/') ? ['plugin' => 'AclManager','controller' => 'Acl','action' => 'index'] : $this->request->referer();
$this->redirect($url);
}
|
Update AROs
|
entailment
|
public function revokePerms() {
$conn = ConnectionManager::get('default');
$stmt = $conn->execute('TRUNCATE TABLE aros_acos');
$info = $stmt->errorInfo();
if ($info != null && !empty($info)) {
$this->Flash->success(__("All permissions dropped!"));
} else {
$this->Flash->error(__("Error while trying to drop permissions"));
}
/**
* Get Model
*/
$models = Configure::read('AclManager.aros');
$mCounter = 0;
foreach ($models as $model) {
if($mCounter == (count($models)-1)) {
$f = $this->{$model}->find('all',
['order' => [$model.'.id' => 'ASC']
])->first();
$this->log($f, LOG_DEBUG);
$this->Acl->allow([$model => ['id' => $f->id]], 'controllers');
$this->Flash->success(__("Granted permissions to {0} with id {1}", $model, (int)$f->id));
}
$mCounter++;
}
$this->redirect(array("action" => "permissions"));
}
|
Delete permissions
|
entailment
|
public function drop() {
$conn = ConnectionManager::get('default');
$stmt1 = $conn->execute('TRUNCATE TABLE aros_acos');
$info1 = $stmt1->errorInfo();
if ($info1[1] != null) {
$this->log($info1, LOG_ERR);
if(!empty($info1)) {
$this->Flash->error($info1);
}
}
$stmt2 = $conn->execute('TRUNCATE TABLE acos');
$info2 = $stmt2->errorInfo();
if ($info2[1] != null) {
$this->log($info2, LOG_ERR);
if(!empty($info2)) {
$this->Flash->error($info2);
}
}
$stmt3 = $conn->execute('TRUNCATE TABLE aros');
$info3 = $stmt3->errorInfo();
if ($info3[1] != null) {
$this->log($info3, LOG_ERR);
if(!empty($info3)) {
$this->Flash->error($info3);
}
}
$this->Flash->success(__("ACOs and AROs have been dropped."));
$this->redirect(["action" => "index"]);
}
|
Delete everything (ACOs and AROs)
|
entailment
|
public function defaults() {
$conn = ConnectionManager::get('default');
$stmt1 = $conn->execute('TRUNCATE TABLE aros_acos');
$info1 = $stmt1->errorInfo();
if ($info1[1] != null) {
$this->log($info1, LOG_ERR);
if(!empty($info1)) {
$this->Flash->error($info1);
}
}
$stmt2 = $conn->execute('TRUNCATE TABLE acos');
$info2 = $stmt2->errorInfo();
if ($info2[1] != null) {
$this->log($info2, LOG_ERR);
if(!empty($info2)) {
$this->Flash->error($info2);
}
}
$stmt3 = $conn->execute('TRUNCATE TABLE aros');
$info3 = $stmt3->errorInfo();
if ($info3[1] != null) {
$this->log($info3, LOG_ERR);
if(!empty($info3)) {
$this->Flash->error($info3);
}
}
$this->Flash->success(__("ACOs and AROs have been dropped"));
/**
* ARO Sync
*/
$aros = $this->AclManager->arosBuilder();
$this->Flash->success(sprintf(__("%d AROs have been created, updated or deleted"), $aros));
// $this->Flash->success(__("AROs update complete"));
/**
* ACO Sync
*/
$this->AclExtras->acoUpdate();
/**
* Get Model
*/
$models = Configure::read('AclManager.aros');
$mCounter = 0;
foreach ($models as $model) {
if($mCounter == (count($models)-1)) {
$f = $this->{$model}->find('all',
['order' => [$model.'.id' => 'ASC']
])->first();
$this->log($f, LOG_DEBUG);
$this->Acl->allow([$model => ['id' => $f->id]], 'controllers');
$this->Flash->success(__("Granted permissions to {0} with id {1}", $model, (int)$f->id));
}
$mCounter++;
}
$this->Flash->success(__("Congratulations! Everything has been restored by default!"));
$this->redirect(["action" => "index"]);
}
|
Delete everything (ACOs and AROs)
TODO: Check $stmt->errorInfo();
|
entailment
|
private function _evaluate_permissions($permKeys, $aro, $aco, $aco_index) {
$this->acoId = $aco['Aco']['id'];
$result = $this->Acl->Aro->find('all', [
'contain' => ['Permissions' => function ($q) {
return $q->where(['aco_id' => $this->acoId]);
}
],
'conditions' => [
'model' => $aro['alias'],
'foreign_key' => $aro['id']
]
])->toArray();
$permissions = array_shift($result);
$permissions = array_shift($permissions->permissions);
$allowed = false;
$inherited = false;
$inheritedPerms = array();
$allowedPerms = array();
/**
* Manually checking permission
* Part of this logic comes from DbAcl::check()
*/
foreach ($permKeys as $key) {
if (!empty($permissions)) {
if ($permissions[$key] == '-1') {
$allowed = false;
break;
} elseif ($permissions[$key] == '1') {
$allowed = true;
$allowedPerms[$key] = 1;
} elseif ($permissions[$key] == '0') {
$inheritedPerms[$key] = 0;
}
} else {
$inheritedPerms[$key] = 0;
}
}
if (count($allowedPerms) === count($permKeys)) {
$allowed = true;
} elseif (count($inheritedPerms) === count($permKeys)) {
if ($aco['Aco']['parent_id'] == null) {
$this->lookup +=1;
$acoNode = (isset($aco['Action'])) ? $aco['Action'] : null;
$aroNode = array('model' => $aro['alias'], 'foreign_key' => $aro['id']);
$allowed = $this->Acl->check($aroNode, $acoNode);
$this->acos[$aco_index]['evaluated'][$aro['id']] = array(
'allowed' => $allowed,
'inherited' => true
);
} else {
/**
* Do not use Set::extract here. First of all it is terribly slow,
* besides this we need the aco array index ($key) to cache are result.
*/
foreach ($this->acos as $key => $a) {
if ($a['Aco']['id'] == $aco['Aco']['parent_id']) {
$parent_aco = $a;
break;
}
}
// Return cached result if present
if (isset($parent_aco['evaluated'][$aro['id']])) {
return $parent_aco['evaluated'][$aro['id']];
}
// Perform lookup of parent aco
$evaluate = $this->_evaluate_permissions($permKeys, $aro, $parent_aco, $key);
// Store result in acos array so we need less recursion for the next lookup
$this->acos[$key]['evaluated'][$aro['id']] = $evaluate;
$this->acos[$key]['evaluated'][$aro['id']]['inherited'] = true;
$allowed = $evaluate['allowed'];
}
$inherited = true;
}
return array(
'allowed' => $allowed,
'inherited' => $inherited,
);
}
|
Recursive function to find permissions avoiding slow $this->Acl->check().
|
entailment
|
protected function _getKeys() {
$keys = $this->Permissions->schema()->columns();
$newKeys = array();
foreach ($keys as $key) {
if (!in_array($key, array('id', 'aro_id', 'aco_id'))) {
$newKeys[] = $key;
}
}
return $newKeys;
}
|
Returns permissions keys in Permission schema
@see DbAcl::_getKeys()
|
entailment
|
protected function _getAcos() {
$acos = $this->Acl->Aco->find('all', array('order' => 'Acos.lft ASC', 'recursive' => -1))->toArray();
$parents = array();
foreach ($acos as $key => $data) {
$aco = & $acos[$key];
$aco = $aco->toArray();
$id = $aco['id'];
// Generate path
if ($aco['parent_id'] && isset($parents[$aco['parent_id']])) {
$parents[$id] = $parents[$aco['parent_id']] . '/' . $aco['alias'];
} else {
$parents[$id] = $aco['alias'];
}
$aco['action'] = $parents[$id];
}
return $acos;
}
|
Returns all the ACOs including their path
|
entailment
|
private function _parseAcos($acos) {
$cache = [];
foreach ($acos as $aco) {
$data['Aco'] = [
'id' => $aco->id,
'parent_id' => $aco->parent_id,
'foreign_key' => $aco->foreign_key,
'alias' => $aco->alias,
'lft' => $aco->lft,
'rght' => $aco->rght,
];
if (isset($aco->model)) {
$data['Aco']['model'] = $aco->model;
}
$d = [];
foreach ($aco['aros'] as $aro) {
$d[] = [
'id' => $aro->id,
'parent_id' => $aro->parent_id,
'model' => $aro->model,
'foreign_key' => $aro->foreign_key,
'alias' => $aro->alias,
'lft' => $aro->lft,
'rght' => $aro->rght,
'Permission' => [
'aro_id' => $aro->_joinData->aro_id,
'id' => $aro->_joinData->id,
'aco_id' => $aro->_joinData->aco_id,
'_create' => $aro->_joinData->_create,
'_read' => $aro->_joinData->_read,
'_update' => $aro->_joinData->_update,
'_delete' => $aro->_joinData->_delete,
]
];
}
$data['Aro'] = $d;
array_push($cache, $data);
}
return $cache;
}
|
Returns an array with acos
@param Acos $acos Parse Acos entities and store into array formated
@return array
|
entailment
|
private function _parseAros($aros) {
$cache = array();
foreach ($aros as $aro) {
$data[$this->model] = $aro;
array_push($cache, $data);
}
return $cache;
}
|
Returns an array with aros
@param Aros $aros Parse Aros entities and store into an array.
@return array
|
entailment
|
public function check($aro, $aco) {
if (empty($aro) || empty($aco)) {
return false;
}
return $this->Acl->check($aro, $aco);
}
|
Check if the User have access to the aco
@param \App\Model\Entity\User $aro The Aro of the user you want to check
@param string $aco The path of the Aco like App/Blog/add
@return bool
|
entailment
|
public function value($value = NULL) {
if($value == NULL) {
return false;
}
$o = explode('.',$value);
$data = $this->request->data;
return $data[$o[0]][$o[1]][$o[2]];
}
|
Return value from permissions input
@param string $value
@return boolean
|
entailment
|
public function startup($controller = null)
{
if (!$controller) {
$controller = new Controller(new Request());
}
$registry = new ComponentRegistry();
$this->Acl = new AclComponent($registry, Configure::read('Acl'));
$this->Aco = $this->Acl->Aco;
$this->controller = $controller;
$this->_buildPrefixes();
$this->_processIgnored();
}
|
Start up And load Acl Component / Aco model
@param \Cake\Controller\Controller $controller Controller instance
@return void
|
entailment
|
public function out($msg)
{
if (!empty($this->controller->Flash)) {
$this->controller->Flash->success($msg);
} else {
$this->Shell->out($msg);
}
}
|
Output a message.
Will either use shell->out, or controller->Flash->success()
@param string $msg The message to output.
@return void
|
entailment
|
public function err($msg)
{
if (!empty($this->controller->Flash)) {
$this->controller->Flash->error($msg);
} else {
$this->Shell->err($msg);
}
}
|
Output an error message.
Will either use shell->err, or controller->Flash->error()
@param string $msg The message to output.
@return void
|
entailment
|
public function acoUpdate($params = [])
{
$root = $this->_checkNode($this->rootNode, $this->rootNode, null);
if (empty($params['plugin'])) {
$plugins = Plugin::loaded();
$this->_processControllers($root);
$this->_processPrefixes($root);
$this->_processPlugins($root, $plugins);
// debug($this->foundACOs);
} else {
$plugin = $params['plugin'];
if (!Plugin::loaded($plugin)) {
$this->err(__d('cake_acl', "Plugin {0} not found or not activated.", [$plugin]));
return false;
}
$plugins = [$params['plugin']];
$this->_processPlugins($root, $plugins);
$this->foundACOs = array_slice($this->foundACOs, 1, null, true);
}
if ($this->_clean) {
foreach ($this->foundACOs as $parentId => $acosList) {
$this->_cleaner($parentId, $acosList);
}
}
$this->out(__d('cake_acl', '{0} ACOs have been created, updated or deleted', (int)$this->counter));
// $this->out(__d('cake_acl', 'ACOs update complete'));
// die();
return true;
}
|
Updates the Aco Tree with new controller actions.
@param array $params An array of parameters
@return bool
|
entailment
|
protected function _processControllers($root)
{
$controllers = $this->getControllerList();
$this->foundACOs[$root->id] = $this->_updateControllers($root, $controllers);
}
|
Updates the Aco Tree with all App controllers.
@param \Acl\Model\Entity\Aco $root The root note of Aco Tree
@return void
|
entailment
|
protected function _processPrefixes($root)
{
foreach (array_keys($this->prefixes) as $prefix) {
$controllers = $this->getControllerList(null, $prefix);
$path = $this->rootNode . '/' . $prefix;
$pathNode = $this->_checkNode($path, $prefix, $root->id);
$this->foundACOs[$root->id][] = $prefix;
if (isset($this->foundACOs[$pathNode->id])) {
$this->foundACOs[$pathNode->id] += $this->_updateControllers($pathNode, $controllers, null, $prefix);
} else {
$this->foundACOs[$pathNode->id] = $this->_updateControllers($pathNode, $controllers, null, $prefix);
}
}
}
|
Updates the Aco Tree with all App route prefixes.
@param \Acl\Model\Entity\Aco $root The root note of Aco Tree
@return void
|
entailment
|
protected function _processPlugins($root, array $plugins = [])
{
foreach ($plugins as $plugin) {
$controllers = $this->getControllerList($plugin);
$pluginAlias = $this->_pluginAlias($plugin);
$path = [
$this->rootNode,
$pluginAlias
];
$path = implode('/', Hash::filter($path));
if(!in_array($path, $this->ignorePaths) && !in_array($path, $this->ignoreActions)) {
$pathNode = $this->_checkNode($path, $pluginAlias, $root->id);
$this->foundACOs[$root->id][] = $pluginAlias;
if (isset($this->foundACOs[$pathNode->id])) {
$this->foundACOs[$pathNode->id] += $this->_updateControllers($pathNode, $controllers, $plugin);
} else {
$this->foundACOs[$pathNode->id] = $this->_updateControllers($pathNode, $controllers, $plugin);
}
if (isset($this->pluginPrefixes[$plugin])) {
foreach (array_keys($this->pluginPrefixes[$plugin]) as $prefix) {
$path = [
$this->rootNode,
$pluginAlias
];
$path = implode('/', Hash::filter($path));
$pluginNode = $this->_checkNode($path, $pluginAlias, $root->id);
$this->foundACOs[$root->id][] = $pluginAlias;
$path = [
$this->rootNode,
$pluginAlias,
$prefix,
];
$path = implode('/', Hash::filter($path));
$pathNode = $this->_checkNode($path, $prefix, $pluginNode->id);
$this->foundACOs[$pluginNode->id][] = $prefix;
$controllers = $this->getControllerList($plugin, $prefix);
if (isset($this->foundACOs[$pathNode->id])) {
$this->foundACOs[$pathNode->id] += $this->_updateControllers($pathNode, $controllers, $pluginAlias, $prefix);
} else {
$this->foundACOs[$pathNode->id] = $this->_updateControllers($pathNode, $controllers, $pluginAlias, $prefix);
}
}
}
}
}
}
|
Updates the Aco Tree with all Plugins.
@param \Acl\Model\Entity\Aco $root The root note of Aco Tree
@param array $plugins list of App plugins
@return void
|
entailment
|
protected function _updateControllers($root, $controllers, $plugin = null, $prefix = null)
{
$pluginPath = $this->_pluginAlias($plugin);
// look at each controller
$controllersNames = [];
foreach ($controllers as $controller) {
$tmp = explode('/', $controller);
$controllerName = str_replace('Controller.php', '', array_pop($tmp));
if ($controllerName == 'App') {
continue;
}
$controllersNames[] = $controllerName;
$path = [
$this->rootNode,
$pluginPath,
$prefix,
$controllerName
];
$path = implode('/', Hash::filter($path));
if(!in_array($path, $this->ignorePaths)) {
$controllerNode = $this->_checkNode($path, $controllerName, $root->id);
$this->_checkMethods($controller, $controllerName, $controllerNode, $pluginPath, $prefix);
}
}
return $controllersNames;
}
|
Updates a collection of controllers.
@param array $root Array or ACO information for root node.
@param array $controllers Array of Controllers
@param string $plugin Name of the plugin you are making controllers for.
@param string $prefix Name of the prefix you are making controllers for.
@return array
|
entailment
|
public function getControllerList($plugin = null, $prefix = null)
{
if (!$plugin) {
$path = App::path('Controller' . (empty($prefix) ? '' : DS . Inflector::camelize($prefix)));
$dir = new Folder($path[0]);
$controllers = $dir->find('.*Controller\.php');
} else {
$path = App::path('Controller' . (empty($prefix) ? '' : DS . Inflector::camelize($prefix)), $plugin);
$dir = new Folder($path[0]);
$controllers = $dir->find('.*Controller\.php');
}
return $controllers;
}
|
Get a list of controllers in the app and plugins.
Returns an array of path => import notation.
@param string $plugin Name of plugin to get controllers for
@param string $prefix Name of prefix to get controllers for
@return array
|
entailment
|
protected function _checkNode($path, $alias, $parentId = null)
{
$node = $this->Aco->node($path);
if (!$node) {
$data = [
'parent_id' => $parentId,
'model' => null,
'alias' => $alias,
];
$entity = $this->Aco->newEntity($data);
$node = $this->Aco->save($entity);
$this->counter++;
// $this->out(__d('cake_acl', 'Created Aco node: {0}', $path));
} else {
$node = $node->first();
}
return $node;
}
|
Check a node for existance, create it if it doesn't exist.
@param string $path The path to check
@param string $alias The alias to create
@param int $parentId The parent id to use when creating.
@return array Aco Node array
|
entailment
|
protected function _getCallbacks($className, $pluginPath = null, $prefixPath = null)
{
$callbacks = [];
$namespace = $this->_getNamespace($className, $pluginPath, $prefixPath);
$reflection = new \ReflectionClass($namespace);
if ($reflection->isAbstract()) {
return $callbacks;
}
try {
$method = $reflection->getMethod('implementedEvents');
} catch (ReflectionException $e) {
return $callbacks;
}
if (version_compare(phpversion(), '5.4', '>=')) {
$object = $reflection->newInstanceWithoutConstructor();
} else {
$object = unserialize(
sprintf('O:%d:"%s":0:{}', strlen($className), $className)
);
}
$implementedEvents = $method->invoke($object);
foreach ($implementedEvents as $event => $callable) {
if (is_string($callable)) {
$callbacks[] = $callable;
}
if (is_array($callable) && isset($callable['callable'])) {
$callbacks[] = $callable['callable'];
}
}
return $callbacks;
}
|
Get a list of registered callback methods
@param string $className The class to reflect on.
@param string $pluginPath The plugin path.
@param string $prefixPath The prefix path.
@return array
|
entailment
|
protected function _checkMethods($className, $controllerName, $node, $pluginPath = null, $prefixPath = null)
{
$excludes = $this->_getCallbacks($className, $pluginPath, $prefixPath);
if(Configure::check('AclManager.ignoreActions')) {
$ignore = Configure::read('AclManager.ignoreActions');
$excludes = array_merge($excludes, $this->ignoreActions);
}
$baseMethods = get_class_methods(new Controller);
$namespace = $this->_getNamespace($className, $pluginPath, $prefixPath);
$methods = get_class_methods(new $namespace);
if ($methods == null) {
$this->err(__d('cake_acl', 'Unable to get methods for {0}', $className));
return false;
}
$actions = array_diff($methods, $baseMethods);
$actions = array_diff($actions, $excludes);
foreach ($actions as $key => $action) {
if (strpos($action, '_', 0) === 0) {
continue;
}
$path = [
$this->rootNode,
$pluginPath,
$prefixPath,
$controllerName,
$action
];
$path = implode('/', Hash::filter($path));
if(!in_array($path, $this->ignorePaths) && !in_array($action, $this->ignoreActions)) {
$this->_checkNode($path, $action, $node->id);
$actions[$key] = $action;
}
}
if ($this->_clean) {
$this->_cleaner($node->id, $actions);
}
return true;
}
|
Check and Add/delete controller Methods
@param string $className The classname to check
@param string $controllerName The controller name
@param array $node The node to check.
@param string $pluginPath The plugin path to use.
@param string $prefixPath The prefix path to use.
@return bool
|
entailment
|
public function recover()
{
$type = Inflector::camelize($this->args[0]);
$this->Acl->{$type}->recover();
$this->out(__('Tree has been recovered, or tree did not need recovery.'));
}
|
Recover an Acl Tree
@return void
|
entailment
|
protected function _getNamespace($className, $pluginPath = null, $prefixPath = null)
{
$namespace = preg_replace('/(.*)Controller\//', '', $className);
$namespace = preg_replace('/\//', '\\', $namespace);
$namespace = preg_replace('/\.php/', '', $namespace);
$prefixPath = preg_replace('/\//', '\\', Inflector::camelize($prefixPath));
if (!$pluginPath) {
$rootNamespace = Configure::read('App.namespace');
} else {
$rootNamespace = preg_replace('/\//', '\\', $pluginPath);
}
$namespace = [
$rootNamespace,
'Controller',
$prefixPath,
$namespace
];
return implode('\\', Hash::filter($namespace));
}
|
Get the namespace for a given class.
@param string $className The class you want a namespace for.
@param string $pluginPath The plugin path.
@param string $prefixPath The prefix path.
@return string
|
entailment
|
protected function _buildPrefixes()
{
$routes = Router::routes();
foreach ($routes as $key => $route) {
if (isset($route->defaults['prefix'])) {
$prefix = Inflector::camelize($route->defaults['prefix']);
if (!isset($route->defaults['plugin'])) {
$this->prefixes[$prefix] = true;
} else {
$this->pluginPrefixes[$route->defaults['plugin']][$prefix] = true;
}
}
}
}
|
Build prefixes for App and Plugins based on configured routes
@return void
|
entailment
|
protected function _cleaner($parentId, $preservedItems = [])
{
$nodes = $this->Aco->find()->where(['parent_id' => $parentId]);
$methodFlip = array_flip($preservedItems);
foreach ($nodes as $node) {
if (!isset($methodFlip[$node->alias])) {
$crumbs = $this->Aco->find('path', ['for' => $node->id, 'order' => 'lft']);
$path = null;
foreach ($crumbs as $crumb) {
$path .= '/' . $crumb->alias;
}
$entity = $this->Aco->get($node->id);
if ($this->Aco->delete($entity)) {
$this->out(__d('cake_acl', 'Deleted ACO node: <warning>{0}</warning> and all children', $path));
}
}
}
}
|
Delete unused ACOs.
@param int $parentId Id of the parent node.
@param array $preservedItems list of items that will not be erased.
@return void
|
entailment
|
public function parameterize($method)
{
$parameterArray = array();
switch ($method) {
case 'create':
if (!is_null($this->getPreauthorization())) {
$parameterArray['preauthorization'] = $this->getPreauthorization();
} elseif (!is_null($this->getPayment())) {
$parameterArray['payment'] = $this->getPayment();
} else {
$parameterArray['token'] = $this->getToken();
}
$parameterArray['amount'] = $this->getAmount();
$parameterArray['currency'] = $this->getCurrency();
$parameterArray['description'] = $this->getDescription();
$parameterArray['client'] = $this->getClient();
if (!is_null($this->getFeeAmount())) {
$parameterArray['fee_amount'] = $this->getFeeAmount();
}
if (!is_null($this->getFeePayment())) {
$parameterArray['fee_payment'] = $this->getFeePayment();
}
if (!is_null($this->getFeeCurrency())) {
$parameterArray['fee_currency'] = $this->getFeeCurrency();
}
if(!is_null($this->getSource())) {
$parameterArray['source'] = $this->getSource();
}
if(!is_null($this->getShippingAddress())) {
$parameterArray['shipping_address'] = $this->getShippingAddress();
}
if(!is_null($this->getBillingAddress())) {
$parameterArray['billing_address'] = $this->getBillingAddress();
}
if(!is_null($this->getItems())) {
$parameterArray['items'] = $this->getItems();
}
if(!is_null($this->getShippingAmount())) {
$parameterArray['shipping_amount'] = $this->getShippingAmount();
}
if(!is_null($this->getHandlingAmount())) {
$parameterArray['handling_amount'] = $this->getHandlingAmount();
}
if (!is_null($this->getMandateReference())) {
$parameterArray['mandate_reference'] = $this->getMandateReference();
}
if(!is_null($this->getShippingAddress())) {
$parameterArray['shipping_address'] = $this->getShippingAddress();
}
if(!is_null($this->getBillingAddress())) {
$parameterArray['billing_address'] = $this->getBillingAddress();
}
break;
case 'update':
$parameterArray['description'] = $this->getDescription();
break;
case 'getAll':
$parameterArray = $this->getFilter();
break;
case 'getOne':
$parameterArray['count'] = 1;
$parameterArray['offset'] = 0;
break;
case 'delete':
break;
}
return $parameterArray;
}
|
Returns an array of parameters customized for the given method name.
@param string $method Method
@return array
|
entailment
|
public function setSubscriptionCount($active, $inactive)
{
$this->_subscriptionCount['active'] = $active;
$this->_subscriptionCount['inactive'] = $inactive;
return $this;
}
|
Sets the subscriptionCount array
@param string|integer $active
@param string|integer $inactive
@return \Paymill\Models\Response\Offer
|
entailment
|
public function parameterize($method)
{
$parameterArray = parent::parameterize($method);
if ('create' == $method) {
if($this->getChecksumAction()) {
$parameterArray['checksum_action'] = $this->getChecksumAction();
}
if($this->getShippingAddress()) {
$parameterArray['shipping_address'] = $this->getShippingAddress();
}
if($this->getBillingAddress()) {
$parameterArray['billing_address'] = $this->getBillingAddress();
}
if($this->getItems()) {
$parameterArray['items'] = $this->getItems();
}
if($this->getShippingAmount()) {
$parameterArray['shipping_amount'] = $this->getShippingAmount();
}
if($this->getHandlingAmount()) {
$parameterArray['handling_amount'] = $this->getHandlingAmount();
}
if($this->getRequireReusablePayment()) {
$parameterArray['require_reusable_payment'] = $this->getRequireReusablePayment();
}
if($this->getReusablePaymentDescription()) {
$parameterArray['reusable_payment_description'] = $this->getReusablePaymentDescription();
}
}
return $parameterArray;
}
|
Converts the model into an array to prepare method calls
@param string $method should be used for handling the required parameter
@return array
|
entailment
|
public function getJSONObject(){
$result = false;
$responseHandler = new ResponseHandler();
if(is_array($this->_lastResponse)){
$result = $responseHandler->arrayToObject($this->_lastResponse['body']);
}
return $result;
}
|
Returns the LastResponse as StdClassObject. Returns false if no request was made earlier.
@return false | stdClass
|
entailment
|
private function _request(Base $model, $method)
{
if(!is_a($this->_connectionClass, '\Paymill\API\CommunicationAbstract')){
throw new PaymillException(null,'The connection class is missing!');
}
$convertedResponse = null;
$httpMethod = $this->_getHTTPMethod($method);
$parameter = $model->parameterize($method);
$serviceResource = $model->getServiceResource() . $model->getId();
if ((is_a($model, '\Paymill\Models\Request\Transaction')
|| is_a($model, '\Paymill\Models\Request\Preauthorization'))
&& $method === "create"
) {
$source = !array_key_exists('source', $parameter) ?
"PhpLib" . $this->getVersion() :
"PhpLib" . $this->getVersion() . "_" . $parameter['source'];
$parameter['source'] = $source;
}
try {
$this->_lastRequest = $parameter;
$response = $this->_connectionClass->requestApi(
$serviceResource, $parameter, $httpMethod
);
$this->_lastResponse = $response;
$responseHandler = new ResponseHandler();
if($method === "getAllAsModel"
&& $responseHandler->validateResponse($response)
&& $this->_util->isNumericArray($response['body']['data'])
) {
foreach($response['body']['data'] as $object){
$convertedResponse[] = $responseHandler->convertResponse($object, $model->getServiceResource());
}
} elseif($method === "getAll" && $responseHandler->validateResponse($response)) {
$convertedResponse = $response['body']['data'];
} elseif($responseHandler->validateResponse($response)) {
$convertedResponse = $responseHandler->convertResponse(
$response['body']['data'], $model->getServiceResource()
);
} else {
$convertedResponse = $responseHandler->convertErrorToModel($response, $model->getServiceResource());
}
} catch (Exception $e) {
$errorModel = new Error();
$convertedResponse = $errorModel->setErrorMessage($e->getMessage());
}
if (is_a($convertedResponse, '\Paymill\Models\Response\Error')) {
throw new PaymillException(
$convertedResponse->getResponseCode(),
$convertedResponse->getErrorMessage(),
$convertedResponse->getHttpStatusCode(),
$convertedResponse->getRawObject(),
$convertedResponse->getErrorResponseArray()
);
}
return $convertedResponse;
}
|
Sends a request based on the provided request model and according to the argumented method
@param \Paymill\Models\Request\Base $model
@param string $method (Create, update, delete, getAll, getOne)
@throws PaymillException
@return \Paymill\Models\Response\Base|\Paymill\Models\Response\Error
|
entailment
|
public function requestApi($action = '', $params = array(), $method = 'POST')
{
$curlOpts = array(
CURLOPT_URL => $this->_apiUrl . $action,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_USERAGENT => 'Paymill-php/0.0.2',
CURLOPT_SSL_VERIFYPEER => true
);
// Add extra options to cURL if defined.
if (!empty($this->_extraOptions)) {
$curlOpts = $this->_extraOptions + $curlOpts;
}
if ('GET' === $method || 'DELETE' === $method) {
if (0 !== count($params)) {
$curlOpts[CURLOPT_URL] .= false === strpos($curlOpts[CURLOPT_URL], '?') ? '?' : '&';
$curlOpts[CURLOPT_URL] .= http_build_query($params, null, '&');
}
} else {
$curlOpts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
if ($this->_apiKey) {
$curlOpts[CURLOPT_USERPWD] = $this->_apiKey . ':';
}
$curl = curl_init();
$this->_curlOpts($curl, $curlOpts);
$responseBody = $this->_curlExec($curl);
$responseInfo = $this->_curlInfo($curl);
if ($responseBody === false) {
$responseBody = array('error' => $this->_curlError($curl));
}
curl_close($curl);
if ('application/json' === $responseInfo['content_type']) {
$responseBody = json_decode($responseBody, true);
} elseif (strpos(strtolower($responseInfo['content_type']), 'text/csv') !== false
&& !isset($responseBody['error'])
) {
return $responseBody;
}
$result = array(
'header' => array(
'status' => $responseInfo['http_code'],
'reason' => null,
),
'body' => $responseBody
);
return $result;
}
|
Perform HTTP request to REST endpoint
@param string $action
@param array $params
@param string $method
@return array
|
entailment
|
public function convertResponse($response, $serviceResource)
{
$resourceName = substr($serviceResource, 0, -2);
return $this->_convertResponseToModel($response, $resourceName);
}
|
Converts a response to a model
@param array $response
@param string $serviceResource
@return Base|Error
|
entailment
|
private function _convertResponseToModel($response, $resourceName)
{
if (!is_array($response) || empty($response)) {
return $response;
}
$model = null;
switch (strtolower($resourceName)) {
case 'client':
$model = $this->_createClient($response);
break;
case 'payment':
$model = $this->_createPayment($response);
break;
case 'transaction':
$model = $this->_createTransaction($response);
break;
case 'preauthorization':
if (isset($response['preauthorization'])) {
$response = $response['preauthorization'];
}
$model = $this->_createPreauthorization($response);
break;
case 'refund':
$model = $this->_createRefund($response);
break;
case 'offer':
$model = $this->_createOffer($response);
break;
case 'subscription':
$model = $this->_createSubscription($response);
break;
case 'webhook':
$model = $this->_createWebhook($response);
break;
case 'fraud':
$model = $this->_createFraud($response);
break;
case 'checksum':
$model = $this->_createChecksum($response);
break;
case AbstractAddress::TYPE_SHIPPING:
$model = $this->_createAddress($response, AbstractAddress::TYPE_SHIPPING);
break;
case AbstractAddress::TYPE_BILLING:
$model = $this->_createAddress($response, AbstractAddress::TYPE_BILLING);
break;
case 'item':
$model = $this->_createItem($response);
break;
}
return $model;
}
|
Creates an object from a response array based on the call-context
@param array $response Response from any Request
@param string $resourceName
@return Base
|
entailment
|
private function _createClient(array $response)
{
$model = new Client();
$model->setId($response['id']);
$model->setEmail($response['email']);
$model->setDescription($response['description']);
$model->setCreatedAt($response['created_at']);
$model->setUpdatedAt($response['updated_at']);
$model->setSubscription($this->_handleRecursive($response['subscription'], 'subscription'));
$model->setAppId($response['app_id']);
$model->setPayment($this->_handleRecursive($response['payment'], 'payment'));
return $model;
}
|
Creates and fills a client model
@param array $response
@return Client
|
entailment
|
private function _createPayment(array $response)
{
$model = new Payment();
$model->setId($response['id']);
$model->setType($response['type']);
$model->setClient($this->_convertResponseToModel($response['client'], "client"));
if ($response['type'] === "creditcard") {
$model->setCardType($response['card_type']);
$model->setCountry($response['country']);
$model->setExpireMonth($response['expire_month']);
$model->setExpireYear($response['expire_year']);
$model->setCardHolder($response['card_holder']);
$model->setLastFour($response['last4']);
} elseif ($response['type'] === "debit") {
$model->setHolder($response['holder']);
$model->setCode($response['code']);
$model->setAccount($response['account']);
$model->setBic($response['bic']);
$model->setIban($response['iban']);
} elseif ($response['type'] === "paypal") {
$model->setHolder($response['holder']);
$model->setAccount($response['account']);
}
$model->setCreatedAt($response['created_at']);
$model->setUpdatedAt($response['updated_at']);
$model->setAppId($response['app_id']);
return $model;
}
|
Creates and fills a payment model
@param array $response
@return Payment
|
entailment
|
private function _createTransaction(array $response)
{
$model = new Transaction();
$model->setId($response['id']);
$model->setAmount($response['amount']);
$model->setOriginAmount($response['origin_amount']);
$model->setStatus($response['status']);
$model->setDescription($response['description']);
$model->setLivemode($response['livemode']);
$model->setRefunds($this->_handleRecursive($response['refunds'], 'refund'));
$model->setCurrency($response['currency']);
$model->setCreatedAt($response['created_at']);
$model->setUpdatedAt($response['updated_at']);
$model->setResponseCode($response['response_code']);
$model->setShortId($response['short_id']);
$model->setInvoices($response['invoices']);
$model->setPayment($this->_convertResponseToModel($response['payment'], "payment"));
$model->setClient($this->_convertResponseToModel($response['client'], "client"));
$model->setPreauthorization($this->_convertResponseToModel($response['preauthorization'], "preauthorization"));
$model->setFees($response['fees']);
$model->setAppId($response['app_id']);
if (isset($response[Transaction::RESPONSE_FIELD_SHIPPING_ADDRESS])) {
$model->setShippingAddress(
$this->_convertResponseToModel(
$response[Transaction::RESPONSE_FIELD_SHIPPING_ADDRESS],
AbstractAddress::TYPE_SHIPPING
)
);
}
if (isset($response[Transaction::RESPONSE_FIELD_BILLING_ADDRESS])) {
$model->setBillingAddress(
$this->_convertResponseToModel(
$response[Transaction::RESPONSE_FIELD_BILLING_ADDRESS],
AbstractAddress::TYPE_BILLING
)
);
}
if (isset($response[Transaction::RESPONSE_FIELD_ITEMS])) {
$model->setItems($this->_handleRecursive($response[Transaction::RESPONSE_FIELD_ITEMS], 'item'));
}
return $model;
}
|
Creates and fills a transaction model
@param array $response
@return Transaction
|
entailment
|
private function _createPreauthorization($response)
{
$model = new Preauthorization();
$model->setId($response['id']);
$model->setAmount($response['amount']);
$model->setCurrency($response['currency']);
$model->setStatus($response['status']);
$model->setLivemode($response['livemode']);
$model->setCreatedAt($response['created_at']);
$model->setUpdatedAt($response['updated_at']);
$model->setPayment($this->_convertResponseToModel($response['payment'], "payment"));
$model->setClient($this->_convertResponseToModel($response['client'], "client"));
$model->setTransaction(isset($response['transaction']) ? $this->_convertResponseToModel($response['transaction'], 'transaction') : null);
$model->setAppId($response['app_id']);
$model->setDescription($response['description']);
return $model;
}
|
Creates and fills a preauthorization model
@param array $response
@return Preauthorization
|
entailment
|
private function _createRefund(array $response)
{
$model = new Refund();
$model->setId($response['id']);
$model->setAmount($response['amount']);
$model->setStatus($response['status']);
$model->setDescription($response['description']);
$model->setLivemode($response['livemode']);
$model->setCreatedAt($response['created_at']);
$model->setUpdatedAt($response['updated_at']);
$model->setResponseCode($response['response_code']);
//Refund doesn't have the array index 'transaction' when using getOne
$model->setTransaction(isset($response['transaction']) ? $this->_convertResponseToModel($response['transaction'], 'transaction') : null);
$model->setAppId($response['app_id']);
return $model;
}
|
Creates and fills a refund model
@param array $response
@return Refund
|
entailment
|
private function _createOffer(array $response)
{
$model = new Offer();
$model->setId($response['id']);
$model->setName($response['name']);
$model->setAmount($response['amount']);
$model->setCurrency($response['currency']);
$model->setInterval($response['interval']);
$model->setTrialPeriodDays($response['trial_period_days']);
$model->setCreatedAt($response['created_at']);
$model->setUpdatedAt($response['updated_at']);
$model->setSubscriptionCount($response['subscription_count']['active'], $response['subscription_count']['inactive']);
$model->setAppId($response['app_id']);
return $model;
}
|
Creates and fills a offer model
@param array $response
@return Offer
|
entailment
|
private function _createSubscription(array $response)
{
$model = new Subscription();
$model->setId($response['id']);
$model->setOffer($this->_convertResponseToModel($response['offer'], 'offer'));
$model->setLivemode($response['livemode']);
$model->setTrialStart($response['trial_start']);
$model->setTrialEnd($response['trial_end']);
$model->setPeriodOfValidity($response['period_of_validity']);
$model->setEndOfPeriod($response['end_of_period']);
$model->setNextCaptureAt($response['next_capture_at']);
$model->setCreatedAt($response['created_at']);
$model->setUpdatedAt($response['updated_at']);
$model->setCanceledAt($response['canceled_at']);
$model->setPayment($this->_convertResponseToModel($response['payment'], "payment"));
$model->setClient($this->_convertResponseToModel($response['client'], "client"));
$model->setAppId($response['app_id']);
$model->setIsCanceled($response['is_canceled']);
$model->setIsDeleted($response['is_deleted']);
$model->setStatus($response['status']);
$model->setAmount($response['amount']);
$model->setTempAmount($response['temp_amount']);
return $model;
}
|
Creates and fills a subscription model
@param array $response
@return Subscription
|
entailment
|
private function _createWebhook(array $response)
{
$model = new Webhook();
$model->setId($response['id']);
isset($response['url']) ? $model->setUrl($response['url']) : $model->setEmail($response['email']);
$model->setLivemode($response['livemode']);
$model->setEventTypes($response['event_types']);
$model->setCreatedAt($response['created_at']);
$model->setUpdatedAt($response['updated_at']);
$model->setAppId($response['app_id']);
$model->setActive($response['active']);
return $model;
}
|
Creates and fills a webhook model
@param array $response
@return Webhook
|
entailment
|
private function _createFraud(array $response)
{
$model = new Fraud();
$model->setId($response['id']);
$model->setLivemode($response['livemode']);
$model->setStatus($response['status']);
$model->setCreatedAt($response['created_at']);
$model->setUpdatedAt($response['updated_at']);
return $model;
}
|
Creates and fills a fraud model
@param array $response
@return Fraud
|
entailment
|
private function _createChecksum(array $response)
{
$model = new Checksum();
$model->setId($response['id']);
$model->setChecksum($response['checksum']);
$model->setData($response['data']);
$model->setType($response['type']);
$model->setAction($response['action']);
$model->setAppId($response['app_id']);
$model->setCreatedAt($response['created_at']);
$model->setUpdatedAt($response['updated_at']);
return $model;
}
|
Creates and fills a checksum model
@param array $response
@return Checksum
|
entailment
|
private function _createItem(array $response)
{
$model = new Item();
$model->setName($response[Item::FIELD_NAME])
->setDescription($response[Item::FIELD_DESCRIPTION])
->setItemNumber($response[Item::FIELD_ITEM_NUMBER])
->setUrl($response[Item::FIELD_URL])
->setAmount($response[Item::FIELD_AMOUNT])
->setQuantity($response[Item::FIELD_QUANTITY]);
return $model;
}
|
Creates and fills an item model.
@param array $response
@return Item
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.