sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function getBaseDatagrid(AdminInterface $admin, array $values = []) { // Check if we use smart or original datagrid builder $smartDatagrid = $this->smartDatagridBuilder->isSmart($admin, $values); return $this->getAdminDatagridBuilder($admin, $smartDatagrid)->getBaseDatagrid($admin, $values); }
{@inheritdoc}
entailment
public function filter(ProxyQueryInterface $query, $alias, $field, $data) { if (!$data || !\is_array($data) || !\array_key_exists('type', $data) || !\array_key_exists('value', $data)) { return; } $data['type'] = !isset($data['type']) ? ChoiceType::TYPE_CONTAINS : $data['type']; list($firstOperator, $secondOperator) = $this->getOperators((int) $data['type']); if (\is_array($data['value'])) { if (0 === \count($data['value'])) { return; } if (\in_array('all', $data['value'], true)) { return; } $queryBuilder = new \Elastica\Query\Builder(); $queryBuilder ->fieldOpen($secondOperator) ->field($field, Util::escapeTerm($data['value'])) ->fieldClose(); if ('must' === $firstOperator) { $query->addMust($queryBuilder); } else { $query->addMustNot($queryBuilder); } } else { if ('' === $data['value'] || null === $data['value'] || false === $data['value'] || 'all' === $data['value']) { return; } $queryBuilder = new \Elastica\Query\Builder(); $queryBuilder ->fieldOpen($secondOperator) ->field($field, Util::escapeTerm([$data['value']])) ->fieldClose(); if ('must' === $firstOperator) { $query->addMust($queryBuilder); } else { $query->addMustNot($queryBuilder); } } }
{@inheritdoc}
entailment
private function getOperators($type) { $choices = [ ChoiceType::TYPE_CONTAINS => ['must', 'terms'], ChoiceType::TYPE_NOT_CONTAINS => ['must_not', 'terms'], ]; return $choices[$type] ?? false; }
@param string $type @return bool
entailment
public function storeAccessToken(string $service, AccessToken $token):OAuthStorageInterface{ $token = $token->toJSON(); if(isset($_SESSION[$this->sessionVar]) && is_array($_SESSION[$this->sessionVar])){ $_SESSION[$this->sessionVar][$service] = $token; } else{ $_SESSION[$this->sessionVar] = [$service => $token]; } return $this; }
@param string $service @param \chillerlan\OAuth\Core\AccessToken $token @return \chillerlan\OAuth\Storage\OAuthStorageInterface
entailment
public function getAccessToken(string $service):AccessToken{ if($this->hasAccessToken($service)){ return (new AccessToken)->fromJSON($_SESSION[$this->sessionVar][$service]); } throw new OAuthStorageException('token not found'); }
@param string $service @return \chillerlan\OAuth\Core\AccessToken|\chillerlan\Settings\SettingsContainerInterface @throws \chillerlan\OAuth\Storage\OAuthStorageException
entailment
public function hasAccessToken(string $service):bool{ return isset($_SESSION[$this->sessionVar], $_SESSION[$this->sessionVar][$service]); }
@param string $service @return bool
entailment
public function clearAccessToken(string $service):OAuthStorageInterface{ if(array_key_exists($service, $_SESSION[$this->sessionVar])){ unset($_SESSION[$this->sessionVar][$service]); } return $this; }
@param string $service @return \chillerlan\OAuth\Storage\OAuthStorageInterface
entailment
public function storeCSRFState(string $service, string $state):OAuthStorageInterface{ if(isset($_SESSION[$this->stateVar]) && is_array($_SESSION[$this->stateVar])){ $_SESSION[$this->stateVar][$service] = $state; } else{ $_SESSION[$this->stateVar] = [$service => $state]; } return $this; }
@param string $service @param string $state @return \chillerlan\OAuth\Storage\OAuthStorageInterface
entailment
public function getCSRFState(string $service):string{ if($this->hasCSRFState($service)){ return $_SESSION[$this->stateVar][$service]; } throw new OAuthStorageException('state not found'); }
@param string $service @return string @throws \chillerlan\OAuth\Storage\OAuthStorageException
entailment
public function hasCSRFState(string $service):bool{ return isset($_SESSION[$this->stateVar], $_SESSION[$this->stateVar][$service]); }
@param string $service @return bool
entailment
public function clearCSRFState(string $service):OAuthStorageInterface{ if(array_key_exists($service, $_SESSION[$this->stateVar])){ unset($_SESSION[$this->stateVar][$service]); } return $this; }
@param string $service @return \chillerlan\OAuth\Storage\OAuthStorageInterface
entailment
public function guessType($class, $property, ModelManagerInterface $modelManager) { if (!$ret = $modelManager->getParentMetadataForProperty($class, $property, $modelManager)) { return false; } $options = [ 'field_type' => null, 'field_options' => [], 'options' => [], ]; list($metadata, $propertyName, $parentAssociationMappings) = $ret; $options['parent_association_mappings'] = $parentAssociationMappings; // FIXME: Try to implement association using elastica /* if ($metadata->hasAssociation($propertyName)) { $mapping = $metadata->getAssociationMapping($propertyName); switch ($mapping['type']) { case ClassMetadataInfo::ONE_TO_ONE: case ClassMetadataInfo::ONE_TO_MANY: case ClassMetadataInfo::MANY_TO_ONE: case ClassMetadataInfo::MANY_TO_MANY: $options['operator_type'] = 'sonata_type_equal'; $options['operator_options'] = array(); $options['field_type'] = 'entity'; $options['field_options'] = array( 'class' => $mapping['targetEntity'] ); $options['field_name'] = $mapping['fieldName']; $options['mapping_type'] = $mapping['type']; return new TypeGuess('doctrine_orm_model', $options, Guess::HIGH_CONFIDENCE); } }*/ $options['field_name'] = $metadata->fieldMappings[$propertyName]['fieldName']; switch ($metadata->getTypeOfField($propertyName)) { case 'boolean': $options['field_type'] = 'sonata_type_boolean'; $options['field_options'] = []; return new TypeGuess('sonata_search_elastica_boolean', $options, Guess::HIGH_CONFIDENCE); case 'datetime': case 'vardatetime': case 'datetimetz': return new TypeGuess('sonata_search_elastica_datetime', $options, Guess::HIGH_CONFIDENCE); case 'date': return new TypeGuess('sonata_search_elastica_date', $options, Guess::HIGH_CONFIDENCE); case 'decimal': case 'float': $options['field_type'] = 'number'; return new TypeGuess('sonata_search_elastica_number', $options, Guess::MEDIUM_CONFIDENCE); case 'integer': case 'bigint': case 'smallint': $options['field_type'] = 'number'; return new TypeGuess('sonata_search_elastica_number', $options, Guess::MEDIUM_CONFIDENCE); case 'string': case 'text': $options['field_type'] = 'text'; return new TypeGuess('sonata_search_elastica_string', $options, Guess::MEDIUM_CONFIDENCE); case 'time': return new TypeGuess('sonata_search_elastica_time', $options, Guess::HIGH_CONFIDENCE); default: return new TypeGuess('sonata_search_elastica_string', $options, Guess::LOW_CONFIDENCE); } }
{@inheritdoc}
entailment
public function refreshAccessToken(AccessToken $token = null):AccessToken{ if($token === null){ $token = $this->storage->getAccessToken($this->serviceName); } $refreshToken = $token->refreshToken; if(empty($refreshToken)){ if(!$this instanceof AccessTokenForRefresh){ throw new ProviderException(sprintf('no refresh token available, token expired [%s]', date('Y-m-d h:i:s A', $token->expires))); } $refreshToken = $token->accessToken; } $body = [ 'client_id' => $this->options->key, 'client_secret' => $this->options->secret, 'grant_type' => 'refresh_token', 'refresh_token' => $refreshToken, 'type' => 'web_server', ]; $request = $this->requestFactory ->createRequest('POST', $this->refreshTokenURL ?? $this->accessTokenURL) ->withHeader('Content-Type', 'application/x-www-form-urlencoded') ->withHeader('Accept-Encoding', 'identity') ->withBody($this->streamFactory->createStream(http_build_query($body, '', '&', PHP_QUERY_RFC1738))) ; foreach($this->authHeaders as $header => $value){ $request = $request->withAddedHeader($header, $value); } $newToken = $this->parseTokenResponse($this->http->sendRequest($request)); if(empty($newToken->refreshToken)){ $newToken->refreshToken = $refreshToken; } $this->storage->storeAccessToken($this->serviceName, $newToken); return $newToken; }
@param \chillerlan\OAuth\Core\AccessToken $token @return \chillerlan\OAuth\Core\AccessToken|\chillerlan\Settings\SettingsContainerInterface @throws \chillerlan\OAuth\Core\ProviderException
entailment
public function prepareRequest($method, array $params = []) { $request = [ 'jsonrpc' => '2.0', 'method' => $method, 'id' => mt_rand() ]; $request['params'] = $params ? $params : []; /*$request['params'] = array_merge($request['params'], $this->params);*/ return $request; }
prepare a json rpc request array @param $method @param array $params @return array
entailment
public function makeRequest($request) { $optionsSet = curl_setopt_array($this->ch, [ CURLOPT_URL => $this->url, CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => $this->timeout, CURLOPT_USERAGENT => 'JSON-RPC Random.org PHP Client', CURLOPT_HTTPHEADER => $this->headers, CURLOPT_FOLLOWLOCATION => false, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_SSL_VERIFYPEER => $this->verifyPeer, CURLOPT_POSTFIELDS => json_encode($request) ]); if (!$optionsSet) { throw new \Exception('Cannot set curl options'); } $responseBody = curl_exec($this->ch); $responseCode = curl_getinfo($this->ch, CURLINFO_HTTP_CODE); if (curl_errno($this->ch)) { throw new \RuntimeException(curl_error($this->ch)); } if ($responseCode === 401 || $responseCode === 403) { throw new \RuntimeException('Access denied'); } $response = json_decode($responseBody, true); if ($this->debug) { echo('==> Request: '.PHP_EOL.json_encode($request, JSON_PRETTY_PRINT)); echo('==> Response: '.PHP_EOL.json_encode($response, JSON_PRETTY_PRINT)); } return $response; }
make the request to the server and get response @param $request @return mixed @throws RuntimeException @throws \Exception
entailment
public function getResponse(array $response) { if (isset($response['error']['code'])) { $this->handleRpcErrors($response['error']); } return isset($response['result']) ? $response['result'] : null; }
Get the response from the server if there are API error pass them to error handler function @param array $response @return null @throws BadFunctionCallException @throws InvalidArgumentException @throws RuntimeException
entailment
public function handleRpcErrors($error) { switch ($error['code']) { case -32600: throw new \InvalidArgumentException('Invalid Request: '. $error['message']); case -32601: throw new \BadFunctionCallException('Procedure not found: '. $error['message']); case -32602: throw new \InvalidArgumentException('Invalid arguments: '. $error['message']); case -32603: throw new \RuntimeException('Internal Error: '. $error['message']); default: throw new \RuntimeException('Invalid request/response: '. $error['message'], $error['code']); } }
Process JSON-RPC errors @param $error @throws BadFunctionCallException @throws InvalidArgumentException @throws RuntimeException
entailment
public function getResults() { return $this->getPaginator()->getResults( $this->getQuery()->getFirstResult(), $this->getQuery()->getMaxResults() )->toArray(); }
{@inheritdoc}
entailment
private function parse_ftp_rawlist($line) { $output = array(); $split = preg_split('[ ]', $line, 9, PREG_SPLIT_NO_EMPTY); if ($split[0] != 'total') { $output['isdir'] = ($split[0] {0} === 'd'); $output['perms'] = $split[0]; $output['number'] = $split[1]; $output['owner'] = $split[2]; $output['group'] = $split[3]; $output['size'] = $split[4]; $output['month'] = $split[5]; $output['day'] = $split[6]; $output['time/year'] = $split[7]; $output['name'] = $split[8]; } return !empty($output) ? $output : false; }
function inspired by http://andreas.glaser.me/2009/03/12/php-ftp_rawlist-parser-windows-unixlinux/
entailment
public static function country2locale($code) { # http://wiki.openstreetmap.org/wiki/Nominatim/Country_Codes $arr = array( 'ad' => 'ca', 'ae' => 'ar', 'af' => 'fa,ps', 'ag' => 'en', 'ai' => 'en', 'al' => 'sq', 'am' => 'hy', 'an' => 'nl,en', 'ao' => 'pt', 'aq' => 'en', 'ar' => 'es', 'as' => 'en,sm', 'at' => 'de', 'au' => 'en', 'aw' => 'nl,pap', 'ax' => 'sv', 'az' => 'az', 'ba' => 'bs,hr,sr', 'bb' => 'en', 'bd' => 'bn', 'be' => 'nl,fr,de', 'bf' => 'fr', 'bg' => 'bg', 'bh' => 'ar', 'bi' => 'fr', 'bj' => 'fr', 'bl' => 'fr', 'bm' => 'en', 'bn' => 'ms', 'bo' => 'es,qu,ay', 'br' => 'pt', 'bq' => 'nl,en', 'bs' => 'en', 'bt' => 'dz', 'bv' => 'no', 'bw' => 'en,tn', 'by' => 'be,ru', 'bz' => 'en', 'ca' => 'en,fr', 'cc' => 'en', 'cd' => 'fr', 'cf' => 'fr', 'cg' => 'fr', 'ch' => 'de,fr,it,rm', 'ci' => 'fr', 'ck' => 'en,rar', 'cl' => 'es', 'cm' => 'fr,en', 'cn' => 'zh', 'co' => 'es', 'cr' => 'es', 'cu' => 'es', 'cv' => 'pt', 'cw' => 'nl', 'cx' => 'en', 'cy' => 'el,tr', 'cz' => 'cs', 'de' => 'de', 'dj' => 'fr,ar,so', 'dk' => 'da', 'dm' => 'en', 'do' => 'es', 'dz' => 'ar', 'ec' => 'es', 'ee' => 'et', 'eg' => 'ar', 'eh' => 'ar,es,fr', 'er' => 'ti,ar,en', 'es' => 'es,ast,ca,eu,gl', 'et' => 'am,om', 'fi' => 'fi,sv,se', 'fj' => 'en', 'fk' => 'en', 'fm' => 'en', 'fo' => 'fo', 'fr' => 'fr', 'ga' => 'fr', 'gb' => 'en,ga,cy,gd,kw', 'gd' => 'en', 'ge' => 'ka', 'gf' => 'fr', 'gg' => 'en', 'gh' => 'en', 'gi' => 'en', 'gl' => 'kl,da', 'gm' => 'en', 'gn' => 'fr', 'gp' => 'fr', 'gq' => 'es,fr,pt', 'gr' => 'el', 'gs' => 'en', 'gt' => 'es', 'gu' => 'en,ch', 'gw' => 'pt', 'gy' => 'en', 'hk' => 'zh,en', 'hm' => 'en', 'hn' => 'es', 'hr' => 'hr', 'ht' => 'fr,ht', 'hu' => 'hu', 'id' => 'id', 'ie' => 'en,ga', 'il' => 'he', 'im' => 'en', 'in' => 'hi,en', 'io' => 'en', 'iq' => 'ar,ku', 'ir' => 'fa', 'is' => 'is', 'it' => 'it,de,fr', 'je' => 'en', 'jm' => 'en', 'jo' => 'ar', 'jp' => 'ja', 'ke' => 'sw,en', 'kg' => 'ky,ru', 'kh' => 'km', 'ki' => 'en', 'km' => 'ar,fr', 'kn' => 'en', 'kp' => 'ko', 'kr' => 'ko,en', 'kw' => 'ar', 'ky' => 'en', 'kz' => 'kk,ru', 'la' => 'lo', 'lb' => 'ar,fr', 'lc' => 'en', 'li' => 'de', 'lk' => 'si,ta', 'lr' => 'en', 'ls' => 'en,st', 'lt' => 'lt', 'lu' => 'lb,fr,de', 'lv' => 'lv', 'ly' => 'ar', 'ma' => 'ar', 'mc' => 'fr', 'md' => 'ru,uk,ro', 'me' => 'srp,sq,bs,hr,sr', 'mf' => 'fr', 'mg' => 'mg,fr', 'mh' => 'en,mh', 'mk' => 'mk', 'ml' => 'fr', 'mm' => 'my', 'mn' => 'mn', 'mo' => 'zh,en,pt', 'mp' => 'ch', 'mq' => 'fr', 'mr' => 'ar,fr', 'ms' => 'en', 'mt' => 'mt,en', 'mu' => 'mfe,fr,en', 'mv' => 'dv', 'mw' => 'en,ny', 'mx' => 'es', 'my' => 'ms,zh,en', 'mz' => 'pt', 'na' => 'en,sf,de', 'nc' => 'fr', 'ne' => 'fr', 'nf' => 'en,pih', 'ng' => 'en', 'ni' => 'es', 'nl' => 'nl', 'no' => 'nb,nn,no,se', 'np' => 'ne', 'nr' => 'na,en', 'nu' => 'niu,en', 'nz' => 'en,mi', 'om' => 'ar', 'pa' => 'es', 'pe' => 'es', 'pf' => 'fr', 'pg' => 'en,tpi,ho', 'ph' => 'en,tl', 'pk' => 'en,ur', 'pl' => 'pl', 'pm' => 'fr', 'pn' => 'en,pih', 'pr' => 'es,en', 'ps' => 'ar,he', 'pt' => 'pt', 'pw' => 'en,pau,ja,sov,tox', 'py' => 'es,gn', 'qa' => 'ar', 're' => 'fr', 'ro' => 'ro', 'rs' => 'sr', 'ru' => 'ru', 'rw' => 'rw,fr,en', 'sa' => 'ar', 'sb' => 'en', 'sc' => 'fr,en,crs', 'sd' => 'ar,en', 'se' => 'sv', 'sg' => 'en,ms,zh,ta', 'sh' => 'en', 'si' => 'sl', 'sj' => 'no', 'sk' => 'sk', 'sl' => 'en', 'sm' => 'it', 'sn' => 'fr', 'so' => 'so,ar', 'sr' => 'nl', 'st' => 'pt', 'ss' => 'en', 'sv' => 'es', 'sx' => 'nl,en', 'sy' => 'ar', 'sz' => 'en,ss', 'tc' => 'en', 'td' => 'fr,ar', 'tf' => 'fr', 'tg' => 'fr', 'th' => 'th', 'tj' => 'tg,ru', 'tk' => 'tkl,en,sm', 'tl' => 'pt,tet', 'tm' => 'tk', 'tn' => 'ar', 'to' => 'en', 'tr' => 'tr', 'tt' => 'en', 'tv' => 'en', 'tw' => 'zh', 'tz' => 'sw,en', 'ua' => 'uk', 'ug' => 'en,sw', 'um' => 'en', 'us' => 'en,es', 'uy' => 'es', 'uz' => 'uz,kaa', 'va' => 'it', 'vc' => 'en', 've' => 'es', 'vg' => 'en', 'vi' => 'en', 'vn' => 'vi', 'vu' => 'bi,en,fr', 'wf' => 'fr', 'ws' => 'sm,en', 'ye' => 'ar', 'yt' => 'fr', 'za' => 'zu,xh,af,st,tn,en', 'zm' => 'en', 'zw' => 'en,sn,nd' ); #---- $code = strtolower($code); if ($code == 'eu') { return 'en_GB'; } elseif ($code == 'ap') { # Asia Pacific return 'en_US'; } elseif ($code == 'cs') { return 'sr_RS'; } #---- if ($code == 'uk') { $code = 'gb'; } if (array_key_exists($code, $arr)) { if (strpos($arr[$code], ',') !== false) { $new = explode(',', $arr[$code]); $loc = array(); foreach ($new as $key => $val) { $loc[] = $val.'_'.strtoupper($code); } return implode(',', $loc); # string; comma-separated values 'en_GB,ga_GB,cy_GB,gd_GB,kw_GB' } else { return $arr[$code].'_'.strtoupper($code); # string 'en_US' } } return 'en_US'; }
#===================================================================
entailment
public function setHost(/* string */ $host) { // Close connection before changing host. if ($this->host !== $host) { $this->close(); $this->host = $host; } }
Changing FTP host name or IP @param string $host New hostname
entailment
public function setPort(/* integer */ $port) { // Close connection before changing port. if ($this->port !== $port) { $this->close(); $this->port = $port; } }
Changing FTP port. @param integer $port New hostname
entailment
public function setUser(/* string */ $user) { // Close connection before changing username. if ($this->user !== $user) { $this->close(); $this->user = $user; } }
Changing FTP connecting username. @param string $user New username
entailment
public function setPass(/* string */ $pass) { // Close connection before changing password. if ($this->pass !== $pass) { $this->close(); $this->pass = $pass; } }
Changing FTP password. @param string $pass New password
entailment
public function setPassive(/* boolean */ $passive) { // Close connection before changing password. if ($this->passive !== $passive) { $this->passive = $passive; if (isset($this->handle) && $this->handle != null) { $this->pasv($this->passive); } } }
Changing FTP passive mode. @param boolean $passive Set passive mode @throws FtpException if passive mode could not be set.
entailment
public function systype() { $this->connectIfNeeded(); $res = @ftp_systype($this->handle); return $res == null || $res == false ? 'UNIX' : $res; }
Returns the remote system type. @return string The remote system type
entailment
public function pasv($pasv) { $this->connectIfNeeded(); $this->param = $pasv; if (!ftp_pasv($this->handle, $pasv === true)) { throw new FtpException( Yii::t('gftp', 'Could not {set} passive mode on server "{host}": {message}', [ 'host' => $this->host, 'set' => $pasv ? "set" : "unset" ]) ); } }
Turns on or off passive mode. @param bool $pasv If <strong>TRUE</strong>, the passive mode is turned on, else it's turned off.
entailment
public function execute($command, $raw = false) { $this->connectIfNeeded(); $this->param = $command; if (!$raw && $this->stringStarts($command, "SITE EXEC")) { $this->exec(substr($command, strlen("SITE EXEC"))); return true; } else if (!$raw && $this->stringStarts($command, "SITE")) { $this->site(substr($command, strlen("SITE"))); return true; } else { return $this->raw($command); } }
Execute any command on FTP server. @param string $command FTP command. @param bool $raw Do not parse command to determine if it is a <i>SITE</i> or <i>SITE EXEC</i> command. @returns bool|string[] Depending on command : SITE and SITE EXEC command will returns <strong>TRUE</strong>; other command will returns an array. If <strong>$raw</strong> is set to <strong>TRUE</strong>, it always return an array. @throws FtpException If command execution fails. @see Ftp::exec Used to execute a <i>SITE EXEC</i> command @see Ftp::site Used to execute a <i>SITE</i> command @see Ftp::raw Used to execute any other command (or if $raw is set to <strong>TRUE</strong>)
entailment
public function exec($command) { $this->connectIfNeeded(); $this->param = "SITE EXEC " . $command; $exec = true; if (!ftp_exec($this->handle, substr($command, strlen("SITE EXEC")))) { throw new FtpException( Yii::t('gftp', 'Could not execute command "{command}" on "{host}"', [ 'host' => $this->host, '{command}' => $this->param ]) ); } }
Sends a SITE EXEC command request to the FTP server. @param string $command FTP command (does not include <i>SITE EXEC</i> words). @throws FtpException If command execution fails.
entailment
public function site($command) { $this->connectIfNeeded(); $this->param = "SITE " . $command; if (!ftp_site($this->handle, $command)) { throw new FtpException( Yii::t('gftp', 'Could not execute command "{command}" on "{host}"', [ 'host' => $this->host, '{command}' => $this->param ]) ); } }
Sends a SITE command request to the FTP server. @param string $command FTP command (does not include <strong>SITE</strong> word). @throws FtpException If command execution fails.
entailment
public function raw($command) { $this->connectIfNeeded(); $this->param = $command; $res = ftp_raw($this->handle, $command); return $res; }
Sends an arbitrary command to the FTP server. @param string $command FTP command to execute. @return string[] The server's response as an array of strings. No parsing is performed on the response string and not determine if the command succeeded. @throws FtpException If command execution fails.
entailment
protected function connectIfNeeded($login = true) { if (!isset($this->handle) || $this->handle == null) { $this->connect(); if ($login && $this->user != null && $this->user != "") { $this->login($this->user, $this->pass); } } }
Connects and log in to FTP server if not already login. Call to {link GFTp::connect} and {@link GTP::login} is not mandatory. Must be called in each method, before executing FTP command. @param bool $login Flag indicating if login will be done. @see GFTp::connect @see GFTp::login @throws FtpException if connection of login onto FTP server failed.
entailment
private function createException($function, $message) { if ($function == 'ftp_connect()' || $function == 'ftp_ssl_connect()') { $this->handle = false; return new FtpException( Yii::t('gftp', 'Could not connect to FTP server "{host}" on port "{port}": {message}', [ 'host' => $this->host, 'port' => $this->port, 'message' => $message ]) ); } else if ($function == 'ftp_close()') { return new FtpException( Yii::t('gftp', 'Could not close connection to FTP server "{host}" on port "{port}": {message}', [ 'host' => $this->host, 'port' => $this->port, 'message' => $message ]) ); } else if ($function == 'ftp_nlist()' || $function == 'ftp_rawlist()') { return new FtpException( Yii::t('gftp', 'Could not read folder "{folder}" on server "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'folder' => $this->param ]) ); } else if ($function == 'ftp_mkdir()') { return new FtpException( Yii::t('gftp', 'Could not create folder "{folder}" on "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'folder' => $this->param ]) ); } else if ($function == 'ftp_rmdir()') { return new FtpException( Yii::t('gftp', 'Could not remove folder "{folder}" on "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'folder' => $this->param ]) ); } else if ($function == 'ftp_cdup()') { return new FtpException( Yii::t('gftp', 'Could not move to parent directory on "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'folder' => $this->param ]) ); } else if ($function == 'ftp_chdir()') { return new FtpException( Yii::t('gftp', 'Could not move to folder "{folder}" on "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'folder' => $this->param ]) ); } else if ($function == 'ftp_pwd()') { return new FtpException( Yii::t('gftp', 'Could not get current folder on server "{host}": {message}', [ 'host' => $this->host, 'message' => $message ]) ); } else if ($function == 'ftp_chmod()') { return new FtpException( Yii::t('gftp', 'Could change mode (to "{mode}") of file "{file}" on server "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'file' => $this->param['file'], 'mode' => $this->param['mode'] ]) ); } else if ($function == 'ftp_put()') { return new FtpException( Yii::t('gftp', 'Could not put file "{local_file}" on "{remote_file}" on server "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'remote_file' => $this->param['remote_file'], 'local_file' => $this->param['local_file'] ]) ); } else if ($function == 'ftp_get()') { return new FtpException( Yii::t('gftp', 'Could not synchronously get file "{remote_file}" from server "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'remote_file' => $this->param['remote_file'] ]) ); } else if ($function == 'ftp_size()') { return new FtpException( Yii::t('gftp', 'Could not get size of file "{file}" on server "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'file' => $this->param ]) ); } else if ($function == 'ftp_nb_get()' || $function == 'ftp_nb_continue()') { return new FtpException( Yii::t('gftp', 'Could not asynchronously get file "{remote_file}" from server "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'remote_file' => $this->param['remote_file'] ]) ); } else if ($function == 'ftp_rename()') { return new FtpException( Yii::t('gftp', 'Could not rename file "{oldname}" to "{newname}" on server "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'oldname' => $this->param['oldname'], 'newname' => $this->param['newname'] ]) ); } else if ($function == 'ftp_delete()') { return new FtpException( Yii::t('gftp', 'Could not delete file "{file}" on server "{host}" : {message}', [ 'host' => $this->host, 'message' => $message, 'file' => $this->param ]) ); } else if ($function == 'ftp_pasv()') { return new FtpException( Yii::t('gftp', 'Could not {set} passive mode on server "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'set' => $this->param ? "set" : "unset" ]) ); } else if ($function == 'ftp_mdtm()') { return new FtpException( Yii::t('gftp', 'Could not get modification time of file "{file}" on server "{host}"', [ 'host' => $this->host, 'message' => $message, 'file' => $this->param ]) ); } else if ($function == 'ftp_exec()' || $function == 'ftp_raw()' || $function == 'ftp_site()') { return new FtpException( Yii::t('gftp', 'Could not execute command "{command}" on "{host}": {message}', [ 'host' => $this->host, 'message' => $message, 'command' => $this->param ]) ); } return null; }
Handles FTP error (ftp_** functions sometimes use PHP error instead of methofr return). It throws FtpException when ftp_** error is found. @param string $function FTP function name @param string $message Error message @return FtpException if PHP error on ftp_*** method is found, null otherwise.
entailment
public function request(string $path, array $params = null, string $method = null, $body = null, array $headers = null):ResponseInterface{ $request = $this->requestFactory ->createRequest($method ?? 'GET', Psr7\merge_query($this->apiURL.$path, $params ?? [])); foreach(array_merge($this->apiHeaders, $headers ?? []) as $header => $value){ $request = $request->withAddedHeader($header, $value); } if(is_array($body) && $request->hasHeader('content-type')){ $contentType = strtolower($request->getHeaderLine('content-type')); // @todo: content type support if($contentType === 'application/x-www-form-urlencoded'){ $body = $this->streamFactory->createStream(http_build_query($body, '', '&', PHP_QUERY_RFC1738)); } elseif($contentType === 'application/json'){ $body = $this->streamFactory->createStream(json_encode($body)); } } if($body instanceof StreamInterface){ $request = $request ->withBody($body) ->withHeader('Content-length', $body->getSize()) ; } return $this->sendRequest($request); }
@param string $path @param array $params @param string $method @param mixed $body @param array $headers @return \Psr\Http\Message\ResponseInterface
entailment
public function sendRequest(RequestInterface $request):ResponseInterface{ // get authorization only if we request the provider API if(strpos((string)$request->getUri(), $this->apiURL) === 0){ $token = $this->storage->getAccessToken($this->serviceName); // attempt to refresh an expired token if($this instanceof TokenRefresh && $this->options->tokenAutoRefresh && ($token->isExpired() || $token->expires === $token::EOL_UNKNOWN)){ $token = $this->refreshAccessToken($token); } $request = $this->getRequestAuthorization($request, $token); } return $this->http->sendRequest($request); }
@param \Psr\Http\Message\RequestInterface $request @return \Psr\Http\Message\ResponseInterface
entailment
public function filter(ProxyQueryInterface $query, $alias, $field, $data) { if (!$data || !\is_array($data) || !\array_key_exists('value', $data) || !is_numeric($data['value'])) { return; } $type = $data['type'] ?? false; $operator = $this->getOperator($type); $queryBuilder = new \Elastica\Query\Builder(); if (false === $operator) { // Match query to get equality $queryBuilder ->fieldOpen('match') ->field($field, $data['value']) ->fieldClose(); } else { // Range query $queryBuilder ->range() ->fieldOpen($field) ->field($operator, $data['value']) ->fieldClose() ->rangeClose(); } $query->addMust($queryBuilder); }
{@inheritdoc}
entailment
public function getBaseDatagrid(AdminInterface $admin, array $values = []) { $pager = new Pager(); $defaultOptions = []; $defaultOptions['csrf_protection'] = false; $formBuilder = $this->formFactory->createNamedBuilder( 'filter', 'form', [], $defaultOptions ); $proxyQuery = $admin->createQuery(); // if the default modelmanager query builder is used, we need to replace it with elastica // if not, that means $admin->createQuery has been overriden by the user and already returns // an ElasticaProxyQuery object if (!$proxyQuery instanceof ElasticaProxyQuery) { if ($this->isSmart($admin, $values)) { $proxyQuery = new ElasticaProxyQuery($this->finderProvider->getFinderByAdmin($admin)); } } return new Datagrid( $proxyQuery, $admin->getList(), $pager, $formBuilder, $values ); }
{@inheritdoc}
entailment
public function isSmart(AdminInterface $admin, array $values = []) { // first : validate if elastica is asked in the configuration for this action $logicalControllerName = $admin->getRequest()->attributes->get('_controller'); $currentAction = explode(':', $logicalControllerName); // remove Action from 'listAction' $currentAction = substr(end($currentAction), 0, -\strlen('Action')); // in case of batch|export action, no need to elasticsearch if (!\in_array($currentAction, $this->finderProvider->getActionsByAdmin($admin), true)) { return false; } // Get mapped field names $finderId = $this->finderProvider->getFinderIdByAdmin($admin); // Assume that finder id is composed like this 'fos_elastica.finder.<index name>.<type name> list($indexName, $typeName) = \array_slice(explode('.', $finderId), 2); $typeConfiguration = $this->configManager->getTypeConfiguration($indexName, $typeName); $mapping = $typeConfiguration->getMapping(); $mappedFieldNames = array_keys($mapping['properties']); // Compare to the fields on wich the search apply $smart = true; foreach ($values as $key => $value) { if (!\is_array($value) || !isset($value['value'])) { // This is not a filter field continue; } if (!$value['value']) { // No value set on the filter field continue; } if (!\in_array($key, $mappedFieldNames, true)) { /* * We are in the case where a field is used as filter * without being mapped in elastic search. * An ugly case would be to have a custom field used in the filter * without mapping in the model, we need to control that */ $ret = $admin->getModelManager()->getParentMetadataForProperty( $admin->getClass(), $key, $admin->getModelManager() ); list($metadata, $propertyName, $parentAssociationMappings) = $ret; //Case if a filter is used in the filter but not linked to the ModelManager ("mapped" = false ) case if (!$metadata->hasField($key)) { break; } // This filter field is not mapped in elasticsearch // so we cannot use elasticsearch $smart = false; break; } } return $smart; }
Returns true if this datagrid builder can process these values.
entailment
public function filter(ProxyQueryInterface $query, $alias, $field, $data) { if (!$data || !\is_array($data) || !\array_key_exists('value', $data)) { return; } $data['value'] = trim($data['value']); if (0 === \strlen($data['value'])) { return; } $data['type'] = !isset($data['type']) ? ChoiceType::TYPE_CONTAINS : $data['type']; list($firstOperator, $secondOperator) = $this->getOperators((int) $data['type']); // Create a query that match terms (indepedent of terms order) or a phrase $queryBuilder = new \Elastica\Query\Builder(); $queryBuilder ->fieldOpen($secondOperator) ->fieldOpen($field) ->field('query', str_replace(['\\', '"'], ['\\\\', '\"'], $data['value'])) ->field('operator', 'and') ->fieldClose() ->fieldClose(); if ('must' === $firstOperator) { $query->addMust($queryBuilder); } else { $query->addMustNot($queryBuilder); } }
{@inheritdoc}
entailment
private function parse_ftp_rawlist($line) { $output = array(); ereg('([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|) +(.+)', $Current, $split); if (is_array($split)) { if ($split[3] < 70) { $split[3] += 2000; } else { $split[3] += 1900; } $output['isdir'] = ($split[7] == ''); $output['size'] = $split[7]; $output['month'] = $split[1]; $output['day'] = $split[2]; $output['time/year'] = $split[3]; $output['name'] = $split[8]; } return !empty($output) ? $output : false; }
function inspired by http://andreas.glaser.me/2009/03/12/php-ftp_rawlist-parser-windows-unixlinux/
entailment
public function getFieldOptions() { return $this->getOption('choices', [ 'required' => false, 'choice_list' => new ChoiceList( array_values($this->getOption('sub_classes')), array_keys($this->getOption('sub_classes')) ), ]); }
{@inheritdoc}
entailment
public function setConnectionString($connectionString) { if (!isset($connectionString) || !is_string($connectionString) || trim($connectionString) === "") { throw new FtpException( Yii::t('gftp', '{connectString} is not a valid connection string', [ 'connectString' => $connectionString ]) ); } $this->close(); $this->connectionString = $connectionString; }
Sets a new connection string. If connection is already openned, try to close it before. @param string $connectionString FTP connection string (like ftp://[<user>[:<pass>]@]<host>[:<port>]) @throws FtpException if <i>connectionString</i> is not valid or if could not close an already openned connection.
entailment
protected function connectIfNeeded($login = true) { if (!isset($this->handle) || $this->handle == null) { $this->connect(); if ($login) $this->login(); } }
Connects and log in to FTP server if not already login. Call to {link GFTp::connect} and {@link GTP::login} is not mandatory. Must be called in each method, before executing FTP command. @param bool $login Flag indicating if login will be done. @see GFTp::connect @see GFTp::login @throws FtpException if connection of login onto FTP server failed.
entailment
public function connect() { if (isset($this->handle) && $this->handle != null) { $this->close(); } $this->parseConnectionString(); $this->handle = \Yii::createObject($this->driverOptions); $this->handle->connect(); $this->onConnectionOpen(new Event(['sender' => $this])); }
Connect to FTP server. throws FtpException If connection failed.
entailment
public function login () { $this->connectIfNeeded(false); $this->handle->login(); $this->onLogin(new Event(['sender' => $this, 'data' => $this->handle->user])); }
Log into the FTP server. If connection is not openned, it will be openned before login. @param string $user Username used for log on FTP server. @param string $password Password used for log on FTP server. @throws FtpException if connection failed.
entailment
public function ls($dir = ".", $full = false, $recursive = false) { $this->connectIfNeeded(); return $this->handle->ls($dir, $full, $recursive); }
Returns list of files in the given directory. @param string $dir The directory to be listed. This parameter can also include arguments, eg. $ftp->ls("-la /your/dir"); Note that this parameter isn't escaped so there may be some issues with filenames containing spaces and other characters. @param string $full List full dir description. @param string $recursive Recursively list folder content @return FtpFile[] Array containing list of files.
entailment
public function close() { if (isset($this->handle) && $this->handle != null) { $this->handle->close(); $this->handle = false; $this->onConnectionClose(new Event(['sender' => $this])); } }
Close FTP connection. @throws FtpException Raised when error occured when closing FTP connection.
entailment
public function mkdir($dir) { $this->connectIfNeeded(); $this->handle->mkdir($dir); $this->onFolderCreated(new Event(['sender' => $this, 'data' => $dir])); }
Create a new folder on FTP server. @param string $dir Folder to create on server (relative or absolute path). @throws FtpException If folder creation failed.
entailment
public function rmdir($dir) { $this->connectIfNeeded(); $this->handle->rmdir($dir); $this->onFolderDeleted(new Event(['sender' => $this, 'data' => $dir])); }
Removes a folder on FTP server. @param string $dir Folder to delete from server (relative or absolute path). @throws FtpException If folder deletion failed.
entailment
public function chdir($dir) { $this->connectIfNeeded(); $this->handle->chdir($dir); $this->onFolderChanged(new Event(['sender' => $this, 'data' => $dir])); try { $cwd = $this->pwd(); } catch (FtpException $ex) { $cwd = $dir; } return $cwd; }
Changes current folder. @param string $dir Folder to move on (relative or absolute path). @return string Current folder on FTP server. @throws FtpException If folder deletion failed.
entailment
public function get($remote_file, $local_file = null, $mode = FTP_ASCII, $asynchronous = false, callable $asyncFn = null) { $this->connectIfNeeded(); $local_file = $this->handle->get($remote_file, $local_file,$mode, $asynchronous, $asyncFn); $this->onFileDownloaded(new Event(['sender' => $this, 'data' => $local_file])); return $local_file; }
Download a file from FTP server. @param string $remote_file The remote file path. @param string|resource $local_file The local file path. If set to <strong>null</strong>, file will be downloaded inside current folder using remote file base name). @param int $mode The transfer mode. Must be either <strong>FTP_ASCII</strong> or <strong>FTP_BINARY</strong>. @param bool $asynchronous Flag indicating if file transfert should block php application or not. @param callable $asyncFn Async callback function called during download process @return string The full local path (absolute).
entailment
public function put($local_file, $remote_file = null, $mode = FTP_ASCII, $asynchronous = false, callable $asyncFn = null) { $this->connectIfNeeded(); $full_remote_file = $this->handle->put($local_file, $remote_file, $mode, $asynchronous, $asyncFn); $this->onFileUploaded(new Event(['sender' => $this, 'data' => $remote_file])); return $full_remote_file; }
Upload a file to the FTP server. @param string|resource $local_file The local file path. @param string $remote_file The remote file path. If set to <strong>null</strong>, file will be downloaded inside current folder using local file base name). @param int $mode The transfer mode. Must be either <strong>FTP_ASCII</strong> or <strong>FTP_BINARY</strong>. @param bool $asynchronous Flag indicating if file transfert should block php application or not. @param callable $asyncFn Async callback function called during download process @return string The full local path (absolute). @throws FtpException If an error occcured during file transfert.
entailment
public function delete($path) { $this->connectIfNeeded(); $this->handle->delete($path); $this->onFileDeleted(new Event(['sender' => $this, 'data' => $path])); }
Deletes specified files from FTP server. @param string $path The file to delete. @throws FtpException If file could not be deleted.
entailment
public function rename($oldname, $newname) { $this->connectIfNeeded(); $this->handle->rename($oldname, $newname); $this->onFileRenamed( new Event(['sender' => $this, 'data' => [ 'oldname' => $oldname, 'newname' => $newname ]]) ); }
Renames a file or a directory on the FTP server. @param string $oldname The old file/directory name. @param string $newname The new name. @throws FtpException If an error occured while renaming file or folder.
entailment
public function chmod($mode, $file) { $this->connectIfNeeded(); $this->handle->chmod($mode, $file); $this->onFileModeChanged( new Event(['sender' => $this, 'data' => [ 'mode' => $mode, 'file' => $file ]]) ); }
Set permissions on a file via FTP. @param string $mode The new permissions, given as an <strong>octal</strong> value. @param string $file The remote file. @throws FtpException If couldn't set file permission.
entailment
public function storeAccessToken(string $service, AccessToken $token):OAuthStorageInterface{ $this->tokens[$service] = $token; return $this; }
@param string $service @param \chillerlan\OAuth\Core\AccessToken $token @return \chillerlan\OAuth\Storage\OAuthStorageInterface
entailment
public function getAccessToken(string $service):AccessToken{ if($this->hasAccessToken($service)){ return $this->tokens[$service]; } throw new OAuthStorageException('token not found'); }
@param string $service @return \chillerlan\OAuth\Core\AccessToken|\chillerlan\Settings\SettingsContainerInterface @throws \chillerlan\OAuth\Storage\OAuthStorageException
entailment
public function hasAccessToken(string $service):bool { return isset($this->tokens[$service]) && $this->tokens[$service] instanceof AccessToken; }
@param string $service @return bool
entailment
public function clearAccessToken(string $service):OAuthStorageInterface{ if(array_key_exists($service, $this->tokens)){ unset($this->tokens[$service]); } return $this; }
@param string $service @return \chillerlan\OAuth\Storage\OAuthStorageInterface
entailment
public function storeCSRFState(string $service, string $state):OAuthStorageInterface{ $this->states[$service] = $state; return $this; }
@param string $service @param string $state @return \chillerlan\OAuth\Storage\OAuthStorageInterface
entailment
public function getCSRFState(string $service):string{ if($this->hasCSRFState($service)){ return $this->states[$service]; } throw new OAuthStorageException('state not found'); }
@param string $service @return string @throws \chillerlan\OAuth\Storage\OAuthStorageException
entailment
public function hasCSRFState(string $service):bool { return isset($this->states[$service]) && null !== $this->states[$service]; }
@param string $service @return bool
entailment
public function clearCSRFState(string $service):OAuthStorageInterface{ if(array_key_exists($service, $this->states)){ unset($this->states[$service]); } return $this; }
@param string $service @return \chillerlan\OAuth\Storage\OAuthStorageInterface
entailment
public function filter(ProxyQueryInterface $query, $alias, $field, $data) { // check data sanity if (!$data || !\is_array($data) || !\array_key_exists('value', $data)) { return; } $format = \array_key_exists('format', $this->getFieldOptions()) ? $this->getFieldOptions()['format'] : 'c'; $queryBuilder = new \Elastica\Query\Builder(); /* * NEXT_MAJOR: Use ($this instanceof RangeFilterInterface) for if statement, remove deprecated range. */ if (!($range = $this instanceof RangeFilterInterface)) { @trigger_error( sprintf( 'Using `range` property is deprecated since version 1.x, will be removed in 2.0.'. ' Implement %s instead.', RangeFilterInterface::class ), E_USER_DEPRECATED ); $range = $this->range; } if ($range) { // additional data check for ranged items if (!\array_key_exists('start', $data['value']) || !\array_key_exists('end', $data['value'])) { return; } if (!$data['value']['start'] || !$data['value']['end']) { return; } // transform types if ('timestamp' === $this->getOption('input_type')) { $data['value']['start'] = $data['value']['start'] instanceof \DateTime ? $data['value']['start']->getTimestamp() : 0; $data['value']['end'] = $data['value']['end'] instanceof \DateTime ? $data['value']['end']->getTimestamp() : 0; } // default type for range filter $data['type'] = !isset($data['type']) || !is_numeric($data['type']) ? DateRangeType::TYPE_BETWEEN : $data['type']; $queryBuilder ->fieldOpen('range') ->fieldOpen($field) ->field('gte', $data['value']['start']->format($format)) ->field('lte', $data['value']['end']->format($format)) ->fieldClose() ->fieldClose(); if (DateRangeType::TYPE_NOT_BETWEEN === $data['type']) { $query->addMustNot($queryBuilder); } else { $query->addMust($queryBuilder); } } else { if (!$data['value']) { return; } // default type for simple filter $data['type'] = !isset($data['type']) || !is_numeric($data['type']) ? DateType::TYPE_GREATER_EQUAL : $data['type']; // just find an operator and apply query $operator = $this->getOperator($data['type']); // transform types if ('timestamp' === $this->getOption('input_type')) { $data['value'] = $data['value'] instanceof \DateTime ? $data['value']->getTimestamp() : 0; } // null / not null only check for col if (\in_array($operator, ['missing', 'exists'], true)) { $queryBuilder ->fieldOpen($operator) ->field('field', $field) ->fieldClose(); } elseif ('=' === $operator) { $queryBuilder ->fieldOpen('range') ->fieldOpen($field) ->field('gte', $data['value']->format($format)) ->field('lte', $data['value']->format($format)) ->fieldClose() ->fieldClose(); } else { $queryBuilder ->fieldOpen('range') ->fieldOpen($field) ->field($operator, $data['value']->format($format)) ->fieldClose() ->fieldClose(); } $query->addMust($queryBuilder); } }
{@inheritdoc}
entailment
public function decode($data, $format, array $context = []) { $decoded = parent::decode($data, $format, $context); if (isset($decoded['$xmlns'])) { $this->decodeCustomFields($decoded); } $this->cleanup($decoded); return $decoded; }
{@inheritdoc}
entailment
protected function cleanup(array &$data) { foreach ($data as &$value) { if (\is_array($value)) { $this->cleanup($value); } } $data = array_filter($data, function ($value) { return null !== $value; }); }
Recursively filter an array, removing null and empty string values. @param array &$data The data to filter.
entailment
protected function decodeCustomFields(&$decoded) { // @todo This is O(namespaces * entries) and can be optimized. foreach ($decoded['$xmlns'] as $prefix => $namespace) { if (!isset($decoded['entries'])) { $this->decodeObject($prefix, $namespace, $decoded); continue; } foreach ($decoded['entries'] as &$entry) { $this->decodeObject($prefix, $namespace, $entry); } } }
Decode custom fields into a format usable by a normalizer. mpx returns custom fields as properties on the data object, prefixed with a namespace identifier. Custom fields are described in a single class, and not by manually extending core data classes. To be able to normalize those fields, they must be moved into a single property. Custom fields are returned in a 'customFields' array, with each value representing one mpx custom field namespace. Within each namespace array there is a 'namespace' key with the fully-qualified mpx namespace URI, and a 'data' key with an array of the custom field values. @param array &$decoded The data to decode.
entailment
protected function decodeObject($prefix, $namespace, &$object) { $customFields = ['namespace' => $namespace]; foreach ($object as $key => $value) { if (false !== strpos($key, $prefix.'$')) { $fieldName = substr($key, \strlen($prefix) + 1); $customFields['data'][$fieldName] = $value; } } // In the case of an object-list response, namespaces are included for // all namespaces in any object in the result set. If a given namespace // is not used in a single object, we can skip custom fields entirely. if (!empty($customFields['data'])) { $object['customFields'][$namespace] = $customFields; } }
Decodes an object's custom fields. @param string $prefix The prefix of the namespace in the response. @param string $namespace The namespace identifier. @param array $object The object data to decode.
entailment
public function boot() { $this->package('maxxscho/laravel-tcpdf'); /* override the default TCPDF config file ------------------------------------- */ if (!defined('K_TCPDF_EXTERNAL_CONFIG')) { define('K_TCPDF_EXTERNAL_CONFIG', TRUE); } $this->setTcpdfConstants(); AliasLoader::getInstance()->alias('PDF', 'Maxxscho\LaravelTcpdf\Facades\LaravelTcpdfFacade'); }
Bootstrap the application events. @return void
entailment
private function setTcpdfConstants() { foreach ($this->config_constant_map as $const => $configkey) { if (!defined($const)) { if (is_string(\Config::get('laravel-tcpdf::' . $configkey))) { if (strlen(\Config::get('laravel-tcpdf::' . $configkey)) > 0) { define($const, \Config::get('laravel-tcpdf::' . $configkey)); } } else { define($const, \Config::get('laravel-tcpdf::' . $configkey)); } } } }
Set TCPDF constants based on configuration file. !Notice! Some contants are never used by TCPDF. They are in the config file of TCPDF, but ... This is a bug by TCPDF but we set it for completeness. @author Markus Schober
entailment
public static function create( RequestInterface $request, ResponseInterface $response, \Exception $previous = null, array $ctx = [] ) { $data = \GuzzleHttp\json_decode($response->getBody(), true); MpxExceptionTrait::validateData($data); $altered = $response->withStatus($data['responseCode'], $data['title']); return self::createException($request, $altered, $previous, $ctx); }
Create a new MPX API exception. @param \Psr\Http\Message\RequestInterface $request @param \Psr\Http\Message\ResponseInterface $response @param \Exception|null $previous @param array $ctx @return \Lullabot\Mpx\Exception\ClientException|\Lullabot\Mpx\Exception\ServerException
entailment
private static function createException(RequestInterface $request, ResponseInterface $altered, \Exception $previous = null, array $ctx = [] ) { if ($altered->getStatusCode() >= 400 && $altered->getStatusCode() < 500) { return new ClientException($request, $altered, $previous, $ctx); } return new ServerException($request, $altered, $previous, $ctx); }
Create a client or server exception. @param RequestInterface $request @param ResponseInterface $altered @param \Exception $previous @param array $ctx @return ClientException|ServerException
entailment
public static function basicDiscovery(): self { // @todo Check Drupal core for other tags to ignore? AnnotationReader::addGlobalIgnoredName('class'); AnnotationRegistry::registerFile(__DIR__.'/Annotation/CustomField.php'); $discovery = new CustomFieldDiscovery('\\Lullabot\\Mpx', 'src', __DIR__.'/../..', new AnnotationReader()); return new static($discovery); }
Register our annotations, relative to this file. @return static
entailment
public function getCustomField(string $name, string $objectType, string $namespace): DiscoveredCustomField { $services = $this->discovery->getCustomFields(); if (isset($services[$name][$objectType][$namespace])) { return $services[$name][$objectType][$namespace]; } throw new \RuntimeException('Custom field not found.'); }
Returns one custom field. @param string $name @param string $objectType @param string $namespace @return DiscoveredCustomField
entailment
private function getClass(InputInterface $input, string $mpxNamespace): array { if (!isset($this->namespaceClasses[$mpxNamespace])) { $nf = new \NumberFormatter('en', \NumberFormatter::SPELLOUT); $className = 'CustomFieldClass'.ucfirst( str_replace('-', '', $nf->format(\count($this->namespaceClasses) + 1)) ); $namespace = new PhpNamespace($input->getArgument('namespace')); $class = $namespace->addClass($className); $this->classNames[$mpxNamespace] = $className; $this->namespaceClasses[$mpxNamespace] = $namespace; $class->addImplement(CustomFieldInterface::class); $class->addComment('@\Lullabot\Mpx\DataService\Annotation\CustomField('); $class->addComment(' namespace="'.$mpxNamespace.'",'); $class->addComment(' service="'.$input->getArgument('data-service').'",'); $class->addComment(' objectType="'.$input->getArgument('data-object').'",'); $class->addComment(')'); } else { $namespace = $this->namespaceClasses[$mpxNamespace]; $class = $namespace->getClasses()[$this->classNames[$mpxNamespace]]; } return [$namespace, $class]; }
@param InputInterface $input @param string $mpxNamespace @return array
entailment
private function addProperty(ClassType $class, Field $field) { $property = $class->addProperty($field->getFieldName()); $property->setVisibility('protected'); if (!empty($field->getDescription())) { $property->setComment($field->getDescription()); $property->addComment(''); } $dataType = $this->getPhpDataType($field); $property->addComment('@var '.$dataType); if ($this->isCollectionType($dataType)) { $property->setValue([]); } }
Add a property to a class. @param ClassType $class @param Field $field
entailment
private function getPhpDataType(Field $field): string { $dataType = static::TYPE_MAP[$field->getDataType()]; if ('Single' != $field->getDataStructure()) { $dataType .= '[]'; } return $dataType; }
Get the PHP data type for a field, including mapping to arrays. @param Field $field @return string
entailment
public function getTargetAvailableDate(): \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface { if (!$this->targetAvailableDate) { return new NullDateTime(); } return $this->targetAvailableDate; }
Returns the DateTime when this playback availability window begins. @return \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface
entailment
public function setTargetAvailableDate(\Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $targetAvailableDate) { $this->targetAvailableDate = $targetAvailableDate; }
Set the DateTime when this playback availability window begins. @param \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $targetAvailableDate
entailment
public function getTargetExpirationDate(): \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface { if (!$this->targetExpirationDate) { return new NullDateTime(); } return $this->targetExpirationDate; }
Returns the DateTime when this playback availability window ends. @return \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface
entailment
public function setTargetExpirationDate(\Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $targetExpirationDate) { $this->targetExpirationDate = $targetExpirationDate; }
Set the DateTime when this playback availability window ends. @param \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $targetExpirationDate
entailment
private function getNewRequest(string $method, UriInterface $uri): RequestInterface { return $this->transport->createRequest($method, $uri); }
To get a new PSR7 request from transport instance to be able to dialog with Sellsy API. @param string $method @param UriInterface $uri @return RequestInterface
entailment
private function encodeOAuthHeaders(&$oauth) { $values = []; foreach ($oauth as $key => &$value) { $values[] = $key.'="'.\rawurlencode($value).'"'; } return 'OAuth '.\implode(', ', $values); }
Transform an the OAuth array configuration to HTTP headers OAuth string. @param array $oauth @return string
entailment
private function setOAuthHeaders(RequestInterface $request): RequestInterface { $now = new \DateTime(); if ($this->now instanceof \DateTime) { $now = clone $this->now; } //Generate HTTP headers $encodedKey = \rawurlencode($this->oauthConsumerSecret).'&'.\rawurlencode($this->oauthAccessTokenSecret); $oauthParams = [ 'oauth_consumer_key' => $this->oauthConsumerKey, 'oauth_token' => $this->oauthAccessToken, 'oauth_nonce' => \sha1(\microtime(true).\rand(10000, 99999)), 'oauth_timestamp' => $now->getTimestamp(), 'oauth_signature_method' => 'PLAINTEXT', 'oauth_version' => '1.0', 'oauth_signature' => $encodedKey, ]; $request = $request->withHeader('Authorization', $this->encodeOAuthHeaders($oauthParams)); return $request->withHeader('Expect', ''); }
Internal method to generate HTTP headers to use for the API authentication with OAuth protocol. @param RequestInterface $request @return RequestInterface
entailment
private function getUri(): UriInterface { $uri = $this->getNewUri(); if (!empty($this->apiUrl['scheme'])) { $uri = $uri->withScheme($this->apiUrl['scheme']); } if (!empty($this->apiUrl['host'])) { $uri = $uri->withHost($this->apiUrl['host']); } if (!empty($this->apiUrl['port'])) { $uri = $uri->withPort($this->apiUrl['port']); } if (!empty($this->apiUrl['path'])) { $uri = $uri->withPath($this->apiUrl['path']); } if (!empty($this->apiUrl['query'])) { $uri = $uri->withQuery($this->apiUrl['query']); } if (!empty($this->apiUrl['fragment'])) { $uri = $uri->withFragment($this->apiUrl['fragment']); } return $uri; }
To get the PSR7 Uri instance to configure the PSR7 request to be able to dialog with the Sellsy API. @return UriInterface
entailment
private function setBodyRequest(RequestInterface $request, array &$requestSettings): RequestInterface { $multipartBody = []; foreach ($requestSettings as $key => &$value) { $multipartBody[] = [ 'name' => $key, 'contents' => $value ]; } return $request->withBody($this->transport->createStream($multipartBody)); }
To register method's argument in the request for the Sellsy API. @param RequestInterface $request @param array $requestSettings @return RequestInterface
entailment
public function run(MethodInterface $method, array $params = []): ResultInterface { //Arguments for the Sellsy API $this->lastResponse = null; $encodedRequest = [ 'request' => 1, 'io_mode' => 'json', 'do_in' => \json_encode([ 'method' => (string) $method, 'params' => $params, ]), ]; //Configure to contact the api with POST request and return value //Generate client request $request = $this->getNewRequest('POST', $this->getUri()); $request = $this->setOAuthHeaders($request); $request = $this->setBodyRequest($request, $encodedRequest); $this->lastRequest = $request; //Execute the request try { $this->lastResponse = $this->transport->execute($request); } catch (\Exception $e) { throw new RequestFailureException($e->getMessage(), $e->getCode(), $e); } $body = $this->lastResponse->getBody(); if (!$body instanceof StreamInterface) { throw new RequestFailureException('Bad body response'); } //OAuth issue, throw an exception $result = (string) $body->getContents(); if (false !== \strpos($result, 'oauth_problem')) { throw new RequestFailureException($result); } $answer = new Result($result); if ($answer->isError()) { //Bad request, error returned by the api, throw an error throw new ErrorException($answer->getErrorMessage()); } return $answer; }
{@inheritdoc}
entailment
protected function getDataObjectFactory(InputInterface $input, OutputInterface $output): DataObjectFactory { $authenticatedClient = $this->getAuthenticatedClient($input, $output); $manager = DataServiceManager::basicDiscovery(); $dataService = $manager->getDataService( $input->getArgument('data-service'), $input->getArgument('data-object'), $input->getArgument('schema') ); $dof = new DataObjectFactory($dataService->getAnnotation() ->getFieldDataService(), $authenticatedClient); return $dof; }
@param InputInterface $input @param OutputInterface $output @return DataObjectFactory
entailment
protected function getAuthenticatedClient(InputInterface $input, OutputInterface $output): \Lullabot\Mpx\AuthenticatedClient { $helper = $this->getHelper('question'); if (!$username = getenv('MPX_USERNAME')) { $question = new Question('Enter the mpx user name, such as mpx/[email protected]: '); $username = $helper->ask($input, $output, $question); } if (!$password = getenv('MPX_PASSWORD')) { $question = new Question('Enter the mpx password: '); $question->setHidden(true) ->setHiddenFallback(false); $password = $helper->ask($input, $output, $question); } $config = Client::getDefaultConfiguration(); $cl = new ConsoleLogger($output); /** @var $handler \GuzzleHttp\HandlerStack */ $handler = $config['handler']; $handler->after('cookies', new CurlFormatterMiddleware($cl)); $responseLogger = new Logger($cl); $responseLogger->setLogLevel(LogLevel::DEBUG); $responseLogger->setFormatter(new MessageFormatter(MessageFormatter::DEBUG)); $handler->after('cookies', $responseLogger); $client = new Client(new \GuzzleHttp\Client($config)); $store = new FlockStore(); $user = new User($username, $password); $userSession = new UserSession($user, $client, $store, new TokenCachePool(new ArrayCachePool())); $authenticatedClient = new AuthenticatedClient( $client, $userSession ); return $authenticatedClient; }
@param \Symfony\Component\Console\Input\InputInterface $input @param \Symfony\Component\Console\Output\OutputInterface $output @return \Lullabot\Mpx\AuthenticatedClient
entailment
private function extractMethodsName(string $websiteUrl): array { $documentSource = \file_get_contents($websiteUrl); $methods = []; $pattern = '#<div class="page-header">.*?<h1><a name="[a-z0-9]+"></a>([a-z0-9]+\.[a-z0-9]+)</h1>#isS'; if (false === \preg_match_all($pattern, $documentSource, $methods)) { throw new \RuntimeException(\preg_last_error()); } return $methods[1]; }
To extract from the documentation (downloaded from the Sellsy server) all methods declared into it. @param string $websiteUrl @return array
entailment
private function getSellsyInstance(): Sellsy { $sellSy = new Sellsy('', '', '', '', ''); $transport = new class implements TransportInterface { public function createUri(): UriInterface { } public function createRequest(string $method, UriInterface $uri): RequestInterface { } public function createStream(array &$elements): StreamInterface { } public function execute(RequestInterface $request): ResponseInterface { } }; $sellSy->setTransport($transport); //To prevent case issues from the inconsistent documentation $sellSy->AccountDatas(); $sellSy->TimeTracking(); return $sellSy; }
To return a instance of sellsy to check if a collection and a method is defined and is available here. TO prevent some issues with the inconsistency of the Sellsy Document, this method will preload some collections. to avoid false positive. @return Sellsy
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $websiteUrl = $input->getArgument('website'); $output->writeln(\sprintf('Check the documentation at "%s"', $websiteUrl)); try { $methodsList = $this->extractMethodsName($websiteUrl); } catch (\Throwable $e) { $output->writeln($e->getMessage()); return 1; } $collectionsToIgnore = \array_flip(\explode(',', $input->getOption('ignore'))); $missingCollections = []; $missingMethods = []; $this->testMethods($methodsList, $missingCollections, $missingMethods, $collectionsToIgnore); if (empty($missingCollections) && empty($missingMethods)) { $output->writeln('Definitions is synchronized'); return 0; } $output->writeln(PHP_EOL.'Missing collections :'); foreach ($missingCollections as $collection) { $output->writeln($collection); } $output->writeln(PHP_EOL.'Missing methods :'); foreach ($missingMethods as $method) { $output->writeln($method); } return 1; }
{@inheritdoc}
entailment
public function getTypes($class, $property, array $context = []) { // First, check to see if this object is a custom field. if (isset($this->xmlns[$property])) { return $this->customFieldInstance($property); } // Check if this is an array of custom field objects. if ('customFields' == $property) { return $this->customFieldsArrayType(); } if ('entries' == $property) { return $this->entriesType(); } // For all other types rely on the phpdoc extractor. return parent::getTypes($class, $property, $context); }
{@inheritdoc}
entailment
private function customFieldInstance($prefix): array { $ns = $this->xmlns[$prefix]; if (!$discoveredCustomField = $this->customFields[$ns]) { throw new LogicException( sprintf( 'No custom field class was found for %s. setCustomFields() must be called before using this extractor.', $ns ) ); } return [new Type('object', false, $discoveredCustomField->getClass())]; }
Return the type for a custom field class. @param string $prefix The prefix of the namespace. @return array
entailment
private function customFieldsArrayType(): array { $collectionKeyType = new Type(Type::BUILTIN_TYPE_STRING); $collectionValueType = new Type('object', false, CustomFieldInterface::class); return [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, $collectionKeyType, $collectionValueType)]; }
Return the type for an array of custom fields, indexed by a string. @return array
entailment
private function entriesType(): array { // This is an object list, so handle the 'entries' key. if (!isset($this->class)) { throw new \UnexpectedValueException('setClass() must be called before using this extractor.'); } $collectionKeyType = new Type(Type::BUILTIN_TYPE_INT); $collectionValueType = new Type('object', false, $this->class); return [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, $collectionKeyType, $collectionValueType)]; }
Return the type of an array of entries used in an object list. @return array
entailment
public function getAdded(): \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface { if (!$this->added) { return new NullDateTime(); } return $this->added; }
Returns the date and time that this object was created. @return \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface
entailment
public function setAdded(\Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $added) { $this->added = $added; }
Set the date and time that this object was created. @param \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $added
entailment
public function getAddedByUserId(): \Psr\Http\Message\UriInterface { if (!$this->addedByUserId) { return new Uri(); } return $this->addedByUserId; }
Returns the id of the user that created this object. @return \Psr\Http\Message\UriInterface
entailment
public function getId(): \Psr\Http\Message\UriInterface { if (!$this->id) { return new Uri(); } return $this->id; }
Returns the globally unique URI of this object. @return \Psr\Http\Message\UriInterface
entailment