sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function registerMethod(MethodInterface $method): CollectionInterface { $this->methods[\strtolower($method->getName())] = $method; return $this; }
{@inheritdoc}
entailment
public function getAdPolicyId(): \Psr\Http\Message\UriInterface { if (!$this->adPolicyId) { return new Uri(); } return $this->adPolicyId; }
Returns the id of the AdPolicy object this object is associated with. @return \Psr\Http\Message\UriInterface
entailment
public function getFileId(): \Psr\Http\Message\UriInterface { if (!$this->fileId) { return new Uri(); } return $this->fileId; }
Returns the id of the MediaFile object this object is associated with. @return \Psr\Http\Message\UriInterface
entailment
public function getRestrictionId(): \Psr\Http\Message\UriInterface { if (!$this->restrictionId) { return new Uri(); } return $this->restrictionId; }
Returns the id of the Restriction object this object is associated with. @return \Psr\Http\Message\UriInterface
entailment
public function getUrl(): \Psr\Http\Message\UriInterface { if (!$this->url) { return new Uri(); } return $this->url; }
Returns the public URL for this object. @return \Psr\Http\Message\UriInterface
entailment
public static function basicDiscovery(CustomFieldManager $customFieldManager = null) { if (!$customFieldManager) { $customFieldManager = CustomFieldManager::basicDiscovery(); } // @todo Check Drupal core for other tags to ignore? AnnotationReader::addGlobalIgnoredName('class'); AnnotationRegistry::registerFile(__DIR__.'/Annotation/DataService.php'); $discovery = new DataServiceDiscovery('\\Lullabot\\Mpx', 'src', __DIR__.'/../..', new AnnotationReader(), $customFieldManager); return new static($discovery); }
Register our annotations, relative to this file. @param CustomFieldManager $customFieldManager (optional) The manager used to discover custom fields. @return static
entailment
public function getDataService(string $name, string $objectType, string $schema) { $services = $this->discovery->getDataServices(); if (isset($services[$name][$objectType][$schema])) { return $services[$name][$objectType][$schema]; } throw new \RuntimeException('Data service not found.'); }
Returns one data service by service. @param string $name @param string $objectType @param string $schema @return DiscoveredDataService
entailment
public function setMatchType(string $matchType): self { if (!isset($this->field)) { throw new \LogicException(); } $this->matchType = $matchType; return $this; }
@param string $matchType @return Term
entailment
private function renderField(string $value): string { if (isset($this->field)) { $field = ''; if (isset($this->namespace)) { $field = $this->namespace.'$'; } $field .= $this->field; if (isset($this->matchType)) { $field .= '.'.$this->matchType; } $value .= $field.':'; } return $value; }
Add the field specification to the term string. @param string $value The current term value. @return string The value with the attached field, if set.
entailment
public function prepareTableDefinition($table) { $tableDefintion = ''; $definitions = $this->calibrateDefinitions($table); foreach ($definitions as $column) { $columnDefinition = explode(':', $column); $tableDefintion .= "\t\t'$columnDefinition[0]',\n"; } return $tableDefintion; }
Prepare a string of the table. @param string $table @return string
entailment
public function prepareTableExample($table) { $tableExample = ''; $definitions = $this->calibrateDefinitions($table); foreach ($definitions as $key => $column) { $columnDefinition = explode(':', $column); $example = $this->createExampleByType($columnDefinition[1]); if ($key === 0) { $tableExample .= "'$columnDefinition[0]' => '$example',\n"; } else { $tableExample .= "\t\t'$columnDefinition[0]' => '$example',\n"; } } return $tableExample; }
Prepare a table array example. @param string $table @return string
entailment
public function getTableSchema($config, $string) { if (!empty($config['schema'])) { $string = str_replace('// _camel_case_ table data', $this->prepareTableExample($config['schema']), $string); } return $string; }
Build a table schema. @param array $config @param string $string @return string
entailment
public function createExampleByType($type) { $faker = Faker::create(); $typeArray = [ 'bigIncrements' => 1, 'increments' => 1, 'string' => $faker->word, 'boolean' => 1, 'binary' => implode(" ", $faker->words(10)), 'char' => 'a', 'ipAddress' => '192.168.1.1', 'macAddress' => 'X1:X2:X3:X4:X5:X6', 'json' => json_encode(['json' => 'test']), 'text' => implode(" ", $faker->words(4)), 'longText' => implode(" ", $faker->sentences(4)), 'mediumText' => implode(" ", $faker->sentences(2)), 'dateTime' => date('Y-m-d h:i:s'), 'date' => date('Y-m-d'), 'time' => date('h:i:s'), 'timestamp' => time(), 'float' => 1.1, 'decimal' => 1.1, 'double' => 1.1, 'integer' => 1, 'bigInteger' => 1, 'mediumInteger' => 1, 'smallInteger' => 1, 'tinyInteger' => 1, ]; if (isset($typeArray[$type])) { return $typeArray[$type]; } return 1; }
Create an example by type for table definitions. @param string $type @return mixed
entailment
public function tableDefintion($table) { $columnStringArray = []; $columns = $this->getTableColumns($table, true); foreach ($columns as $key => $column) { if ($key === 'id') { $column['type'] = 'increments'; } $columnStringArray[] = $key.':'.$this->columnNameCheck($column['type']); } $columnString = implode(',', $columnStringArray); return $columnString; }
Table definitions. @param string $table @return string
entailment
public function getTableColumns($table, $allColumns = false) { $tableColumns = Schema::getColumnListing($table); $tableTypeColumns = []; $badColumns = ['id', 'created_at', 'updated_at']; if ($allColumns) { $badColumns = []; } foreach ($tableColumns as $column) { if (!in_array($column, $badColumns)) { $type = DB::connection()->getDoctrineColumn($table, $column)->getType()->getName(); $tableTypeColumns[$column]['type'] = $type; } } return $tableTypeColumns; }
Get Table Columns. @param string $table Table name @return array
entailment
private function discoverDataServices() { $path = $this->rootDir.'/'.$this->directory; $finder = new Finder(); $finder->files()->in($path); /** @var SplFileInfo $file */ foreach ($finder as $file) { $class = $this->classForFile($file); /* @var \Lullabot\Mpx\DataService\Annotation\DataService $annotation */ $annotation = $this->annotationReader->getClassAnnotation(new \ReflectionClass($class), 'Lullabot\Mpx\DataService\Annotation\DataService'); if (!$annotation) { continue; } // Now that we have a new data service, we need to attach any // custom field implementations. $customFields = $this->getCustomFields($annotation); $this->dataServices[$annotation->getService()][$annotation->getObjectType()][$annotation->getSchemaVersion()] = new DiscoveredDataService($class, $annotation, $customFields); } }
Discovers data services.
entailment
private function getCustomFields(DataService $annotation): array { $fields = $this->customFieldManager->getCustomFields(); $customFields = []; if (isset($fields[$annotation->getService()][$annotation->getObjectType()])) { $customFields = $fields[$annotation->getService()][$annotation->getObjectType()]; } return $customFields; }
Return the array of custom fields for an annotation. @param DataService $annotation The Data Service annotation being discovered. @return DiscoveredCustomField[] An array of custom field definitions.
entailment
public function getUrl(bool $insecure = false): UriInterface { $url = $this->resolveAllUrlsResponse[array_rand($this->resolveAllUrlsResponse)]; if ($insecure) { return $url; } return $url->withScheme('https'); }
Return the resolved URL for this service. @param bool $insecure (optional) Set to true to request the insecure version of this service. @return UriInterface
entailment
public function run() { parent::run(); if ($this->enableAjaxSubmit) { $id = $this->options['id']; $view = $this->getView(); AjaxFormAsset::register($view); $_options = Json::htmlEncode($this->ajaxSubmitOptions); $view->registerJs("jQuery('#$id').yiiActiveForm().on('beforeSubmit', function(_event) { jQuery(_event.target).ajaxSubmit($_options); return false;});"); } }
{@inheritdoc}
entailment
public function search($term, $params = array()) { $params = $this->getSearchParams($term, $params); $results = $this->http->get($this->request('search', $params))->json(); return $results ?: $this->emptyResults(); }
Search the API for a term. @param string $term @param array $params @return object
entailment
public function searchRegion($region, $term, $params = array()) { return $this->search($term, array_merge(array('country' => strtoupper($region)), $params)); }
Search withing a defined region. @param string $region @param string $term @param array $params @return obejct
entailment
public function lookup($id, $value = null, $params = array()) { $results = $this->http->get($this->request('lookup', $this->getLookupParams($id, $value, $params)))->json(); return $results ?: $this->emptyResults(); }
Lookup an item in the API. @param string $item @param array $params @return object
entailment
public function specificMediaSearch($method, $arguments) { if (isset($arguments[0])) { $params = array(); if (strpos($method, 'InRegion') !== false && isset($arguments[1])) { // performing regional search list($region, $term) = $arguments; $params['country'] = strtoupper($region); // remove InRegion to get the media type out of the method name $media = str_replace('InRegion', '', $method); $term = $arguments[1]; } else { $media = $method; $term = $arguments[0]; } $params['media'] = $media; if (count($arguments) > 1 && is_array($arguments[count($arguments) - 1])) { $params = array_merge($arguments[count($arguments) - 1], $params); } return $this->search($term, $params); } throw new InvalidSearchException('Missing arguments for search'); }
This method is automatically called through the __call method. A convenience in order to be able to perform searches like:. music($term); musicInRegion($region, $term); tvShow($show); tvShowInregion($region, $show); @param string $method @param array $arguments @return object
entailment
public function request($type, $params = array()) { if (isset($this->iTunesConfig['api'])) { if ( isset($this->iTunesConfig['api']['url']) && isset($this->iTunesConfig['api']['search_uri']) && isset($this->iTunesConfig['api']['lookup_uri']) ) { $host = $this->iTunesConfig['api']['url']; switch ($type) { case 'search': default: $uri = $this->iTunesConfig['api']['search_uri']; $params = array_merge( array( 'limit' => isset($this->iTunesConfig['limit']) ? $this->iTunesConfig['limit'] : 50, ), $params ); break; case 'lookup': $uri = $this->iTunesConfig['api']['lookup_uri']; break; } return array( 'url' => $host.$uri, 'params' => $params, ); } } throw new ConfigurationException('Incomplete Configuration'); }
Builds up the request array. @param string $type supported: search | lookup @param string $term @param array $params @return array
entailment
protected function getLookupParams($id, $value, array $params) { // Make the id default if (!$value) { $value = $id; $id = 'id'; } return array_merge(array($id => $value), $params); }
Get the query params for a lookup request. @param string $id @param string $value @param array $params @return array
entailment
public function resolve(IdInterface $account): ResolveDomainResponse { $key = md5($account->getMpxId().static::SCHEMA_VERSION); $item = $this->cache->getItem($key); if ($item->isHit()) { return $item->get(); } $options = [ 'query' => [ 'schema' => static::SCHEMA_VERSION, '_accountId' => (string) $account->getMpxId(), 'account' => (string) $account->getMpxId(), ], ]; $response = $this->authenticatedClient->request('GET', static::RESOLVE_DOMAIN_URL, $options); $encoders = [new JsonEncoder()]; $normalizers = [new UriNormalizer(), new ObjectNormalizer(null, null, null, new ResolveDomainResponseExtractor()), new ArrayDenormalizer()]; $serializer = new Serializer($normalizers, $encoders); $resolved = $serializer->deserialize($response->getBody(), ResolveDomainResponse::class, 'json'); $item->set($resolved); // thePlatform provides no guidance on how long we can cache this for. // Since many of their examples and other mpx clients hardcode these // values, we assume 30 days and that they will implement redirects or // domain aliases if required. $item->expiresAfter(new \DateInterval('P30D')); $this->cache->save($item); return $resolved; }
Resolve all URLs for an account. @param IdInterface $account The account to resolve service URLs for. @return ResolveDomainResponse A response with the service URLs.
entailment
public function setToken(UserSession $user, Token $token) { $item = $this->cacheItemPool->getItem($this->cacheKey($user)); $item->set($token); // @todo Test that these values are compatible. $item->expiresAfter($token->getLifetime()); $this->cacheItemPool->save($item); }
Set an authentication token for a user. @param \Lullabot\Mpx\Service\IdentityManagement\UserSession $user The user the token is associated with. @param \Lullabot\Mpx\Token $token The authentication token for the user.
entailment
public function getToken(UserSession $user): Token { // @todo Test that the expiresAfter() call works. We don't want to be caught // by cron etc. $item = $this->cacheItemPool->getItem($this->cacheKey($user)); if (!$item->isHit()) { throw new TokenNotFoundException($user); } return $item->get(); }
Get the cached token for a user. @param \Lullabot\Mpx\Service\IdentityManagement\UserSession $user The user to look up tokens for. @return \Lullabot\Mpx\Token The cached token.
entailment
protected function getUserByToken($token) { $params = [ 'format' => 'json', 'method' => 'users.getCurrentUser', 'application_key' => $this->getConfig('client_public', env('ODNOKLASSNIKI_PUBLIC')), 'fields' => 'uid,name,first_name,last_name,birthday,pic190x190,has_email,email' ]; ksort($params, SORT_STRING); $_params = array_map(function($key, $value) { return $key . '=' . $value; }, array_keys($params), array_values($params)); $params['sig'] = md5(implode('', $_params) . md5($token . $this->clientSecret)); $params['access_token'] = $token; $response = $this->getHttpClient()->get( 'https://api.ok.ru/fb.do?' . http_build_query($params) ); return json_decode($response->getBody(), true); }
{@inheritdoc}
entailment
public function title($value = null) { $this->options = array_merge($this->options, ['title' => ($value == null ? $this->name : $value)] ); return $this; }
Adds title attribute @param string $value @return self If $value == null then the flag identifier is used
entailment
public function id($value = null) { $this->options = array_merge($this->options, ['id' => ($value == null ? $this->name : $value)] ); return $this; }
Adds id attribute @param string $value @return self If $value == null then the flag identifier is used
entailment
public function search($params) { $query = Gallery::find()->joinWith('galleryPhotos', false)->groupBy('g_gallery.gallery_id'); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort'=> ['defaultOrder' => ['date'=>SORT_DESC]] ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere([ 'gallery_id' => $this->gallery_id, 'date' => $this->date, ]); $query->andFilterWhere(['like', 'name', $this->name]) ->andFilterWhere(['like', 'descr', $this->descr]); return $dataProvider; }
Creates data provider instance with search query applied @param array $params @return ActiveDataProvider
entailment
public function prepareModelRelationships($relationships) { $relationshipMethods = ''; foreach ($relationships as $relation) { if (!isset($relation[2])) { $relationEnd = explode('\\', $relation[1]); $relation[2] = strtolower(end($relationEnd)); } $method = str_singular($relation[2]); if (stristr($relation[0], 'many')) { $method = str_plural($relation[2]); } $relationshipMethods .= "\n\tpublic function ".$method.'() {'; $relationshipMethods .= "\n\t\treturn \$this->$relation[0]($relation[1]::class);"; $relationshipMethods .= "\n\t}\n\t"; } return $relationshipMethods; }
Prepare a models relationships. @param array $relationships @return string
entailment
public function configTheModel($config, $model) { if (!empty($config['schema'])) { $model = str_replace('// _camel_case_ table data', $this->tableService->prepareTableDefinition($config['schema']), $model); } if (!empty($config['relationships'])) { $relationships = []; foreach (explode(',', $config['relationships']) as $relationshipExpression) { $relationships[] = explode('|', $relationshipExpression); } $model = str_replace('// _camel_case_ relationships', $this->prepareModelRelationships($relationships), $model); } return $model; }
Configure the model. @param array $config @param string $model @return string
entailment
private function mergeAuth(array $options, bool $reset = false): array { if (!isset($options['query'])) { $options['query'] = []; } $token = $this->userSession->acquireToken($this->duration, $reset); $options['query'] += [ 'token' => $token->getValue(), ]; return $options; }
Merge authentication headers into request options. @param array $options The array of request options. @param bool $reset Acquire a new token even if one is cached. @return array The updated request options.
entailment
private function sendAsyncWithRetry(RequestInterface $request, array $options) { // This is the initial API request that we expect to pass. $merged = $this->mergeAuth($options); $inner = $this->client->sendAsync($request, $merged); // However, if it fails, we need to try a second request. We can't // create the second request method outside of the promise body as we // need a new invocation of mergeAuth() that resets the token. $outer = $this->outerPromise($inner); $inner->then(function ($value) use ($outer) { // The very first request worked, so resolve the outer promise. $outer->resolve($value); }, function ($e) use ($request, $options, $outer) { // Only retry if it's a token auth error. if (!$this->isTokenAuthError($e)) { $outer->reject($e); return; } $merged = $this->mergeAuth($options, true); $func = [$this->client, 'send']; $args = [$request, $merged]; $this->finallyResolve($outer, $func, $args); }); return $outer; }
Send a request, retrying once if the authentication token is invalid. @param \Psr\Http\Message\RequestInterface $request The request to send. @param array $options Request options to apply. @return \GuzzleHttp\Promise\PromiseInterface|\Psr\Http\Message\RequestInterface
entailment
private function sendWithRetry(RequestInterface $request, array $options) { $merged = $this->mergeAuth($options); try { return $this->client->send($request, $merged); } catch (ClientException $e) { // Only retry if MPX has returned that the existing token is no // longer valid. if (!$this->isTokenAuthError($e)) { throw $e; } $merged = $this->mergeAuth($options, true); return $this->client->send($request, $merged); } }
Send a request, retrying once if the authentication token is invalid. @param \Psr\Http\Message\RequestInterface $request The request to send. @param array $options An array of request options. @return \Psr\Http\Message\ResponseInterface
entailment
private function requestAsyncWithRetry(string $method, $uri, array $options) { // This is the initial API request that we expect to pass. $merged = $this->mergeAuth($options); $inner = $this->client->requestAsync($method, $uri, $merged); // However, if it fails, we need to try a second request. We can't // create the second request method outside of the promise body as we // need a new invocation of mergeAuth() that resets the token. $outer = $this->outerPromise($inner); $inner->then(function ($value) use ($outer) { // The very first request worked, so resolve the outer promise. $outer->resolve($value); }, function ($e) use ($method, $uri, $options, $outer) { // Only retry if it's a token auth error. if (!$this->isTokenAuthError($e)) { $outer->reject($e); return; } $merged = $this->mergeAuth($options, true); $func = [$this->client, 'request']; $args = [$method, $uri, $merged]; $this->finallyResolve($outer, $func, $args); }); return $outer; }
Create and send a request, retrying once if the authentication token is invalid. @param string $method HTTP method @param string|\Psr\Http\Message\UriInterface $uri URI object or string. @param array $options Request options to apply. @return \GuzzleHttp\Promise\PromiseInterface|\Psr\Http\Message\RequestInterface
entailment
private function finallyResolve(PromiseInterface $promise, callable $callable, $args) { try { // Since we must have blocked to get to this point, we now use // a blocking request to resolve things once and for all. $promise->resolve(\call_user_func_array($callable, $args)); } catch (\Exception $e) { $promise->reject($e); } }
Resolve or reject a promise by invoking a callable. @param \GuzzleHttp\Promise\PromiseInterface $promise @param callable $callable @param array $args
entailment
private function requestWithRetry(string $method, $uri, array $options) { try { $merged = $this->mergeAuth($options); return $this->client->request($method, $uri, $merged); } catch (ClientException $e) { // Only retry if MPX has returned that the existing token is no // longer valid. if (!$this->isTokenAuthError($e)) { throw $e; } $merged = $this->mergeAuth($options, true); return $this->client->request($method, $uri, $merged); } }
Create and send a request, retrying once if the authentication token is invalid. This method intentionally doesn't call requestAsyncWithRetry and wait() on the promise, as we want to make sure the underlying sync client methods are used. @param string $method HTTP method @param string|\Psr\Http\Message\UriInterface $uri URI object or string. @param array $options Request options to apply. @return \Psr\Http\Message\ResponseInterface The response.
entailment
private function outerPromise(PromiseInterface $inner): Promise { $outer = new Promise(function () use ($inner) { // Our wait function invokes the inner's wait function, as as far // as callers are concerned there is only one promise. try { $inner->wait(); } catch (\Exception $e) { // The inner promise handles all rejections. } }); return $outer; }
Return a new promise that waits on another promise. @param \GuzzleHttp\Promise\PromiseInterface $inner @return \GuzzleHttp\Promise\Promise
entailment
public function isAvailable(Media $media, \DateTime $time) { return $this->between($time, $media->getAvailableDate(), $media->getExpirationDate()); }
Return if the media is available as of the given time. @param Media $media @param $time @return bool
entailment
private function between(\DateTime $time, DateTimeFormatInterface $start, DateTimeFormatInterface $end) { return $this->after($time, $start) && $this->before($time, $end); }
Return if a time is between a start and end time. @param \DateTime $time @param DateTimeFormatInterface $start @param DateTimeFormatInterface $end @return bool
entailment
private function before(\DateTime $time, DateTimeFormatInterface $other) { if ($other instanceof ConcreteDateTimeInterface) { // If the other time is the Unix epoch, the time should represent // the "end of all time". // @see https://docs.theplatform.com/help/media-media-expirationdate if ($this->isEpoch($other)) { return true; } return $time <= $other->getDateTime(); } // The other time is a NullDateTime, so we take this to mean the video // is available. return true; }
Return if a time is equal to or before the other time. @param \DateTime $time @param DateTimeFormatInterface $other @return bool
entailment
public function createController($config) { $this->fileService->mkdir($config['_path_controller_'], 0777, true); $request = $this->fileService->get($config['template_source'].'/Controller.txt'); foreach ($config as $key => $value) { $request = str_replace($key, $value, $request); } $request = $this->putIfNotExists($config['_path_controller_'].'/'.$config['_ucCamel_casePlural_'].'Controller.php', $request); return $request; }
Create the controller. @param array $config @return bool
entailment
public function createModel($config) { $repoParts = [ '_path_model_', ]; foreach ($repoParts as $repoPart) { $this->fileService->mkdir($config[$repoPart], 0777, true); } $model = $this->fileService->get($config['template_source'].'/Model.txt'); $model = $this->modelService->configTheModel($config, $model); foreach ($config as $key => $value) { $model = str_replace($key, $value, $model); } $model = $this->putIfNotExists($config['_path_model_'].'/'.$config['_camel_case_'].'.php', $model); return $model; }
Create the model. @param array $config @return bool
entailment
public function createRequest($config) { $this->fileService->mkdir($config['_path_request_'], 0777, true); $createRequest = $this->fileService->get($config['template_source'].'/CreateRequest.txt'); $updateRequest = $this->fileService->get($config['template_source'].'/UpdateRequest.txt'); foreach ($config as $key => $value) { $createRequest = str_replace($key, $value, $createRequest); $updateRequest = str_replace($key, $value, $updateRequest); } $createRequest = $this->putIfNotExists($config['_path_request_'].'/'.$config['_camel_case_'].'CreateRequest.php', $createRequest); $updateRequest = $this->putIfNotExists($config['_path_request_'].'/'.$config['_camel_case_'].'UpdateRequest.php', $updateRequest); return $createRequest; }
Create the request. @param array $config @return bool
entailment
public function createService($config) { $this->fileService->mkdir($config['_path_service_'], 0777, true); $service = $this->fileService->get($config['template_source'].'/Service.txt'); if ($config['options-withBaseService'] ?? false) { $baseService = $this->fileService->get($config['template_source'].'/BaseService.txt'); $service = $this->fileService->get($config['template_source'].'/ExtendedService.txt'); } foreach ($config as $key => $value) { $service = str_replace($key, $value, $service); if ($config['options-withBaseService'] ?? false) { $baseService = str_replace($key, $value, $baseService); } } $service = $this->putIfNotExists($config['_path_service_'].'/'.$config['_camel_case_'].'Service.php', $service); if ($config['options-withBaseService'] ?? false) { $this->putIfNotExists($config['_path_service_'].'/BaseService.php', $baseService); } return $service; }
Create the service. @param array $config @return bool
entailment
public function createRoutes($config) { $routesMaster = $config['_path_routes_']; if (!empty($config['routes_prefix'])) { $this->filesystem->append($routesMaster, $config['routes_prefix']); } $routes = $this->fileService->get($config['template_source'].'/Routes.txt'); foreach ($config as $key => $value) { $routes = str_replace($key, $value, $routes); } $this->filesystem->append($routesMaster, $routes); if (!empty($config['routes_prefix'])) { $this->filesystem->append($routesMaster, $config['routes_suffix']); } return true; }
Create the routes. @param array $config @return bool
entailment
public function createFactory($config) { $this->fileService->mkdir(dirname($config['_path_factory_']), 0777, true); if (!file_exists($config['_path_factory_'])) { $this->putIfNotExists($config['_path_factory_'], '<?php'); } $factory = $this->fileService->get($config['template_source'].'/Factory.txt'); $factory = $this->tableService->getTableSchema($config, $factory); foreach ($config as $key => $value) { $factory = str_replace($key, $value, $factory); } return $this->filesystem->append($config['_path_factory_'], $factory); }
Append to the factory. @param array $config @return bool
entailment
public function createFacade($config) { $this->fileService->mkdir($config['_path_facade_'], 0777, true); $facade = $this->fileService->get($config['template_source'].'/Facade.txt'); foreach ($config as $key => $value) { $facade = str_replace($key, $value, $facade); } $facade = $this->putIfNotExists($config['_path_facade_'].'/'.$config['_camel_case_'].'.php', $facade); return $facade; }
Create the facade. @param array $config @return bool
entailment
public function generatePackageServiceProvider($config) { $provider = $this->fileService->get(__DIR__.'/../Templates/Provider.txt'); foreach ($config as $key => $value) { $provider = str_replace($key, $value, $provider); } $provider = $this->putIfNotExists($config['_path_package_'].'/'.$config['_camel_case_'].'ServiceProvider.php', $provider); return $provider; }
Create a service provider. @param array $config @return bool
entailment
public function createViews($config) { $this->fileService->mkdir($config['_path_views_'].'/'.$config['_lower_casePlural_'], 0777, true); $viewTemplates = 'Views'; if ($config['bootstrap']) { $viewTemplates = 'BootstrapViews'; } if ($config['semantic']) { $viewTemplates = 'SemanticViews'; } $createdView = false; foreach (glob($config['template_source'].'/'.$viewTemplates.'/*') as $file) { $viewContents = $this->fileService->get($file); $basename = str_replace('txt', 'php', basename($file)); foreach ($config as $key => $value) { $viewContents = str_replace($key, $value, $viewContents); } $createdView = $this->putIfNotExists($config['_path_views_'].'/'.$config['_lower_casePlural_'].'/'.$basename, $viewContents); } return $createdView; }
Create the views. @param array $config @return bool
entailment
public function createApi($config) { $routesMaster = $config['_path_api_routes_']; if (!file_exists($routesMaster)) { $this->putIfNotExists($routesMaster, "<?php\n\n"); } $this->fileService->mkdir($config['_path_api_controller_'], 0777, true); $routes = $this->fileService->get($config['template_source'].'/ApiRoutes.txt'); foreach ($config as $key => $value) { $routes = str_replace($key, $value, $routes); } $this->filesystem->append($routesMaster, $routes); $request = $this->fileService->get($config['template_source'].'/ApiController.txt'); foreach ($config as $key => $value) { $request = str_replace($key, $value, $request); } $request = $this->putIfNotExists($config['_path_api_controller_'].'/'.$config['_ucCamel_casePlural_'].'Controller.php', $request); return $request; }
Create the Api. @param array $config @return bool
entailment
public function putIfNotExists($file, $contents) { if (!$this->filesystem->exists($file)) { return $this->filesystem->put($file, $contents); } return $this->fileService->get($file); }
Make a file if it doesnt exist. @param string $file @param mixed $contents @return void
entailment
public function register() { /* |-------------------------------------------------------------------------- | Providers |-------------------------------------------------------------------------- */ if (class_exists('Illuminate\Foundation\AliasLoader')) { $this->app->register(FormMakerProvider::class); } /* |-------------------------------------------------------------------------- | Register the Commands |-------------------------------------------------------------------------- */ $this->commands([ \Grafite\CrudMaker\Console\CrudMaker::class, \Grafite\CrudMaker\Console\TableCrudMaker::class, ]); }
Register the service provider. @return void
entailment
public function toUri(): UriInterface { $uri = $this->uriToFeedComponent(); $uri = $uri->withPath($uri->getPath().'/guid/'.$this->ownerId.'/'.implode(',', $this->guids)); $uri = $this->appendSeoTerms($uri); return $uri; }
{@inheritdoc}
entailment
public function handle() { $section = ''; $splitTable = []; $appPath = app()->path(); $basePath = app()->basePath(); $appNamespace = $this->appService->getAppNamespace(); $framework = ucfirst('Laravel'); if (stristr(get_class(app()), 'Lumen')) { $framework = ucfirst('lumen'); } $table = ucfirst(str_singular($this->argument('table'))); $this->validator->validateSchema($this); $this->validator->validateOptions($this); $options = [ 'api' => $this->option('api'), 'apiOnly' => $this->option('apiOnly'), 'ui' => $this->option('ui'), 'serviceOnly' => $this->option('serviceOnly'), 'withFacade' => $this->option('withFacade'), 'withBaseService' => $this->option('withBaseService'), 'migration' => $this->option('migration'), 'schema' => $this->option('schema'), 'asPackage' => $this->option('asPackage'), 'relationships' => $this->option('relationships'), ]; if ($this->option('asPackage')) { $newPath = base_path($this->option('asPackage').'/'.str_plural($table)); if (!is_dir($newPath)) { mkdir($newPath, 755, true); } $appPath = $newPath; $basePath = $newPath; $appNamespace = ucfirst($this->option('asPackage')); } $config = $this->configService->basicConfig( $framework, $appPath, $basePath, $appNamespace, $table, $options ); if ($this->option('ui')) { $config[$this->option('ui')] = true; } $config['schema'] = $this->option('schema'); $config['relationships'] = $this->option('relationships'); $config['template_source'] = $this->configService->getTemplateConfig($framework); if (stristr($table, '_')) { $splitTable = explode('_', $table); $table = $splitTable[1]; $section = $splitTable[0]; $config = $this->configService->configASectionedCRUD($config, $section, $table, $splitTable); } else { $config = array_merge($config, app('config')->get('crudmaker.single', [])); $config = $this->configService->setConfig($config, $section, $table); } if ($this->option('asPackage')) { $moduleDirectory = base_path($this->option('asPackage').'/'.str_plural($table)); $config = array_merge($config, [ '_path_package_' => $moduleDirectory, '_path_facade_' => $moduleDirectory.'/Facades', '_path_service_' => $moduleDirectory.'/Services', '_path_model_' => $moduleDirectory.'/Models', '_path_model_' => $moduleDirectory.'/Models', '_path_controller_' => $moduleDirectory.'/Controllers', '_path_views_' => $moduleDirectory.'/Views', '_path_tests_' => $moduleDirectory.'/Tests', '_path_request_' => $moduleDirectory.'/Requests', '_path_routes_' => $moduleDirectory.'/Routes/web.php', '_namespace_services_' => $appNamespace.'\\'.ucfirst(str_plural($table)).'\Services', '_namespace_facade_' => $appNamespace.'\\'.ucfirst(str_plural($table)).'\Facades', '_namespace_model_' => $appNamespace.'\\'.ucfirst(str_plural($table)).'\Models', '_namespace_controller_' => $appNamespace.'\\'.ucfirst(str_plural($table)).'\Controllers', '_namespace_request_' => $appNamespace.'\\'.ucfirst(str_plural($table)).'\Requests', '_namespace_package_' => $appNamespace.'\\'.ucfirst(str_plural($table)), ]); if (! is_dir($moduleDirectory.'/Routes')) { mkdir($moduleDirectory.'/Routes'); } } $this->createCRUD($config, $section, $table, $splitTable); if ($this->option('asPackage')) { $this->createPackageServiceProvider($config); $this->crudService->correctViewNamespace($config); } $this->info("\nYou may wish to add this as your testing database:\n"); $this->comment("'testing' => [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '' ],"); $this->info("\n".'You now have a working CRUD for '.$table."\n"); }
Generate a CRUD stack. @return mixed
entailment
public function createCRUD($config, $section, $table, $splitTable) { $bar = $this->output->createProgressBar(7); try { $this->crudService->generateCore($config, $bar); $this->crudService->generateAppBased($config, $bar); $this->crudGenerator->createTests( $config, $this->option('serviceOnly'), $this->option('apiOnly'), $this->option('api') ); $bar->advance(); $this->crudGenerator->createFactory($config); $bar->advance(); $this->crudService->generateAPI($config, $bar); $bar->advance(); $this->crudService->generateDB($config, $bar, $section, $table, $splitTable, $this); $bar->finish(); $this->crudReport($table); } catch (Exception $e) { throw new Exception('Unable to generate your CRUD: ('.$e->getFile().':'.$e->getLine().') '.$e->getMessage(), 1); } }
Create a CRUD. @param array $config @param string $section @param string $table @param array $splitTable
entailment
private function crudReport($table) { $this->line("\n"); $this->line('Built model...'); $this->line('Built request...'); $this->line('Built service...'); if (!$this->option('serviceOnly') && !$this->option('apiOnly')) { $this->line('Built controller...'); if (!$this->option('withoutViews')) { $this->line('Built views...'); } $this->line('Built routes...'); } if ($this->option('withFacade')) { $this->line('Built facade...'); } $this->line('Built tests...'); $this->line('Built factory...'); if ($this->option('api') || $this->option('apiOnly')) { $this->line('Built api...'); $this->comment("\nAdd the following to your app/Providers/RouteServiceProvider.php: \n"); $this->info("require base_path('routes/api.php'); \n"); } if ($this->option('migration')) { $this->line('Built migration...'); if ($this->option('schema')) { $this->line('Built schema...'); } } else { $this->info("\nYou will want to create a migration in order to get the $table tests to work correctly.\n"); } }
Generate a CRUD report. @param string $table
entailment
public function getAvailableDate(): \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface { if (!$this->availableDate) { return new NullDateTime(); } return $this->availableDate; }
Returns the date that this content becomes available for playback. @return \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface
entailment
public function setAvailableDate(\Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $availableDate) { $this->availableDate = $availableDate; }
Set the date that this content becomes available for playback. @param \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $availableDate
entailment
public function getExpirationDate(): \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface { if (!$this->expirationDate) { return new NullDateTime(); } return $this->expirationDate; }
Returns the date that this content expires and is no longer available for playback. @return \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface
entailment
public function setExpirationDate(\Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $expirationDate) { $this->expirationDate = $expirationDate; }
Set the date that this content expires and is no longer available for playback. @param \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $expirationDate
entailment
public function getFileSourceMediaId(): \Psr\Http\Message\UriInterface { if (!$this->fileSourceMediaId) { return new Uri(); } return $this->fileSourceMediaId; }
Returns reserved for future use. @return \Psr\Http\Message\UriInterface
entailment
public function getProgramId(): \Psr\Http\Message\UriInterface { if (!$this->programId) { return new Uri(); } return $this->programId; }
Returns the ID of the Program that represents this media. The GUID URI is recommended. @return \Psr\Http\Message\UriInterface
entailment
public function getProviderId(): \Psr\Http\Message\UriInterface { if (!$this->providerId) { return new Uri(); } return $this->providerId; }
Returns the id of the Provider that represents the account that shared this Media. @return \Psr\Http\Message\UriInterface
entailment
public function getPubDate(): \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface { if (!$this->pubDate) { return new NullDateTime(); } return $this->pubDate; }
Returns the original release date or airdate of this Media object's content. @return \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface
entailment
public function setPubDate(\Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $pubDate) { $this->pubDate = $pubDate; }
Set the original release date or airdate of this Media object's content. @param \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $pubDate
entailment
public function getSeriesId(): \Psr\Http\Message\UriInterface { if (!$this->seriesId) { return new Uri(); } return $this->seriesId; }
Returns the ID of the Program that represents the series to which this media belongs. The GUID URI is recommended. @return \Psr\Http\Message\UriInterface
entailment
public function getTransliterationMap($path, $alphabet) { // Valdate if (!in_array($alphabet, array(Settings::ALPHABET_CYR, Settings::ALPHABET_LAT))) { throw new \InvalidArgumentException(sprintf('Alphabet "%s" is not recognized.', $alphabet)); } // Load form cache $map = $this->loadFromCache($path, $alphabet); if (null !== $map) { return $map; } // Load from file $map = $this->loadFromFile($path); // Store to cache $this->storeToCache($path, $map); return $this->loadFromCache($path, $alphabet); }
Get transliteration map. @param string $path path to map file @param string $alphabet @return array map array
entailment
protected function loadFromFile($path) { if (!file_exists($path)) { throw new \Exception(sprintf('Map file "%s" does not exist.', $path)); } $map = require($path); if (!is_array($map) || !is_array($map[Settings::ALPHABET_CYR]) || !is_array($map[Settings::ALPHABET_LAT]) ) { throw new \Exception(sprintf( 'Map file "%s" is not valid, should return an array with %s and %s subarrays.', $path, Settings::ALPHABET_CYR, Settings::ALPHABET_LAT )); } return $map; }
Load map from file. @param string $path path to map file @return array map array
entailment
protected function loadFromCache($id, $alphabet) { if (isset($this->mappingCache[$id]) && isset($this->mappingCache[$id][$alphabet])) { return $this->mappingCache[$id][$alphabet]; } return null; }
Load map from cache. @param string $id cache ID @param string $alphabet @return array|null char map, null if not found
entailment
public function setAmount($amount) { if (!is_int($amount)) { throw new InvalidArgumentException("Integer expected. Amount is always in cents"); } if ($amount <= 0) { throw new InvalidArgumentException("Amount must be a positive number"); } $this->parameters['amount'] = $amount; }
Set amount in cents, eg EUR 12.34 is written as 1234
entailment
public function copyDirectory($directory, $destination) { $files = $this->fileSystem->allFiles($directory); $fileDeployed = false; $this->fileSystem->copyDirectory($directory, $destination); foreach ($files as $file) { $fileContents = $this->fileSystem->get($file); $fileDeployed = $this->fileSystem->put($destination.'/'.$file->getRelativePathname(), $fileContents); } return $fileDeployed; }
Copy a directory and its content. @param $directory @param $destination @throws \Illuminate\Contracts\Filesystem\FileNotFoundException @return bool|int
entailment
private function publishConfig() { if (!file_exists(getcwd().'/config/crudmaker.php')) { $this->copyDirectory(__DIR__.'/../../config', getcwd().'/config'); $this->info("\n\nLumen config file have been published"); } else { $this->error('Lumen config files has already been published'); } }
Publish config files for Lumen.
entailment
private function publishTemplates() { if (!$this->fileSystem->isDirectory(getcwd().'/resources/crudmaker')) { $this->copyDirectory(__DIR__.'/../Templates/Lumen', getcwd().'/resources/crudmaker'); $this->info("\n\nLumen templates files have been published"); } else { $this->error('Lumen templates files has already been published'); } }
Publish templates files for Lumen.
entailment
public function handle() { $filesystem = new Filesystem(); $tableService = new TableService(); $table = (string) $this->argument('table'); $tableDefintion = $tableService->tableDefintion($table); if (empty($tableDefintion)) { throw new Exception("There is no table definition for $table. Are you sure you spelled it correctly? Table names are case sensitive.", 1); } $this->call('crudmaker:new', [ 'table' => $table, '--api' => $this->option('api'), '--ui' => $this->option('ui'), '--serviceOnly' => $this->option('serviceOnly'), '--withFacade' => $this->option('withFacade'), '--migration' => true, '--relationships' => $this->option('relationships'), '--schema' => $tableDefintion, ]); // Format the table name accordingly // usecase: OrderProducts turns into order_products $table_name = str_plural(strtolower(snake_case($table))); $migrationName = 'create_'.$table_name.'_table'; $migrationFiles = $filesystem->allFiles(base_path('database/migrations')); foreach ($migrationFiles as $file) { if (stristr($file->getBasename(), $migrationName)) { $migrationData = file_get_contents($file->getPathname()); if (stristr($migrationData, 'updated_at')) { $migrationData = str_replace('$table->timestamps();', '', $migrationData); } file_put_contents($file->getPathname(), $migrationData); } } $this->line("\nYou've generated a CRUD for the table: ".$table); $this->line("\n\nYou may wish to add this as your testing database"); $this->line("'testing' => [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '' ],"); $this->info("\n\nCRUD for $table is done."); }
Generate a CRUD stack. @return mixed
entailment
public function basicConfig($framework, $appPath, $basePath, $appNamespace, $table, $options) { $config = [ 'framework' => $framework, 'bootstrap' => false, 'semantic' => false, 'template_source' => '', '_sectionPrefix_' => '', '_sectionTablePrefix_' => '', '_sectionRoutePrefix_' => '', '_sectionNamespace_' => '', '_path_facade_' => $appPath.'/Facades', '_path_service_' => $appPath.'/Services', '_path_model_' => $appPath.'/Models', '_path_controller_' => $appPath.'/Http/Controllers/', '_path_api_controller_' => $appPath.'/Http/Controllers/Api', '_path_views_' => $basePath.'/resources/views', '_path_tests_' => $basePath.'/tests', '_path_request_' => $appPath.'/Http/Requests/', '_path_routes_' => $basePath.'/routes/web.php', '_path_api_routes_' => $basePath.'/routes/api.php', '_path_migrations_' => $basePath.'/database/migrations', '_path_factory_' => $basePath.'/database/factories/'.snake_case($table).'Factory.php', 'routes_prefix' => '', 'routes_suffix' => '', '_app_namespace_' => 'App\\', '_namespace_services_' => $appNamespace.'Services', '_namespace_facade_' => $appNamespace.'Facades', '_namespace_model_' => $appNamespace.'Models', '_namespace_controller_' => $appNamespace.'Http\Controllers', '_namespace_api_controller_' => $appNamespace.'Http\Controllers\Api', '_namespace_request_' => $appNamespace.'Http\Requests', '_table_name_' => str_plural(strtolower(snake_case($table))), '_lower_case_' => strtolower(snake_case($table)), '_lower_casePlural_' => str_plural(strtolower(snake_case($table))), '_camel_case_' => ucfirst(camel_case($table)), '_camel_casePlural_' => str_plural(camel_case($table)), '_ucCamel_casePlural_' => ucfirst(str_plural(camel_case($table))), '_plain_space_textLower_' => strtolower(str_replace('_', ' ', snake_case($table))), '_plain_space_textFirst_' => ucfirst(strtolower(str_replace('_', ' ', snake_case($table)))), '_snake_case_' => snake_case($table), '_snake_casePlural_' => str_plural(snake_case($table)), 'options-api' => $options['api'], 'options-apiOnly' => $options['apiOnly'], 'options-ui' => $options['ui'], 'options-serviceOnly' => $options['serviceOnly'], 'options-withFacade' => $options['withFacade'], 'options-withBaseService' => $options['withBaseService'], 'options-migration' => $options['migration'], 'options-schema' => $options['schema'], 'options-relationships' => $options['relationships'], ]; return $config; }
Generate the basic config @param string $framework @param string $appPath @param string $basePath @param string $appNamespace @param string $table @param array $options @return array
entailment
public function configASectionedCRUD($config, $section, $table, $splitTable) { $appPath = app()->path(); $basePath = app()->basePath(); $appNamespace = $this->appService->getAppNamespace(); $sectionalConfig = [ '_sectionPrefix_' => strtolower($section).'.', '_sectionTablePrefix_' => strtolower($section).'_', '_sectionRoutePrefix_' => strtolower($section).'/', '_sectionNamespace_' => ucfirst($section).'\\', '_path_facade_' => $appPath.'/Facades', '_path_service_' => $appPath.'/Services', '_path_model_' => $appPath.'/Models/'.ucfirst($section).'/'.ucfirst($table), '_path_controller_' => $appPath.'/Http/Controllers/'.ucfirst($section).'/', '_path_api_controller_' => $appPath.'/Http/Controllers/Api/'.ucfirst($section).'/', '_path_views_' => $basePath.'/resources/views/'.strtolower($section), '_path_tests_' => $basePath.'/tests', '_path_request_' => $appPath.'/Http/Requests/'.ucfirst($section), '_path_routes_' => $appPath.'/Http/routes.php', '_path_api_routes_' => $appPath.'/Http/api-routes.php', '_path_migrations_' => $basePath.'/database/migrations', '_path_factory_' => $basePath.'/database/factories/'.snake_case($table).'Factory.php', 'routes_prefix' => "\n\nRoute::group(['namespace' => '".ucfirst($section)."', 'prefix' => '".strtolower($section)."', 'middleware' => ['web']], function () { \n", 'routes_suffix' => "\n});", '_app_namespace_' => $appNamespace, '_namespace_services_' => $appNamespace.'Services\\'.ucfirst($section), '_namespace_facade_' => $appNamespace.'Facades', '_namespace_model_' => $appNamespace.'Models\\'.ucfirst($section).'\\'.ucfirst($table), '_namespace_controller_' => $appNamespace.'Http\Controllers\\'.ucfirst($section), '_namespace_api_controller_' => $appNamespace.'Http\Controllers\Api\\'.ucfirst($section), '_namespace_request_' => $appNamespace.'Http\Requests\\'.ucfirst($section), '_lower_case_' => strtolower($splitTable[1]), '_lower_casePlural_' => str_plural(strtolower($splitTable[1])), '_camel_case_' => ucfirst(camel_case($splitTable[1])), '_camel_casePlural_' => str_plural(camel_case($splitTable[1])), '_ucCamel_casePlural_' => ucfirst(str_plural(camel_case($splitTable[1]))), '_table_name_' => str_plural(strtolower(implode('_', $splitTable))), ]; $config = array_merge($config, $sectionalConfig); $config = array_merge($config, app('config')->get('crudmaker.sectioned', [])); $config = $this->setConfig($config, $section, $table); $pathsToMake = [ '_path_model_', '_path_controller_', '_path_api_controller_', '_path_views_', '_path_request_', ]; foreach ($config as $key => $value) { if (in_array($key, $pathsToMake) && !file_exists($value)) { mkdir($value, 0777, true); } } return $config; }
Set the config of the CRUD. @param array $config @param string $section @param string $table @param array $splitTable @return array
entailment
public function getTemplateConfig($framework) { $templates = __DIR__.'/../Templates/'.$framework; $templates = app('config')->get('crudmaker.template_source', $templates); return $templates; }
Get the templates directory. @param string $framework @return string
entailment
public function setConfig($config, $section, $table) { if (!empty($section)) { foreach ($config as $key => $value) { $config[$key] = str_replace('_table_', ucfirst($table), str_replace('_section_', ucfirst($section), str_replace('_sectionLowerCase_', strtolower($section), $value))); } } else { foreach ($config as $key => $value) { $config[$key] = str_replace('_table_', ucfirst($table), $value); } } return $config; }
Set the config. @param array $config @param string $section @param string $table @return array
entailment
public function getResponse() { if (!isset($this->decodedResult['response'])) { if (isset($this->decodedResult['error'])) { return $this->decodedResult['error']; } throw new \RuntimeException('Missing response value'); } return $this->decodedResult['response']; }
{@inheritdoc}
entailment
public function addField(string $field, string $value): self { $this->fields[$field] = $value; return $this; }
Add a field to this filter, such as 'title'. @param string $field The field to filter on. @param string $value The value to filter by. @return self Fluent return.
entailment
public function toQueryParts(): array { $fields = []; foreach ($this->fields as $field => $value) { $fields['by'.ucfirst($field)] = $value; } return $fields; }
Return all of the fields being filtered. @return array
entailment
public static function read($key = null, $type = null) { if (!self::_tableExists()) { return; } self::autoLoad(); if (!$key) { return self::$_data; } if (key_exists($key, self::$_data)) { if ($type) { $value = self::$_data[$key]; settype($value, $type); return $value; } return self::$_data[$key]; } $model = self::model(); $data = $model->findByName($key)->select('value'); if ($data->count() > 0) { $data = $data->first()->toArray(); } else { return null; } self::_store($key, $data['value']); $value = $data['value']; if ($type) { settype($value, $type); } return $value; }
read Method to read the data. @param string $key Key with the name of the setting. @param string $type The type to return in. @return mixed
entailment
public static function write($key, $value = null, $options = []) { if (!self::_tableExists()) { return; } self::autoLoad(); $_options = [ 'editable' => 1, 'overrule' => true, ]; $options = Hash::merge($_options, $options); $model = self::model(); if (self::check($key)) { if ($options['overrule']) { $data = $model->findByName($key)->first(); if ($data) { $data->set('value', $value); $model->save($data); } else { return false; } } else { return false; } } else { $data = $model->newEntity($options); $data->name = $key; $data->value = $value; $model->save($data); } self::_store($key, $value); return true; }
write Method to write data to database. ### Example Setting::write('Plugin.Autoload', true); ### Options - editable value if the setting is editable in the admin-area. Default 1 (so, editable) - overrule boolean if the setting should be written if it already exists. Default true. Example: Setting::write('Plugin.Autoload', false, [ 'overrule' => true, 'editable' => 0, ] @param string $key Key of the value. Must contain an prefix. @param mixed $value The value of the key. @param array $options Options array. @return void|bool
entailment
public static function check($key) { if (!self::_tableExists()) { return; } self::autoLoad(); $model = self::model(); if (key_exists($key, self::$_data)) { return true; } $query = $model->findByName($key); if (!$query->Count()) { return false; } return true; }
check Checks if an specific key exists. Returns boolean. @param string $key Key. @return bool|void
entailment
public static function model($model = null) { if ($model) { self::$_model = $model; } if (!self::$_model) { self::$_model = TableRegistry::get('Settings.Configurations'); } return self::$_model; }
model Returns an instance of the Configurations-model (Table). Also used as setter for the instance of the model. @param \Cake\ORM\Table|null $model Model to use. @return \Cake\ORM\Table
entailment
public static function register($key, $value, $data = []) { if (!self::_tableExists()) { return; } self::autoLoad(); $_data = [ 'value' => $value, 'editable' => 1, 'autoload' => true, 'options' => [], 'description' => null, ]; $data = array_merge($_data, $data); // Don't overrule because we register $data['overrule'] = false; self::options($key, $data['options']); self::write($key, $data['value'], $data); }
register Registers a setting and its default values. @param string $key The key. @param mixed $value The default value. @param array $data Custom data. @return void
entailment
public static function options($key, $value = null) { if (!self::_tableExists()) { return; } if ($value) { self::$_options[$key] = $value; } if (array_key_exists($key, self::$_options)) { return self::$_options[$key]; } else { return false; } }
options @param string $key Key for options. @param array $value Options to use. @return mixed
entailment
public static function autoLoad() { if (!self::_tableExists()) { return; } if (self::$_autoloaded) { return; } self::$_autoloaded = true; $model = self::model(); $query = $model->find('all')->where(['autoload' => 1])->select(['name', 'value']); foreach ($query as $configure) { self::_store($configure->get('name'), $configure->get('value')); } }
autoLoad AutoLoad method. Loads all configurations who are autoloaded. @return void
entailment
protected static function _tableExists() { $db = ConnectionManager::get('default'); $tables = $db->schemaCollection()->listTables(); if (in_array('settings_configurations', $tables)) { return true; } return false; }
_tableExists @return bool
entailment
public function createFromReflector(\Reflector $reflector) { if (method_exists($reflector, 'getDeclaringClass')) { $reflector = $reflector->getDeclaringClass(); } $fileName = $reflector->getFileName(); $namespace = $reflector->getNamespaceName(); if (file_exists($fileName)) { return $this->createForNamespace($namespace, file_get_contents($fileName)); } return new Context($namespace, []); }
Build a Context given a Class Reflection. @param \Reflector $reflector @see Context for more information on Contexts. @return Context
entailment
private function parseUseStatement(\ArrayIterator $tokens) { $uses = []; $continue = true; while ($continue) { $this->skipToNextStringOrNamespaceSeparator($tokens); list($alias, $fqnn) = $this->extractUseStatement($tokens); $uses[$alias] = $fqnn; if (self::T_LITERAL_END_OF_USE === $tokens->current()[0]) { $continue = false; } } return $uses; }
Deduce the names of all imports when we are at the T_USE token. @param \ArrayIterator $tokens @return string[]
entailment
private function skipToNextStringOrNamespaceSeparator(\ArrayIterator $tokens) { while ($tokens->valid() && (T_STRING !== $tokens->current()[0]) && (T_NS_SEPARATOR !== $tokens->current()[0])) { $tokens->next(); } }
Fast-forwards the iterator as longs as we don't encounter a T_STRING or T_NS_SEPARATOR token. @param \ArrayIterator $tokens
entailment
private function extractUseStatement(\ArrayIterator $tokens) { $result = ['']; while ($tokens->valid() && (self::T_LITERAL_USE_SEPARATOR !== $tokens->current()[0]) && (self::T_LITERAL_END_OF_USE !== $tokens->current()[0]) ) { if (T_AS === $tokens->current()[0]) { $result[] = ''; } if (T_STRING === $tokens->current()[0] || T_NS_SEPARATOR === $tokens->current()[0]) { $result[\count($result) - 1] .= $tokens->current()[1]; } $tokens->next(); } if (1 == \count($result)) { $backslashPos = strrpos($result[0], '\\'); if (false !== $backslashPos) { $result[] = substr($result[0], $backslashPos + 1); } else { $result[] = $result[0]; } } return array_reverse($result); }
Deduce the namespace name and alias of an import when we are at the T_USE token or have not reached the end of a USE statement yet. @param \ArrayIterator $tokens @return string
entailment
public function getTypes($class, $property, array $context = []) { if ('resolveAllUrlsResponse' != $property) { throw new \InvalidArgumentException('This extractor only supports resolveAllUrlsResponse properties.'); } $collectionKeyType = new Type(Type::BUILTIN_TYPE_STRING); $collectionValueType = new Type('object', false, Uri::class); return [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, $collectionKeyType, $collectionValueType)]; }
{@inheritdoc}
entailment
public static function validateData($data) { // @todo Prior code also checked for $data being an array, but the docs // at https://docs.theplatform.com/help/wsf-handling-data-service-exceptions#tp-toc4 // don't show that. $required = [ 'responseCode', 'isException', 'title', ]; // The error description is only returned for client errors. According // to thePlatform support, the documentation is wrong about description // always being included. if (isset($data['responseCode']) && $data['responseCode'] >= 400 && $data['responseCode'] < 500) { $required[] = 'description'; } foreach ($required as $key) { if (empty($data[$key])) { throw new \InvalidArgumentException(sprintf('Required key %s is missing.', $key)); } } }
Validate required data in the MPX error. @param array $data The array of data returned by MPX. @throws \InvalidArgumentException Thrown if a required key in $data is missing. @see https://docs.theplatform.com/help/wsf-handling-data-service-exceptions#tp-toc4
entailment
protected function parseResponse(ResponseInterface $response): string { $data = \GuzzleHttp\json_decode($response->getBody(), true); isset($data[0]) ? $this->setNotificationData($data) : $this->setData($data); $message = sprintf('HTTP %s Error %s', $response->getStatusCode(), $this->data['title']); if (isset($this->data['description'])) { $message .= sprintf(': %s', $this->getDescription()); } return $message; }
Parse a response into the exception. @param \Psr\Http\Message\ResponseInterface $response The response exception. @return string The message to use for the exception.
entailment