sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function setUserAccess($userLogin, $access, $idSites, array $optional = []) { return $this->_request('UsersManager.setUserAccess', [ 'userLogin' => $userLogin, 'access' => $access, 'idSites' => $idSites, ], $optional); }
Grant access to multiple sites @param string $userLogin Username @param string $access @param array $idSites @param array $optional @return bool|object @throws InvalidRequestException
entailment
public function getTokenAuth($userLogin, $md5Password, array $optional = []) { return $this->_request('UsersManager.getTokenAuth', [ 'userLogin' => $userLogin, 'md5Password' => md5($md5Password), ], $optional); }
Get the token for a user @param string $userLogin Username @param string $md5Password Password in clear text @param array $optional @return bool|object @throws InvalidRequestException
entailment
public function read($n) { $n = (int) $n; $raw = substr($this->bytes, $this->position, $n); $this->position += $n; return $raw; }
@param int $n @return string
entailment
public function forward($n) { $n = (int) $n; if (($this->position + $n) > $this->getLength()) { throw new \OutOfBoundsException(sprintf('No more bytes to read')); } $this->position += $n; }
@param int $n @throws \OutOfBoundsException
entailment
public function setPosition($n) { $n = (int) $n; if ($n > $this->getLength()) { throw new \OutOfBoundsException(sprintf('Require position out of bound')); } $this->position = $n; }
@param int $n @throws \OutOfBoundsException
entailment
public function rewind($n) { $n = (int) $n; if ($n > $this->position) { throw new \InvalidArgumentException(sprintf('You try to rewind %d characters, but current position is %d', $n, $this->position )); } $this->position -= $n; }
@param int $n @throws \InvalidArgumentException
entailment
public static function newInstance() { $config = self::create(); $config->username = 'null'; $config->password = 'null'; $config->credentials = ['null', 'null']; $config->bindtoInterface = 'null'; $config->timeout = 5; return $config; }
@return Configuration @deprecated Will be removed in 2.0. Use Configuration::create
entailment
public function withCredentials($username, $password) { if (null === $username || null === $password) { // No change if credentials or null return $this; } $new = $this->setValue('username', $username) ->setValue('password', $password) ->setValue('credentials', [$username, $password]); // To keep BC $new->username = $username; $new->password = $password; $new->credentials = [$username, $password]; return $new; }
@param string $username @param string $password @return Configuration
entailment
public function getSession($version, array $credentials) { $v = (int) $version; if (!$this->supportsVersion($v)) { throw new \InvalidArgumentException(sprintf('No session registered supporting Version %d', $v)); } $class = $this->sessions[$v]; return new $class($this->io, $this->dispatcher, $credentials); }
@param int $version @param array $credentials @return SessionInterface
entailment
public function getRequestOptions() { return [ \GuzzleHttp\RequestOptions::FORM_PARAMS => [ $this->options['form_fields'][0] => $this->options['username'], $this->options['form_fields'][1] => $this->options['password'], ], ]; }
{@inheritdoc}
entailment
public function get($key, $defaultValue = null) { if (!isset($this->keyToIndexMap[$key]) && 2 === func_num_args()) { return $defaultValue; } return $this->value($key); }
@param string $key @param mixed $defaultValue @return \GraphAware\Bolt\Result\Type\Node|\GraphAware\Bolt\Result\Type\Path|\GraphAware\Bolt\Result\Type\Relationship|mixed
entailment
public function nodeValue($key) { if (!isset($this->keyToIndexMap[$key]) || !$this->values[$this->keyToIndexMap[$key]] instanceof Node) { throw new \InvalidArgumentException(sprintf('value for %s is not of type %s', $key, 'NODE')); } return $this->value($key); }
Returns the Node for value <code>$key</code>. Ease IDE integration. @param $key @return \GraphAware\Bolt\Result\Type\Node @throws \InvalidArgumentException When the value is not null or instance of Node
entailment
public function relationshipValue($key) { if (!isset($this->keyToIndexMap[$key]) || !$this->values[$this->keyToIndexMap[$key]] instanceof Relationship) { throw new \InvalidArgumentException(sprintf('value for %s is not of type %s', $key, 'RELATIONSHIP')); } return $this->value($key); }
@param $key @return \GraphAware\Bolt\Result\Type\Relationship @throws \InvalidArgumentException When the value is not null or instance of Relationship
entailment
public function pathValue($key) { if (!isset($this->keyToIndexMap[$key]) || !$this->values[$this->keyToIndexMap[$key]] instanceof Path) { throw new \InvalidArgumentException(sprintf('value for %s is not of type %s', $key, 'PATH')); } return $this->value($key); }
@param $key @return \GraphAware\Bolt\Result\Type\Path @throws \InvalidArgumentException When the value is not null or instance of Path
entailment
protected function getResourceClass() { if (array_key_exists('class', $this->options)) { if ($this->options['class'] === false) { return $this->getName(); } elseif (is_string($this->options['class'])) { return studly_case($this->options['class']); } } return studly_case($this->getNamespacedName()); }
only be used for authorization, not loading since there's no class to load through.
entailment
protected function getResourceBase() { if (array_key_exists('through', $this->options)) { if ($this->getParentResource()) { if (array_key_exists('singleton', $this->options)) { return $this->getResourceClass(); } elseif (array_key_exists('throughAssociation', $this->options)) { $associationName = $this->options['throughAssociation']; return get_classname($this->getParentResource()->$associationName()->getModel()); } else { $associationName = str_plural(camel_case($this->getName())); return get_classname($this->getParentResource()->$associationName()->getModel()); } } elseif (array_key_exists('shallow', $this->options)) { return $this->getResourceClass(); } else { // Maybe this should be a record not found error instead? throw new Exceptions\AccessDenied(null, $this->getAuthorizationAction(), $this->getResourceClass()); } } else { return $this->getResourceClass(); } }
The object that methods (such as "find", "new" or "build") are called on. If the 'through' option is passed it will go through an association on that instance. If the 'shallow' option is passed it will use the getResourceClass() method if there's no parent If the 'singleton' option is passed it won't use the association because it needs to be handled later.
entailment
protected function getCreateActions() { // We keep the 'new' option to match CanCan API $optionNew = array_key_exists('new', $this->options) ? $this->options['new'] : []; $optionCreate = array_key_exists('create', $this->options) ? $this->options['create'] : []; $options = array_merge((array) $optionNew, (array) $optionCreate); return array_unique(array_flatten(array_merge(['new', 'create', 'store'], $options))); }
And the Rails 'create' action is named 'store' in Laravel.
entailment
public function register() { $this->app->singleton('parameters', function ($app) { return new Parameters; }); // Find the default Controller class of the current Laravel application $controllerClass = $this->app['config']->get( 'authority-controller.controllerClass', 'Illuminate\Routing\Controller' ); $this->app->resolving(function ($object) use ($controllerClass) { // Check if the current $object class is a Controller class and if it responds to paramsBeforeFilter method if (is_a($object, $controllerClass) && respond_to($object, 'paramsBeforeFilter')) { // Fill $params properties of the current controller $this->app['parameters']->fillController($object); } }); $this->app->singleton('authority', function ($app) { $user = $app['auth']->user(); $authority = new Authority($user); $fn = $app['config']->get('authority-controller.initialize'); $serializer = new Serializer; if (is_string($fn)) { $fn = $serializer->unserialize($fn); } if ($fn) { $fn($authority); } return $authority; }); $this->app->bind('Efficiently\AuthorityController\ControllerResource', function ($app, $parameters) { list($controller, $resourceName, $resourceOptions) = $parameters; return new ControllerResource($controller, $resourceName, $resourceOptions); }); }
Register the service provider. @return void
entailment
public function push($query, array $parameters = array(), $tag = null) { if (null === $query) { throw new BoltInvalidArgumentException('Statement cannot be null'); } $this->messages[] = new RunMessage($query, $parameters, $tag); }
{@inheritdoc}
entailment
public function run() { $pullAllMessage = new PullAllMessage(); $batch = []; $resultCollection = new ResultCollection(); foreach ($this->messages as $message) { $result = $this->session->run($message->getStatement(), $message->getParams(), $message->getTag()); $resultCollection->add($result); } return $resultCollection; }
{@inheritdoc}
entailment
public function can($action, $resource, $resourceValue = null) { if (is_object($resource)) { $resourceValue = $resource; $resource = get_classname($resourceValue); } elseif (is_array($resource)) { // Nested resources can be passed through an associative array, this way conditions which are // dependent upon the association will work when using a class. $resourceValue = head(array_values($resource)); $resource = head(array_keys($resource)); } // The conditional callback (Closure) is only evaluated when an actual instance object is present. // It is not evaluated when checking permissions on the class name (such as in the 'index' action). $skipConditions = false; if (is_string($resource) && ! is_object($resourceValue) && $this->hasCondition($action, $resource)) { $skipConditions = true; } $self = $this; $rules = $this->getRulesFor($action, $resource); if (! $rules->isEmpty()) { $allowed = array_reduce($rules->all(), function ($result, $rule) use ($self, $resourceValue, $skipConditions) { if ($skipConditions) { return $rule->getBehavior(); // Short circuit } else { if ($rule->isRestriction()) { // 'deny' rules override prior rules. $result = $result && $rule->isAllowed($self, $resourceValue); } else { // 'allow' rules do not override prior rules but instead are logically or'ed. // Unlike Authority default behavior. $result = $result || $rule->isAllowed($self, $resourceValue); } } return $result; }, false); } else { $allowed = false; } return $allowed; }
Determine if current user can access the given action and resource @return boolean
entailment
public function addRule($allow, $actions, $resources, $condition = null) { $actions = (array) $actions; $resources = (array) $resources; $rules = []; foreach ($actions as $action) { foreach ($resources as $resource) { $rule = new Rule($allow, $action, $resource, $condition); $this->rules->add($rules[] = $rule); } } return $rules; }
Define rule(s) for a given action(s) and resource(s) @param boolean $allow True if privilege, false if restriction @param string|array $actions Action(s) for the rule(s) @param mixed $resources Resource(s) for the rule(s) @param Closure|null $condition Optional condition for the rule @return array
entailment
public function addRules($allow, $actions, $resources, $condition = null) { return $this->addRule($allow, $actions, $resources, $condition); }
alias of addRule()
entailment
public function addAlias($name, $actions) { $actions = (array) $actions; $this->addAliasAction($name, $actions); parent::addAlias($name, $this->getExpandActions($actions)); }
Define new alias for an action $this->$authority->addAlias('read', ['index', 'show']); $this->$authority->addAlias('create', 'new'); $this->$authority->addAlias('update', 'edit'); This way one can use $params['action'] in the controller to determine the permission. @param string $name Name of action @param string|array $actions Action(s) that $name aliases @return RuleAlias
entailment
public function getRulesFor($action, $resource) { $aliases = array_merge((array) $action, $this->getAliasesForAction($action)); return $this->rules->getRelevantRules($aliases, $resource); }
Returns all rules relevant to the given action and resource @return RuleRepository
entailment
public function getExpandActions($actions) { $actions = (array) $actions; return array_flatten(array_map(function ($action) use ($actions) { return array_key_exists($action, $this->getAliasedActions()) ? [$action, $this->getExpandActions($this->getAliasedActions()[$action])] : $action; }, $actions)); }
rely on the actions to be expanded.
entailment
public function getAliasesForAction($action) { $action = (array) $action; $results = []; foreach ($this->getAliasedActions() as $aliasedAction => $actions) { if (array_intersect($action, $actions)) { $results = array_merge($results, parent::getAliasesForAction($aliasedAction)); } } return array_unique($results); }
This does the opposite kind of lookup as 'getExpandActions()'.
entailment
public function read($n) { if (0 === $n) { return ''; } $remaining = ($n - $this->length) + $this->position; while ($remaining > 0) { //$this->io->wait(); if ($this->io->shouldEnableCrypto()) { $new = $this->io->read($remaining); } else { $new = $this->io->readChunk($remaining); } $this->bytes .= $new; $remaining -= strlen($new); } $this->length = strlen($this->bytes); $data = substr($this->bytes, $this->position, $n); $this->position += $n; return $data; }
@param int $n @return string
entailment
public static function driver($uri, ConfigInterface $config = null) { return new Driver(self::formatUri($uri), $config); }
@param string $uri @param BaseConfiguration|null $config @return Driver
entailment
public function handshake() { $packer = new Packer(); if (!$this->io->isConnected()) { $this->io->reconnect(); } $msg = ''; $msg .= chr(0x60).chr(0x60).chr(0xb0).chr(0x17); foreach (array(1, 0, 0, 0) as $v) { $msg .= $packer->packBigEndian($v, 4); } try { $this->io->write($msg); $rawHandshakeResponse = $this->io->read(4); $response = unpack('N', $rawHandshakeResponse); $version = $response[1]; if (0 === $version) { $this->throwHandshakeException(sprintf('Handshake Exception. Unable to negotiate a version to use. Proposed versions were %s', json_encode(array(1, 0, 0, 0)))); } return $version; } catch (IOException $e) { $this->throwHandshakeException($e->getMessage()); } }
@return int @throws HandshakeException
entailment
public function isRelevant($action, $resource) { // Nested resources can be passed through a associative array, this way conditions which are // dependent upon the association will work when using a class. $resource = is_array($resource) ? head(array_keys($resource)) : $resource; return parent::isRelevant($action, $resource); }
Determine if current rule is relevant based on an action and resource @param string|array $action Action in question @param string|mixed $resource Name of resource or instance of object @return boolean
entailment
public function matchesAction($action) { $action = (array) $action; return $this->action === 'manage' || in_array($this->action, $action); }
Determine if the instance's action matches the one passed in @param string|array $action Action in question @return boolean
entailment
public function fillController($controller) { $router = app('router'); $controllerClass = get_classname($controller); $paramsFilterPrefix = "router.filter: "; $paramsFilterName = "controller.parameters.".$controllerClass; if (! Event::hasListeners($paramsFilterPrefix.$paramsFilterName)) { Event::listen($paramsFilterPrefix.$paramsFilterName, function () use ($controller, $router) { $currentRoute = $router->current(); $resourceParams = []; list($resourceParams['controller'], $resourceParams['action']) = explode('@', $router->currentRouteAction()); $resourceParams['controller'] = $this->normalizeControllerName($resourceParams['controller']); $resourceId = str_singular($resourceParams['controller']); if (request()->has($resourceId)) { $params = request()->all(); } else { $specialInputKeys = $this->specialInputKeys(); $params = [$resourceId => request()->except($specialInputKeys)] + request()->only($specialInputKeys); } $routeParams = $currentRoute->parametersWithoutNulls(); // In Laravel, unlike Rails, by default 'id' parameter of a 'Product' resource is 'products' // And 'shop_id' parameter of a 'Shop' parent resource is 'shops' // So we need to reaffect correct parameter name before any controller's actions or filters. $routeParamsParsed = []; $keysToRemove = []; $lastRouteParamKey = last(array_keys($routeParams)); if ($lastRouteParamKey === 'id' || $resourceId === str_singular($lastRouteParamKey)) { $id = last($routeParams); if (is_a($id, 'Illuminate\Database\Eloquent\Model')) { $id = $id->getKey(); } if (is_string($id) || is_numeric($id)) { array_pop($routeParams); $routeParamsParsed['id'] = $id; } } foreach ($routeParams as $parentIdKey => $parentIdValue) { if (is_a($parentIdValue, 'Illuminate\Database\Eloquent\Model')) { $parentIdValue = $parentIdValue->getKey(); } if (is_string($parentIdValue) || is_numeric($parentIdValue)) { if (! ends_with($parentIdKey, '_id')) { $parentIdKey = str_singular($parentIdKey).'_id'; } $routeParamsParsed[$parentIdKey] = $parentIdValue; $keysToRemove[] = $parentIdKey; } } $routeParams = array_except($routeParams, $keysToRemove); /** * You can escape or purify these parameters. For example: * * class ProductsController extends Controller * { * public function __construct() * { * $self = $this; * $this->beforeFilter(function () use($self) { * if (array_get($self->params, 'product')) { * $productParams = $this->yourPurifyOrEscapeMethod('product'); * $self->params['product'] = $productParams; * } * }); * } * } * */ $this->params = array_filter(array_merge($params, $routeParams, $routeParamsParsed, $resourceParams)); if (property_exists($controller, 'params')) { set_property($controller, 'params', $this->params); } else { $controller->params = $this->params; } }); $controller->paramsBeforeFilter($paramsFilterName); } }
Fill the $params property of the given Controller @param \Illuminate\Routing\Controller $controller
entailment
public function only($keys = null) { $keys = is_array($keys) ? $keys : func_get_args(); return array_only($this->params, $keys); }
Get a subset of the items from the parameters. @param array $keys @return array
entailment
public function except($keys = null) { $keys = is_array($keys) ? $keys : func_get_args(); return array_except($this->params, $keys); }
Get all of the input except for a specified array of items. @param array $keys @return array
entailment
protected function specialInputKeys($inputKeys = []) { $inputKeys = $inputKeys ?: array_keys(request()->all()); return array_filter($inputKeys, function ($value) { return is_string($value) ? starts_with($value, '_') : false; }); }
Returns all inputs keys who starts with an underscore character (<code>_</code>). For exmaple '_method' and '_token' inputs @param array $inputKeys @return array
entailment
public function write($data) { //echo \GraphAware\Bolt\Misc\Helper::prettyHex($data) . PHP_EOL; $this->assertConnected(); $written = 0; $len = mb_strlen($data, 'ASCII'); while ($written < $len) { $buf = fwrite($this->sock, $data); if ($buf === false) { throw new IOException('Error writing data'); } if ($buf === 0 && feof($this->sock)) { throw new IOException('Broken pipe or closed connection'); } $written += $buf; } }
{@inheritdoc}
entailment
public function read($n) { if (null === $n) { return $this->readAll(); } $this->assertConnected(); $read = 0; $data = ''; while ($read < $n) { $buffer = fread($this->sock, ($n - $read)); //var_dump(\GraphAware\Bolt\Misc\Helper::prettyHex($buffer)); // check '' later for non-blocking mode use case if ($buffer === false || '' === $buffer) { throw new IOException('Error receiving data'); } $read += mb_strlen($buffer, 'ASCII'); $data .= $buffer; } return $data; }
{@inheritdoc}
entailment
public function select($sec, $usec) { $r = array($this->sock); $w = $e = null; $result = stream_select($r, $w, $e, $sec, $usec); return $result; }
{@inheritdoc}
entailment
public function connect() { $errstr = $errno = null; $remote = sprintf( '%s://%s:%s', $this->protocol, $this->host, $this->port ); $this->sock = stream_socket_client( $remote, $errno, $errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->context ); if (false === $this->sock) { throw new IOException(sprintf( 'Error to connect to the server(%s) : "%s"', $errno, $errstr )); } if ($this->shouldEnableCrypto()) { $result = stream_socket_enable_crypto($this->sock, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); if (true !== $result) { throw new \RuntimeException(sprintf('Unable to enable crypto on socket')); } } stream_set_read_buffer($this->sock, 0); return true; }
{@inheritdoc}
entailment
public function rollback() { $this->assertNotClosed(); $this->assertStarted(); $this->session->run('ROLLBACK'); $this->closed = true; $this->state = self::ROLLED_BACK; $this->session->transaction = null; }
{@inheritdoc}
entailment
public function begin() { $this->assertNotStarted(); $this->session->run('BEGIN'); $this->state = self::OPENED; }
{@inheritdoc}
entailment
public function run(Statement $statement) { try { return $this->session->run($statement->text(), $statement->parameters(), $statement->getTag()); } catch (MessageFailureException $e) { $spl = explode('.', $e->getStatusCode()); if (self::$NO_ROLLBACK_STATUS_CODE !== $spl[1]) { $this->state = self::ROLLED_BACK; $this->closed = true; } throw $e; } }
{@inheritdoc}
entailment
public function runMultiple(array $statements) { $pipeline = $this->session->createPipeline(); foreach ($statements as $statement) { $pipeline->push($statement->text(), $statement->parameters(), $statement->getTag()); } return $pipeline->run(); }
@param Statement[] $statements @return \GraphAware\Common\Result\ResultCollection
entailment
public function run($statement, array $parameters = array(), $tag = null) { if (null === $statement) { //throw new BoltInvalidArgumentException("Statement cannot be null"); } $messages = array( new RunMessage($statement, $parameters), ); $messages[] = new PullAllMessage(); $this->sendMessages($messages); $runResponse = new Response(); $r = $this->unpacker->unpack(); if ($r->isSuccess()) { $runResponse->onSuccess($r); } elseif ($r->isFailure()) { try { $runResponse->onFailure($r); } catch (MessageFailureException $e) { // server ignores the PULL ALL $this->handleIgnore(); $this->sendMessage(new AckFailureMessage()); // server success for ACK FAILURE $r2 = $this->handleSuccess(); throw $e; } } $pullResponse = new Response(); while (!$pullResponse->isCompleted()) { $r = $this->unpacker->unpack(); if ($r->isRecord()) { $pullResponse->onRecord($r); } if ($r->isSuccess()) { $pullResponse->onSuccess($r); } if ($r->isFailure()) { $pullResponse->onFailure($r); } } $cypherResult = new CypherResult(Statement::create($statement, $parameters, $tag)); $cypherResult->setFields($runResponse->getMetadata()[0]->getElements()); foreach ($pullResponse->getRecords() as $record) { $cypherResult->pushRecord($record); } $pullMeta = $pullResponse->getMetadata(); if (isset($pullMeta[0])) { if (isset($pullMeta[0]->getElements()['stats'])) { $cypherResult->setStatistics($pullResponse->getMetadata()[0]->getElements()['stats']); } else { $cypherResult->setStatistics([]); } } return $cypherResult; }
{@inheritdoc}
entailment
public function recv($statement, array $parameters = array(), $tag = null) { $runResponse = new Response(); $r = $this->unpacker->unpack(); $shouldThrow = false; if ($r->isFailure()) { try { $runResponse->onFailure($r); } catch (MessageFailureException $e) { // server ignores the PULL ALL $this->handleIgnore(); $this->handleIgnore(); $this->sendMessage(new AckFailureMessage()); $this->handleIgnore(); // server success for ACK FAILURE $r2 = $this->handleSuccess(); $shouldThrow = $e; } } if ($shouldThrow !== false) { throw $shouldThrow; } if ($r->isSuccess()) { $runResponse->onSuccess($r); } $pullResponse = new Response(); while (!$pullResponse->isCompleted()) { $r = $this->unpacker->unpack(); if ($r->isRecord()) { $pullResponse->onRecord($r); } if ($r->isSuccess()) { $pullResponse->onSuccess($r); } } $cypherResult = new CypherResult(Statement::create($statement, $parameters, $tag)); $cypherResult->setFields($runResponse->getMetadata()[0]->getElements()); foreach ($pullResponse->getRecords() as $record) { $cypherResult->pushRecord($record); } if (null !== $pullResponse && array_key_exists(0, $pullResponse->getMetadata())) { $metadata = $pullResponse->getMetadata()[0]->getElements(); $stats = array_key_exists('stats', $metadata) ? $metadata['stats'] : array(); $cypherResult->setStatistics($stats); } return $cypherResult; }
@param string $statement @param array $parameters @param null|string $tag @return CypherResult
entailment
public function validate($schema_config, $data) { $this->schema_config = $schema_config; if (isset($schema_config['prefix'])) { $this->prefix = $schema_config['prefix']; } return $this->validateNode('root', $schema_config['root'][$this->getFullName('type')], $schema_config['root'], $data ); }
main function
entailment
public function validateNode($name, $type, $node, $data) { $validator = $this->factory->getValidator($name, $type, $this); return $validator->validate($name, $node, $data); }
validate nodes
entailment
public function request($verb, array $params = array()) { if (! $this->url) { throw new RuntimeException("Cannot perform request when URL not set. Use setUrl() method"); } //Build the URL $params = array_merge(array('verb' => $verb), $params); $url = $this->url . (parse_url($this->url, PHP_URL_QUERY) ? '&' : '?') . http_build_query($params); //Do the request try { $resp = $this->httpAdapter->request($url); return $this->decodeResponse($resp); } catch (HttpException $e) { $this->checkForOaipmhException($e); } }
Perform a request and return a OAI SimpleXML Document @param string $verb Which OAI-PMH verb to use @param array $params An array of key/value parameters @return \SimpleXMLElement An XML document
entailment
private function checkForOaipmhException(HttpException $httpException) { try { if ($resp = $httpException->getBody()) { $this->decodeResponse($resp); // Throw OaipmhException in case of an error } } catch (MalformedResponseException $e) { // There was no valid OAI error in the response, therefore re-throw HttpException } throw $httpException; }
Check for OAI-PMH Exception from HTTP Exception Converts a HttpException into an OAI-PMH exception if there is an OAI-PMH Error Code. @param HttpException $httpException
entailment
protected function decodeResponse($resp) { //Setup a SimpleXML Document try { $xml = @new \SimpleXMLElement($resp); } catch (\Exception $e) { throw new MalformedResponseException(sprintf("Could not decode XML Response: %s", $e->getMessage())); } //If we get back a OAI-PMH error, throw a OaipmhException if (isset($xml->error)) { $code = (string) $xml->error['code']; $msg = (string) $xml->error; throw new OaipmhException($code, $msg); } return $xml; }
Decode the response into XML @param string $resp The response body from a HTTP request @return \SimpleXMLElement An XML document
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $formatter = $this->getHelper('formatter'); $call = $input->getOption('call'); if ($call == 'basic' || $call == 'all') { $data = $this->example->getBasicInformation(); $output->writeln("Basic information: "); foreach ($data as $key => $value) { $line = $formatter->formatSection($key, $value); $output->writeln($line); } } if ($call == 'formats' || $call == 'all') { $data = $this->example->getAvailableMetadataFormats(); $table = new Table($output); $output->writeln("Metadata formats: "); $table->setHeaders($data['header']); $table->setRows($data['rows']); $table->render(); } if ($call == 'records' || $call == 'all') { $data = $this->example->getRecords(); $table = new Table($output); $output->writeln("Ten records: "); $table->setHeaders($data['header']); $table->setRows($data['rows']); $table->render(); } if ($call == 'exception' || $call == 'all') { $data = $this->example->tryAnException(); } }
{@inheritdoc}
entailment
public static function formatDate(\DateTimeInterface $dateTime, $format) { $phpFormats = array( self::DATE => "Y-m-d", self::DATE_AND_TIME => 'Y-m-d\TH:i:s\Z', ); $phpFormat = $phpFormats[$format]; return $dateTime->format($phpFormat); }
Format DateTime string based on granularity @param \DateTimeInterface $dateTime @param string $format Either self::DATE or self::DATE_AND_TIME @return string
entailment
public function createContext(Registry $registry) { // List of schemas can evolve, but we don't want to generate new schema dynamically added, so we "clone" the array // to have a fixed list of schemas $schemas = array_values($registry->getSchemas()); /** @var Schema $schema */ foreach ($schemas as $schema) { $jsonSchema = $this->serializer->deserialize(file_get_contents($schema->getOrigin()), 'Joli\Jane\Model\JsonSchema', 'json', [ 'document-origin' => $schema->getOrigin() ]); $this->chainGuesser->guessClass($jsonSchema, $schema->getRootName(), $schema->getOrigin() . '#', $registry); } foreach ($registry->getSchemas() as $schema) { foreach ($schema->getClasses() as $class) { $properties = $this->chainGuesser->guessProperties($class->getObject(), $schema->getRootName(), $class->getReference(), $registry); foreach ($properties as $property) { $property->setType($this->chainGuesser->guessType($property->getObject(), $property->getName(), $property->getReference(), $registry)); } $class->setProperties($properties); } } return new Context($registry); }
Return a list of class guessed. @param $registry @return Context
entailment
public function generate($registry) { $context = $this->createContext($registry); $prettyPrinter = new Standard(); $modelFiles = []; $normalizerFiles = []; foreach ($registry->getSchemas() as $schema) { if (!file_exists(($schema->getDirectory().DIRECTORY_SEPARATOR.'Model'))) { mkdir($schema->getDirectory().DIRECTORY_SEPARATOR.'Model', 0755, true); } if (!file_exists(($schema->getDirectory().DIRECTORY_SEPARATOR.'Normalizer'))) { mkdir($schema->getDirectory().DIRECTORY_SEPARATOR.'Normalizer', 0755, true); } $context->setCurrentSchema($schema); $modelFiles = array_merge($modelFiles, $this->modelGenerator->generate($schema, $schema->getRootName(), $context)); $normalizerFiles = array_merge($normalizerFiles, $this->normalizerGenerator->generate($schema, $schema->getRootName(), $context)); } $generated = []; foreach ($modelFiles as $file) { $generated[] = $file->getFilename(); file_put_contents($file->getFilename(), $prettyPrinter->prettyPrintFile([$file->getNode()])); } foreach ($normalizerFiles as $file) { $generated[] = $file->getFilename(); file_put_contents($file->getFilename(), $prettyPrinter->prettyPrintFile([$file->getNode()])); } foreach ($registry->getSchemas() as $schema) { $this->fix($schema->getDirectory()); } return $generated; }
Generate code. @param Registry $registry @return array
entailment
public function getBasicInformation() { $data = array(); $xml = $this->endpoint->identify(); $data['Base URL'] = $xml->Identify->baseURL; $data['Repository Name'] = $xml->Identify->repositoryName; $data['Administrator'] = $xml->Identify->adminEmail; return $data; }
Retrieves the basic information from the endpoint. @return array An array of properties.
entailment
public function getAvailableMetadataFormats() { $data = array(); // List identifiers if (is_null($this->metadataIterator)) { $this->metadataIterator = $this->endpoint->listMetadataFormats(); } $data = array( 'header' => array('Metadata Prefix', 'Schema', 'Namespace'), 'rows' => array(), ); foreach ($this->metadataIterator as $rec) { $data['rows'][] = array( $rec->metadataPrefix, $rec->schema, $rec->metadataNamespace ); } return $data; }
Retrieve a list of available metadata format schemas from the endpoint. @return array An array containing data in a tabular format.
entailment
public function getRecords() { $data = array(); // List identifiers if (empty($this->metadataIterator)) { $this->metadataIterator = $this->endpoint->listMetadataFormats(); } else { $this->metadataIterator->rewind(); // rewind the iterator } // Auto-determine a metadata prefix to use for getting records $mdPrefix = (string) $this->metadataIterator->current()->metadataPrefix; $data = array( 'header' => array('Identifier', 'Title', 'usageDataResourceURL'), 'rows' => array(), ); // Iterate $recordIterator = $this->endpoint->listRecords($mdPrefix); for ($i = 0; $i < 10; $i++) { $rec = $recordIterator->next(); $data['rows'][] = array( $rec->header->identifier, // Truncate title substr($rec->metadata->commParadata->paradataTitle->string->__toString(), 0, 30), $rec->metadata->commParadata->usageDataResourceURL ); } return $data; }
Get a list of the first 10 records from the first available metadata format. @return array An array containing data in a tabular format.
entailment
public function tryAnException() { try { $iterator = $this->endpoint->listRecords('foobardoesnotexist'); $iterator->current(); } catch (\Phpoaipmh\Exception\OaipmhException $e) { throw $e; } }
Throws a deliberate exception for a non existing schema. @return void
entailment
public function generate($schema, $className, Context $context) { $files = []; $classes = []; foreach ($schema->getClasses() as $class) { $methods = []; $modelFqdn = $schema->getNamespace()."\\Model\\".$class->getName(); $methods[] = $this->createSupportsDenormalizationMethod($modelFqdn); $methods[] = $this->createSupportsNormalizationMethod($modelFqdn); $methods[] = $this->createDenormalizeMethod($modelFqdn, $context, $class->getProperties()); $methods[] = $this->createNormalizeMethod($modelFqdn, $context, $class->getProperties()); $normalizerClass = $this->createNormalizerClass( $class->getName().'Normalizer', $methods ); $classes[] = $normalizerClass->name; $namespace = new Stmt\Namespace_(new Name($schema->getNamespace()."\\Normalizer"), [ new Stmt\Use_([new Stmt\UseUse(new Name('Joli\Jane\Runtime\Reference'))]), new Stmt\Use_([new Stmt\UseUse(new Name('Symfony\Component\Serializer\Exception\InvalidArgumentException'))]), new Stmt\Use_([new Stmt\UseUse(new Name('Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface'))]), new Stmt\Use_([new Stmt\UseUse(new Name('Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait'))]), new Stmt\Use_([new Stmt\UseUse(new Name('Symfony\Component\Serializer\Normalizer\DenormalizerInterface'))]), new Stmt\Use_([new Stmt\UseUse(new Name('Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface'))]), new Stmt\Use_([new Stmt\UseUse(new Name('Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait'))]), new Stmt\Use_([new Stmt\UseUse(new Name('Symfony\Component\Serializer\Normalizer\NormalizerInterface'))]), $normalizerClass ]); $files[] = new File($schema->getDirectory().'/Normalizer/'.$class->getName().'Normalizer.php', $namespace, self::FILE_TYPE_NORMALIZER); } $files[] = new File( $schema->getDirectory().'/Normalizer/NormalizerFactory.php', new Stmt\Namespace_(new Name($schema->getNamespace()."\\Normalizer"), [ $this->createNormalizerFactoryClass($classes) ]), self::FILE_TYPE_NORMALIZER ); return $files; }
Generate a set of files given a schema @param Schema $schema Schema to generate from @param string $className Class to generate @param Context $context Context for generation @return File[]
entailment
protected function createSupportsNormalizationMethod($modelFqdn) { return new Stmt\ClassMethod('supportsNormalization', [ 'type' => Stmt\Class_::MODIFIER_PUBLIC, 'params' => [ new Param('data'), new Param('format', new Expr\ConstFetch(new Name('null'))), ], 'stmts' => [ new Stmt\If_( new Expr\Instanceof_(new Expr\Variable('data'), new Name('\\'.$modelFqdn)), [ 'stmts' => [ new Stmt\Return_(new Expr\ConstFetch(new Name('true'))), ], ] ), new Stmt\Return_(new Expr\ConstFetch(new Name('false'))), ], ]); }
Create method to check if denormalization is supported. @param string $modelFqdn Fully Qualified name of the model class denormalized @return Stmt\ClassMethod
entailment
protected function createNormalizeMethod($modelFqdn, Context $context, $properties) { $context->refreshScope(); $dataVariable = new Expr\Variable('data'); $statements = [ new Expr\Assign($dataVariable, new Expr\New_(new Name('\\stdClass'))), ]; /** @var Property $property */ foreach ($properties as $property) { $propertyVar = new Expr\MethodCall(new Expr\Variable('object'), $this->getNaming()->getPrefixedMethodName('get', $property->getName())); list($normalizationStatements, $outputVar) = $property->getType()->createNormalizationStatement($context, $propertyVar); $normalizationStatements[] = new Expr\Assign(new Expr\PropertyFetch($dataVariable, sprintf("{'%s'}", $property->getName())), $outputVar); if ($property->isNullable()) { $statements = array_merge($statements, $normalizationStatements); continue; } $statements[] = new Stmt\If_( new Expr\BinaryOp\NotIdentical(new Expr\ConstFetch(new Name('null')), $propertyVar), [ 'stmts' => $normalizationStatements, ] ); } $statements[] = new Stmt\Return_($dataVariable); return new Stmt\ClassMethod('normalize', [ 'type' => Stmt\Class_::MODIFIER_PUBLIC, 'params' => [ new Param('object'), new Param('format', new Expr\ConstFetch(new Name('null'))), new Param('context', new Expr\Array_(), 'array'), ], 'stmts' => $statements, ]); }
Create the normalization method. @param $modelFqdn @param Context $context @param $properties @return Stmt\ClassMethod
entailment
public function guessClass($object, $name, $reference, Registry $registry) { if (!$registry->hasClass($reference)) { $registry->getSchema($reference)->addClass($reference, new ClassGuess($object, $reference, $this->naming->getClassName($name))); } foreach ($object->getProperties() as $key => $property) { $this->chainGuesser->guessClass($property, $name . ucfirst($key), $reference . '/properties/' . $key, $registry); } }
{@inheritdoc}
entailment
public function guessProperties($object, $name, $reference, Registry $registry) { $properties = []; foreach ($object->getProperties() as $key => $property) { $propertyObj = $property; if ($propertyObj instanceof Reference) { $propertyObj = $this->resolve($propertyObj, $this->getSchemaClass()); } $type = $propertyObj->getType(); $nullable = $type == 'null' || (is_array($type) && in_array('null', $type)); $properties[] = new Property($property, $key, $reference . '/properties/' . $key, $nullable); } return $properties; }
{@inheritdoc}
entailment
public function guessType($object, $name, $reference, Registry $registry) { $discriminants = []; $required = $object->getRequired() ?: []; foreach ($object->getProperties() as $key => $property) { if (!in_array($key, $required)) { continue; } if ($property instanceof Reference) { $property = $this->resolve($property, $this->getSchemaClass()); } if ($property->getEnum() !== null) { $isSimple = true; foreach ($property->getEnum() as $value) { if (is_array($value) || is_object($value)) { $isSimple = false; } } if ($isSimple) { $discriminants[$key] = $property->getEnum(); } } else { $discriminants[$key] = null; } } if ($registry->hasClass($reference)) { return new ObjectType($object, $registry->getClass($reference)->getName(), $registry->getSchema($reference)->getNamespace(), $discriminants); } return new Type($object, 'object'); }
{@inheritdoc}
entailment
public function request($url) { try { $resp = $this->guzzle->get($url); return (string) $resp->getBody(); } catch (RequestException $e) { $response = $e->getResponse(); throw new HttpException($response ? $response->getBody() : null, $e->getMessage(), $e->getCode(), $e); } catch (TransferException $e) { throw new HttpException('', $e->getMessage(), $e->getCode(), $e); } }
Do the request with GuzzleAdapter @param string $url @return string @throws HttpException
entailment
protected function createPath(Filesystem $filesystem, $type) { $customPath = $this->option('path'); $defaultPath = config("vue-generators.paths.{$type}s"); $path = $customPath !== null ? $customPath : $defaultPath; $this->buildPathFromArray($path, $filesystem); return $path; }
Create path for file. @param Filesystem $filesystem @param string $type File type. @return string
entailment
public function supportObject($object) { if (!($object instanceof JsonSchema)) { return false; } if ($object->getType() !== 'object') { return false; } if ($object->getAdditionalProperties() !== true && !is_object($object->getAdditionalProperties())) { return false; } return true; }
{@inheritDoc}
entailment
public function guessType($object, $name, $reference, Registry $registry) { if ($object->getAdditionalProperties() === true) { return new MapType($object, new Type($object, 'mixed')); } return new MapType($object, $this->chainGuesser->guessType($object->getAdditionalProperties(), $name . 'Item', $reference . '/additionalProperties', $registry)); }
{@inheritDoc}
entailment
public function setCurlOpts(array $opts, $merge = true) { $this->curlOpts = ($merge) ? array_replace($this->curlOpts, $opts) : $opts; }
Set cURL Options at runtime Sets cURL options. If $merge is true, then merges desired params with existing. If $merge is false, then clobbers the existing cURL options @param array $opts @param bool $merge
entailment
public function request($url) { $curlOpts = array_replace($this->curlOpts, [CURLOPT_URL => $url]); $ch = curl_init(); foreach ($curlOpts as $opt => $optVal) { curl_setopt($ch, $opt, $optVal); } $resp = curl_exec($ch); $info = (object) curl_getinfo($ch); curl_close($ch); //Check response $httpCode = (string) $info->http_code; if ($httpCode{0} != '2') { $msg = sprintf('HTTP Request Failed (code %s): %s', $info->http_code, $resp); throw new HttpException($resp, $msg, $httpCode); } elseif (strlen(trim($resp)) == 0) { throw new HttpException($resp, 'HTTP Response Empty'); } return $resp; }
Do CURL Request @param string $url The full URL @return string The response body
entailment
public function guessType($object, $name, $reference, Registry $registry) { $items = $object->getItems(); if ($items === null) { return new ArrayType($object, new Type($object, 'mixed')); } if (!is_array($items)) { return new ArrayType($object, $this->chainGuesser->guessType($items, $name . 'Item', $reference . '/items', $registry)); } $type = new MultipleType($object); foreach ($items as $key => $item) { $type->addType(new ArrayType($object, $this->chainGuesser->guessType($item, $name . 'Item', $reference . '/items/' . $key, $registry))); } return $type; }
{@inheritDoc}
entailment
private function xmlToArray(\SimpleXMLIterator $sxi) { $a = array(); for ($sxi->rewind(); $sxi->valid(); $sxi->next()) { $t = array(); $current = $sxi->current(); $attributes = $current->attributes(); $name = isset($attributes->_key) ? strval($attributes->_key) : $sxi->key(); // save attributes foreach ($attributes as $att_key => $att_value) { if ($att_key !== '_key') { $t[$att_key] = strval($att_value); } } // we parse nodes if ($sxi->hasChildren()) { // children $t = array_merge($t, $this->xmlToArray($current)); } else { // it's a leaf if (empty($t)) { $t = strval($current); // strval will call _toString() } else { $t['_value'] = strval($current); // strval will call _toString() } } $a[$name] = $t; } return $a; }
/* Private XML parser
entailment
public function guessClass($object, $name, $reference, Registry $registry) { /** * @var string $key * @var JsonSchema $definition */ foreach ($object->getDefinitions() as $key => $definition) { $this->chainGuesser->guessClass($definition, $key, $reference . '/definitions/' . $key, $registry); if (is_a($definition, $this->getSchemaClass()) && $definition->getType() === "array") { $this->chainGuesser->guessClass($definition->getItems(), $key . 'Item', $reference . '/definitions/' . $key . '/items', $registry); } } }
{@inheritDoc}
entailment
public function handle() { $filesystem = new Filesystem(); $name = $this->argument('name').'.vue'; $path = $this->createPath($filesystem, 'component'); $fullPath = resource_path("{$path}/{$name}"); $this->checkFileExists($filesystem, $fullPath, $name); $stub = $this->getStub($filesystem); $filesystem->put($fullPath, $stub); $this->info("Component {$name} succesfully created."); }
Execute the console command.
entailment
protected function getStub(Filesystem $filesystem) { $fileName = $this->option('empty') ? 'EmptyComponent' : 'Component'; return $filesystem->get(__DIR__.'/../Stubs/'.$fileName.'.vue'); }
Get and return stub. @param Filesystem $filesystem @return string
entailment
public function nextItem() { if ($this->batch === null) { $this->batch = []; } //If no items in batch, and we have a resumptionToken or need to make initial request... if (count($this->batch) == 0 && ($this->resumptionToken or $this->numRequests == 0)) { $this->retrieveBatch(); } //if still items in current batch, return one if (count($this->batch) > 0) { $this->numProcessed++; $item = array_shift($this->batch); $this->currItem = clone $item; } else { $this->currItem = false; } return $this->currItem; }
Get the next item Return an item from the currently-retrieved batch, get next batch and return first record from it, or return false if no more records @return \SimpleXMLElement|bool
entailment
private function retrieveBatch() { // Set OAI-PMH parameters for request // If resumptionToken, then we ignore params and just use that $params = ($this->resumptionToken) ? ['resumptionToken' => $this->resumptionToken] : $this->params; // Node name and verb $nodeName = $this->getItemNodeName(); $verb = $this->verb; //Do it.. $resp = $this->oaipmhClient->request($verb, $params); $this->numRequests++; //Result format error? if (! isset($resp->$verb->$nodeName)) { throw new MalformedResponseException(sprintf( "Expected XML element list '%s' missing for verb '%s'", $nodeName, $verb )); } //Set the resumption token and expiration date, if specified in the response if (isset($resp->$verb->resumptionToken)) { $this->resumptionToken = (string) $resp->$verb->resumptionToken; if (isset($resp->$verb->resumptionToken['completeListSize'])) { $this->totalRecordsInCollection = (int) $resp->$verb->resumptionToken['completeListSize']; } if (isset($resp->$verb->resumptionToken['expirationDate'])) { $t = $resp->$verb->resumptionToken['expirationDate']; $this->expireDate = \DateTime::createFromFormat(\DateTime::ISO8601, $t); } } else { //Unset the resumption token when we're at the end of the list $this->resumptionToken = null; } //Process the results foreach ($resp->$verb->$nodeName as $node) { $this->batch[] = $node; } //Return a count return count($this->batch); }
Do a request to get the next batch of items @return int The number of items in the batch after the retrieve
entailment
private function getItemNodeName() { $mappings = array( 'ListMetadataFormats' => 'metadataFormat', 'ListSets' => 'set', 'ListIdentifiers' => 'header', 'ListRecords' => 'record' ); return (isset($mappings[$this->verb])) ? $mappings[$this->verb] : false; }
Get Item Node Name Map the item node name based on the verb @return string|boolean The element name for the mapping, or false if unmapped
entailment
public function reset() { $this->numRequests = 0; $this->numProcessed = 0; $this->currItem = null; $this->resumptionToken = null; $this->totalRecordsInCollection = null; $this->expireDate = null; $this->batch = []; }
Reset the request state
entailment
protected function registerCommands() { $this->app->singleton('command.vueg.component', function ($app) { return $app[MakeComponent::class]; }); $this->app->singleton('command.vueg.mixin', function ($app) { return $app[MakeMixin::class]; }); $this->commands('command.vueg.component'); $this->commands('command.vueg.mixin'); }
Register Artisan commands.
entailment
public function execute(InputInterface $input, OutputInterface $output) { $options = []; $configFile = null; if (!$input->hasOption('config-file') && file_exists('.jane')) { $configFile = '.jane'; } elseif($input->hasOption('config-file') && null !== $input->getOption('config-file')) { $configFile = $input->getOption('config-file'); } if ($configFile) { $configFile = $input->getOption('config-file'); if (!file_exists($configFile)) { throw new \RuntimeException(sprintf('Config file %s does not exist', $configFile)); } $options = require $configFile; if (!is_array($options)) { throw new \RuntimeException(sprintf('Invalid config file specified or invalid return type in file %s', $configFile)); } } else { if ($input->hasArgument('json-schema-file') && null !== $input->getArgument('json-schema-file')) { $options['json-schema-file'] = $input->getArgument('json-schema-file'); } if ($input->hasArgument('root-class') && null !== $input->getArgument('root-class')) { $options['root-class'] = $input->getArgument('root-class'); } if ($input->hasArgument('directory') && null !== $input->getArgument('directory')) { $options['directory'] = $input->getArgument('directory'); } if ($input->hasArgument('namespace') && null !== $input->getArgument('namespace')) { $options['namespace'] = $input->getArgument('namespace'); } if ($input->hasOption('date-format') && null !== $input->getOption('date-format')) { $options['date-format'] = $input->getOption('date-format'); } if ($input->hasOption('no-reference') && null !== $input->getOption('no-reference')) { $options['reference'] = !$input->getOption('no-reference'); } } $options = $this->resolveConfiguration($options); $registry = new Registry(); if (array_key_exists('json-schema-file', $options)) { $registry->addSchema($this->resolveSchema($options['json-schema-file'], $options)); } else { foreach ($options['mapping'] as $schema => $schemaOptions) { $registry->addSchema($this->resolveSchema($schema, $schemaOptions)); } } $jane = \Joli\Jane\Jane::build($options); if ($input->hasOption('fixer-config-file') && null !== $input->getOption('fixer-config-file')) { $fixerConfigFile = $input->getOption('fixer-config-file'); if (!file_exists($fixerConfigFile)) { throw new \RuntimeException(sprintf('Fixer config file %s could not be found', $fixerConfigFile)); } $configFile = require $fixerConfigFile; $jane->setFixerConfig($configFile); } $files = $jane->generate($registry); foreach ($files as $file) { $output->writeln(sprintf("Generated %s", $file)); } }
{@inheritdoc}
entailment
public function guessClass($object, $name, $reference, Registry $registry) { $hasSubObject = false; foreach ($object->getAllOf() as $allOf) { if ($this->resolve($allOf, $this->getSchemaClass())->getType() === 'object') { $hasSubObject = true; break; } } if ($hasSubObject) { if (!$registry->hasClass($reference)) { $registry->getSchema($reference)->addClass($reference, new ClassGuess($object, $reference, $this->naming->getClassName($name))); } foreach ($object->getAllOf() as $allOfIndex => $allOf) { if (is_a($allOf, $this->getSchemaClass())) { if ($allOf->getProperties()) { foreach ($allOf->getProperties() as $key => $property) { $this->chainGuesser->guessClass($property, $name . $key, $reference . '/allOf/' . $allOfIndex . '/properties/' . $key, $registry); } } } } } }
{@inheritdoc}
entailment
protected function createProperty($name, Type $type, $namespace, $default = null) { $propertyName = $this->getNaming()->getPropertyName($name); $property = new Stmt\PropertyProperty($propertyName); if ($default !== null) { $property->default = new Expr\ConstFetch(new Name($default)); } return new Stmt\Property(Stmt\Class_::MODIFIER_PROTECTED, [ $property ], [ 'comments' => [$this->createPropertyDoc($type, $namespace)] ]); }
Return a property stmt @param string $name @param Type $type @param string|null $default @return Stmt\Property
entailment
public function getTypeHint($namespace) { // We have exactly two types: one null and an object if (count($this->types) === 2) { list($type1, $type2) = $this->types; if ($this->isOptionalObjectType($type1, $type2)) { return $type2->getTypeHint($namespace); } if ($this->isOptionalObjectType($type2, $type1)) { return $type1->getTypeHint($namespace); } } return null; }
{@inheritdoc}
entailment
public function createDenormalizationStatement(Context $context, Expr $input) { $output = new Expr\Variable($context->getUniqueVariableName('value')); $statements = [ new Expr\Assign($output, $input) ]; foreach ($this->getTypes() as $type) { list($typeStatements, $typeOutput) = $type->createDenormalizationStatement($context, $input); $statements[] = new Stmt\If_( $type->createConditionStatement($input), [ 'stmts' => array_merge( $typeStatements, [ new Expr\Assign($output, $typeOutput) ] ) ] ); } return [$statements, $output]; }
{@inheritdoc}
entailment
protected function buildPathFromArray($path, Filesystem $filesystem = null) { $pathArray = collect(explode('/', $path))->prepend('resources'); if (is_null($filesystem)) { $filesystem = new Filesystem(); } $base = base_path(); foreach ($pathArray as $path) { $base = $base.'/'.$path; if (!$filesystem->exists($base)) { $filesystem->makeDirectory($base); } } }
Build directory tree from array of paths. @param string $path @param Filesystem|null $filesystem
entailment
protected function createSupportsDenormalizationMethod($modelFqdn) { return new Stmt\ClassMethod('supportsDenormalization', [ 'type' => Stmt\Class_::MODIFIER_PUBLIC, 'params' => [ new Param('data'), new Param('type'), new Param('format', new Expr\ConstFetch(new Name('null'))), ], 'stmts' => [ new Stmt\If_( new Expr\BinaryOp\NotIdentical(new Expr\Variable('type'), new Scalar\String_($modelFqdn)), [ 'stmts' => [ new Stmt\Return_(new Expr\ConstFetch(new Name('false'))), ], ] ), new Stmt\Return_(new Expr\ConstFetch(new Name('true'))), ], ]); }
Create method to check if denormalization is supported. @param string $modelFqdn Fully Qualified name of the model class denormalized @return Stmt\ClassMethod
entailment
protected function createDenormalizeMethod($modelFqdn, Context $context, $properties) { $context->refreshScope(); $objectVariable = new Expr\Variable('object'); $assignStatement = new Expr\Assign($objectVariable, new Expr\New_(new Name('\\'.$modelFqdn))); $statements = [$assignStatement]; if ($this->useReference) { $statements = [ new Stmt\If_( new Expr\Isset_([new Expr\PropertyFetch(new Expr\Variable('data'), "{'\$ref'}")]), [ 'stmts' => [ new Stmt\Return_(new Expr\New_(new Name('Reference'), [ new Expr\PropertyFetch(new Expr\Variable('data'), "{'\$ref'}"), new Expr\ArrayDimFetch(new Expr\Variable('context'), new Scalar\String_('document-origin')), ])), ], ] ), $assignStatement, ]; } array_unshift($statements, new Stmt\If_( new Expr\BooleanNot(new Expr\FuncCall(new Name('is_object'), [new Arg(new Expr\Variable('data'))])), [ 'stmts' => [ new Stmt\Throw_(new Expr\New_(new Name('InvalidArgumentException'))) ] ] )); foreach ($properties as $property) { $propertyVar = new Expr\PropertyFetch(new Expr\Variable('data'), sprintf("{'%s'}", $property->getName())); list($denormalizationStatements, $outputVar) = $property->getType()->createDenormalizationStatement($context, $propertyVar); $statements[] = new Stmt\If_( new Expr\FuncCall(new Name('property_exists'), [ new Arg(new Expr\Variable('data')), new Arg(new Scalar\String_($property->getName())), ]), [ 'stmts' => array_merge($denormalizationStatements, [ new Expr\MethodCall($objectVariable, $this->getNaming()->getPrefixedMethodName('set', $property->getName()), [ $outputVar, ]), ]), ] ); } $statements[] = new Stmt\Return_($objectVariable); return new Stmt\ClassMethod('denormalize', [ 'type' => Stmt\Class_::MODIFIER_PUBLIC, 'params' => [ new Param('data'), new Param('class'), new Param('format', new Expr\ConstFetch(new Name('null'))), new Param('context', new Expr\Array_(), 'array'), ], 'stmts' => $statements, ]); }
Create the denormalization method. @param $modelFqdn @param Context $context @param $properties @return Stmt\ClassMethod
entailment
protected function createModel($name, $properties, $methods) { return new Stmt\Class_( new Name($this->getNaming()->getClassName($name)), [ 'stmts' => array_merge($properties, $methods) ] ); }
Return a model class @param string $name @param Node[] $properties @param Node[] $methods @return Stmt\Class_
entailment
public function createConditionStatement(Expr $input) { return new Expr\FuncCall( new Name($this->conditionMapping[$this->name]), [ new Arg($input) ] ); }
Create the condition Statement @param Expr $input @return Expr
entailment
public function createNormalizationConditionStatement(Expr $input) { return new Expr\FuncCall( new Name($this->normalizationConditionMapping[$this->name]), [ new Arg($input) ] ); }
Create the condition Statement @param Expr $input @return Expr
entailment
public function avg($key = null) { if ($count = $this->count()) { return $this->sum($key) / $count; } }
Get the average value of a given key. @param string|null $key @return mixed
entailment
public function contains($key, $value = null): bool { if (func_num_args() == 2) { return $this->contains(function ($k, $item) use ($key, $value) { return ArrayHelper::getValue($item, $key) == $value; }); } if ($this->useAsCallable($key)) { return !is_null($this->first($key)); } return in_array($key, $this->items); }
Determine if an item exists in the collection. @param mixed $key @param mixed $value @return bool
entailment
public function where($key, $value, $strict = true) { return $this->filter(function ($item) use ($key, $value, $strict) { return $strict ? ArrayHelper::getValue($item, $key) === $value : ArrayHelper::getValue($item, $key) == $value; }); }
Filter items by the given key value pair. @param string $key @param mixed $value @param bool $strict @return static
entailment
public function whereIn($key, array $values, $strict = true) { return $this->filter(function ($item) use ($key, $values, $strict) { return in_array(ArrayHelper::getValue($item, $key), $values, $strict); }); }
Filter items by the given key value pair. @param string $key @param array $values @param bool $strict @return static
entailment
public function implode($value, $glue = ', ') { $first = $this->first(); if (is_array($first) || is_object($first)) { return implode($glue, $this->pluck($value)->all()); } return implode($value, $this->items); }
Concatenate values of a given key as a string. @param string $value @param string $glue @return string
entailment
public function pluck($value, $key = null) { return new static(ArrayHelper::pluck($this->items, $value, $key)); }
Get the values of a given key. @param string $value @param string|null $key @return static
entailment
public function max($key = null) { return $this->reduce(function ($result, $item) use ($key) { $value = ArrayHelper::getValue($item, $key); return is_null($result) || $value > $result ? $value : $result; }); }
Get the max value of a given key. @param string|null $key @return mixed
entailment
public function forPage(int $page, int $perPage) { return $this->slice(($page - 1) * $perPage, $perPage); }
"Paginate" the collection by slicing it into a smaller collection. @param int $page @param int $perPage @return static
entailment