sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function getMediaId(): \Psr\Http\Message\UriInterface { if (!$this->mediaId) { return new Uri(); } return $this->mediaId; }
Returns the id of the Media object this object is associated with. @return \Psr\Http\Message\UriInterface
entailment
public function getOwnerId(): \Psr\Http\Message\UriInterface { if (!$this->ownerId) { return new Uri(); } return $this->ownerId; }
Returns the id of the account that owns this object. @return \Psr\Http\Message\UriInterface
entailment
public function getServerId(): \Psr\Http\Message\UriInterface { if (!$this->serverId) { return new Uri(); } return $this->serverId; }
Returns the id of the Server object representing the storage server that this file is on. @return \Psr\Http\Message\UriInterface
entailment
public function getSourceMediaFileId(): \Psr\Http\Message\UriInterface { if (!$this->sourceMediaFileId) { return new Uri(); } return $this->sourceMediaFileId; }
Returns the id of the source MediaFile object that this file was generated from. @return \Psr\Http\Message\UriInterface
entailment
public function getTransformId(): \Psr\Http\Message\UriInterface { if (!$this->transformId) { return new Uri(); } return $this->transformId; }
Returns the id of the encoding template used to generate the file. @return \Psr\Http\Message\UriInterface
entailment
public function getUpdated(): \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface { if (!$this->updated) { return new NullDateTime(); } return $this->updated; }
Returns the date and time this object was last modified. @return \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface
entailment
public function setUpdated(\Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $updated) { $this->updated = $updated; }
Set the date and time this object was last modified. @param \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $updated
entailment
public function getUpdatedByUserId(): \Psr\Http\Message\UriInterface { if (!$this->updatedByUserId) { return new Uri(); } return $this->updatedByUserId; }
Returns the id of the user that last modified this object. @return \Psr\Http\Message\UriInterface
entailment
public static function getDefaultConfiguration($handler = null) { $config = [ 'headers' => [ 'Accept' => 'application/json', 'Content-Type' => 'application/json', ], ]; if (!$handler) { $handler = HandlerStack::create(); $handler->push(Middleware::mpxErrors(), 'mpx_errors'); } $config['handler'] = $handler; return $config; }
Get the default Guzzle client configuration array. @param mixed $handler (optional) A Guzzle handler to use for requests. If a custom handler is specified, it must include Middleware::mpxErrors or a replacement. @return array An array of configuration options suitable for use with Guzzle.
entailment
public function request($method = 'GET', $url = null, array $options = []) { // MPX forces all JSON requests to return HTTP 200, even with an error. // We force all requests (including XML) to suppress errors so we can // have the same error handling code. $options['query']['httpError'] = false; return $this->client->request($method, $url, $options); }
{@inheritdoc}
entailment
protected function handleXmlResponse(ResponseInterface $response, $url) { if (false !== strpos((string) $response->getBody(), 'xmlns:e="http://xml.theplatform.com/exception"')) { if (preg_match('~<e:title>(.+)</e:title><e:description>(.+)</e:description><e:responseCode>(.+)</e:responseCode>~', (string) $response->getBody(), $matches)) { throw new ApiException("Error {$matches[1]} on request to {$url}: {$matches[2]}", (int) $matches[3]); } elseif (preg_match('~<title>(.+)</title><summary>(.+)</summary><e:responseCode>(.+)</e:responseCode>~', (string) $response->getBody(), $matches)) { throw new ApiException("Error {$matches[1]} on request to {$url}: {$matches[2]}", (int) $matches[3]); } } $data = simplexml_load_string($response->getBody()->getContents()); $data = [$data->getName() => static::convertXmlToArray($data)]; return $data; }
Handle an XML API response. @param ResponseInterface $response The response. @param string $url The request URL. @throws \Lullabot\Mpx\Exception\ApiException If an error occurred. @return array The decoded response data.
entailment
protected static function convertXmlToArray(\SimpleXMLElement $data) { $result = []; foreach ((array) $data as $index => $node) { $result[$index] = (\is_object($node)) ? static::convertXmlToArray($node) : trim((string) $node); } return $result; }
Convert a string of XML to an associative array. @param \SimpleXMLElement $data An XML element node. @return array An array representing the XML data.
entailment
public function requestAsync($method, $uri, array $options = []) { return $this->client->requestAsync($method, $uri, $options); }
{@inheritdoc}
entailment
public function getUrl(string $service, bool $insecure = false): Uri { if (!isset($this->resolveDomainResponse[$service])) { throw new \RuntimeException(sprintf('%s service was not found.', $service)); } $url = $this->resolveDomainResponse[$service]; if (!$insecure) { $url = $url->withScheme('https'); } return $url; }
Get the URL for a given service. Note that no 'getResolveDomainResponse' method is implemented, to ensure that callers get https URLs unless they explicitly ask for insecure URLs. While resolveDomainResponse currently returns many services with http URLs, according to thePlatform all services should now support https. @param string $service The name of the service, such as 'Media Data Service read-only'. @param bool $insecure (optional) Set to true to request the insecure version of this service. @return Uri The URL for the service.
entailment
public function denormalize($data, $class, $format = null, array $context = []) { if (!\is_int($data)) { throw new NotNormalizableValueException('The data is not an integer, you should pass an integer representing the unix time in milliseconds.'); } $seconds = floor($data / 1000); $remainder = $data % 1000; $bySeconds = "$seconds.$remainder"; $context[self::FORMAT_KEY] = 'U.u'; $date = parent::denormalize($bySeconds, \DateTime::class, $format, $context); return new ConcreteDateTime($date); }
{@inheritdoc}
entailment
public static function b($name, $options = []) { $options = array_merge($options, ['type' => 'submit']); return static::socialButton($name, $options)->tag('button'); }
Creates a SocialButton component as a button tag @param string $name @param array $options @return p2m\components\SocialButton
entailment
public function transliterate($text, $direction) { if ($direction) { return str_replace($this->getCyrMap(), $this->getLatMap(), $text); } else { return str_replace($this->getLatMap(), $this->getCyrMap(), $text); } }
Transliterates cyrillic text to latin and vice versa depending on $direction parameter. @param string $text latin text @param bool $direction if true transliterates cyrillic text to latin, if false latin to cyrillic @return string transliterated text
entailment
public function getCyrMap() { if (null === $this->cyrMap) { $this->cyrMap = $this->getTransliterationMap(Settings::ALPHABET_CYR); } return $this->cyrMap; }
Get cyrillic char map. @return array cyrillic char map
entailment
public function getLatMap() { if (null === $this->latMap) { $this->latMap = $this->getTransliterationMap(Settings::ALPHABET_LAT); } return $this->latMap; }
Get latin char map. @return array latin char map
entailment
public function setIds(array $ids): void { if (empty($ids)) { throw new \InvalidArgumentException('At least one ID must be specified'); } foreach ($ids as $id) { if (!\is_int($id)) { throw new \InvalidArgumentException('All IDs must be integers'); } } $this->ids = $ids; }
A comma-separated list of numeric IDs for individual items in the feed. @param int[] $ids
entailment
public function toUri(): UriInterface { $uri = $this->uriToFeedComponent(); $uri = $uri->withPath($uri->getPath().'/'.implode(',', $this->ids)); $uri = $this->appendSeoTerms($uri); return $uri; }
{@inheritdoc}
entailment
public function normalize($object, $format = null, array $context = []) { if (!$object instanceof UriInterface) { throw new InvalidArgumentException('The object must implement "\\Psr\\Http\\Message\\UriInterface".'); } return (string) $object; }
{@inheritdoc}
entailment
public function denormalize($data, $class, $format = null, array $context = []) { // If an empty string is normalized, we can still return a valid URI object. if ('' === $data || null === $data) { return new Uri(); } try { $object = new Uri($data); } catch (\InvalidArgumentException $e) { throw new NotNormalizableValueException(sprintf( 'Parsing URI string "%s" resulted in error: %s', $data, $e->getMessage()), $e->getCode(), $e); } return $object; }
{@inheritdoc}
entailment
public function process(ContainerBuilder $container) { $clients = $container->findTaggedServiceIds('playbloom_guzzle.client'); if (empty($clients)) { return; } $plugins = $container->findTaggedServiceIds('playbloom_guzzle.client.plugin'); foreach ($clients as $clientId => $attribute) { $clientDefinition = $container->findDefinition($clientId); $this->registerGuzzlePlugin($clientDefinition, $plugins); if ($container->hasDefinition('profiler')) { $clientDefinition->addMethodCall( 'addSubscriber', array(new Reference('playbloom_guzzle.client.plugin.profiler')) ); } } }
{@inheritdoc}
entailment
private function registerGuzzlePlugin(Definition $clientDefinition, array $plugins) { foreach ($plugins as $pluginId => $attributes) { $clientDefinition->addMethodCall( 'addSubscriber', array(new Reference($pluginId)) ); } }
Register plugin for a client @param Definition $clientDefinition @param array $plugins
entailment
public function resolve(string $service): ResolveAllUrlsResponse { $key = $this->cacheKey($service); $item = $this->cache->getItem($key); if ($item->isHit()) { return $item->get(); } $options = [ 'query' => [ 'schema' => self::SCHEMA_VERSION, '_service' => $service, ], ]; $response = $this->authenticatedClient->request('GET', static::RESOLVE_ALL_URLS_URL, $options); $encoders = [new JsonEncoder()]; $normalizers = [new UriNormalizer(), new ObjectNormalizer(null, null, null, new PhpDocExtractor()), new ArrayDenormalizer()]; $serializer = new Serializer($normalizers, $encoders); /** @var ResolveAllUrlsResponse $resolved */ $resolved = $serializer->deserialize($response->getBody(), ResolveAllUrlsResponse::class, 'json'); $resolved->setService($service); $this->saveCache($key, $resolved); return $resolved; }
Fetch URLs and return the response. @param string $service The service to find URLs for, such as 'Media Data Service'. @return ResolveAllUrlsResponse
entailment
protected function cacheKey(string $key_part): string { $key = md5('resolveAllUrls'.$key_part.self::SCHEMA_VERSION); return $key; }
@param string $key_part @return string
entailment
public function getMapFilePath() { return sprintf( '%s.php', $this->mapBasePath . DIRECTORY_SEPARATOR . $this->getLang(). DIRECTORY_SEPARATOR . $this->getSystem() ); }
Get path to map file depending on current settings. @return string path to map file
entailment
public function setLang($lang) { if (2 !== strlen($lang)) { throw new \InvalidArgumentException('Language identifier should be 2 characters long.'); } if (!in_array($lang, $this->getSupportedLanguages())) { throw new \InvalidArgumentException(sprintf('Language "%s" is not supported.', $lang)); } $this->lang = $lang; return $this; }
Set language. @param string $lang ISO 639-1 language code @return Settings fluent interface @see http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
entailment
public function setSystem($system) { if (!in_array($system, $this->getSupportedTranliterationSystems())) { throw new \InvalidArgumentException( sprintf('Transliteration system "%s" is not supported for "%s" language.', $system, $this->getLang() ) ); } $this->system = $system; return $this; }
Set transliteration system. @param string $system transliteration system @return Settings fluent interface
entailment
public function getSupportedLanguages() { return array( self::LANG_SR, self::LANG_RU, self::LANG_BE, self::LANG_MK, self::LANG_UK, self::LANG_BG, self::LANG_EL ); }
Get suported languages. @return array of supported languages
entailment
public function getSupportedTranliterationSystems() { $default = array(self::SYSTEM_DEFAULT); switch ($this->getLang()) { case self::LANG_RU: return array_merge($default, array( self::SYSTEM_ISO_R_9_1968, self::SYSTEM_GOST_1971, self::SYSTEM_GOST_1983, self::SYSTEM_GOST_2000_B, self::SYSTEM_GOST_2002, self::SYSTEM_ALA_LC, self::SYSTEM_British_Standard, self::SYSTEM_BGN_PCGN, self::SYSTEM_Passport_2003 )); break; case self::LANG_BE: return array_merge($default, array( self::SYSTEM_ALA_LC, self::SYSTEM_BGN_PCGN, self::SYSTEM_ISO_9, self::SYSTEM_National_2000 )); break; case self::LANG_MK: return array_merge($default, array( self::SYSTEM_ISO_9_1995, self::SYSTEM_BGN_PCGN, self::SYSTEM_ISO_9_R_1968_National_Academy, self::SYSTEM_ISO_9_R_1968_b )); break; case self::LANG_UK: return array_merge($default, array( self::SYSTEM_ALA_LC, self::SYSTEM_British, self::SYSTEM_BGN_PCGN, self::SYSTEM_ISO_9, self::SYSTEM_National, self::SYSTEM_GOST_1971, self::SYSTEM_GOST_1986, self::SYSTEM_Derzhstandart_1995, self::SYSTEM_Passport_2004, self::SYSTEM_Passport_2007, self::SYSTEM_Passport_2010 )); break; case self::LANG_BG: case self::LANG_EL: break; } return $default; }
Get suported transliteration systems for current language. @return array of supported transliteration systems
entailment
public function loadByNumericId(int $id, bool $readonly = false, array $options = []) { $annotation = $this->dataService->getAnnotation(); $base = $this->getBaseUri($annotation, $readonly); $uri = new Uri($base.'/'.$id); return $this->load($uri, $options); }
Load a data object from MPX, returning a promise to it. @param int $id The numeric ID to load. @param bool $readonly (optional) Load from the read-only service. @param array $options (optional) An array of HTTP client options. @return PromiseInterface
entailment
protected function deserialize($data, string $class) { // @todo Is this extractor required? $dataServiceExtractor = new DataServiceExtractor(); $dataServiceExtractor->setClass($this->dataService->getClass()); $dataServiceExtractor->setCustomFields($this->dataService->getCustomFields()); // The serializer treats the $xmlns as it's own separate property, and // there is no way to access it from within the extractor. We can't // alter $context in the CJsonEncoder as it is not passed by reference. // @todo This feels like a bit of a hack. $decoded = \GuzzleHttp\json_decode($data, true); if (isset($decoded['$xmlns'])) { $dataServiceExtractor->setNamespaceMapping($decoded['$xmlns']); } $p = new PropertyInfoExtractor([], [$dataServiceExtractor], [], []); $cached = new PropertyInfoCacheExtractor($p, $this->cacheItemPool); $object = $this->getObjectSerializer($cached)->deserialize($data, $class, 'json'); // Adds any missing custom field classes. A given object may not // contain any set fields in a given custom field namespace. In that // case, the serializer will never create a field class. This is fine // until calling code wants to check to see if a given field exists. // By ensuring we add in any missing custom field definitions, we // ensure a valid object is returned instead of null. if ($object instanceof ObjectInterface) { $customFields = $object->getCustomFields(); $remaining = array_diff_key($this->dataService->getCustomFields(), $customFields); /** @var string $namespace */ /** @var DiscoveredCustomField $field */ foreach ($remaining as $namespace => $field) { $namespaceClass = $field->getClass(); $customFields[$namespace] = new $namespaceClass(); } $object->setCustomFields($customFields); } if ($object instanceof JsonInterface) { $object->setJson($data); } return $object; }
Deserialize a JSON string into a class. @todo Inject the serializer in the constructor? @param string $data The JSON string to deserialize. @param string $class The full class name to create. @return mixed An object matching the $class parameter.
entailment
public function load(UriInterface $uri, array $options = []): PromiseInterface { /** @var DataService $annotation */ $annotation = $this->dataService->getAnnotation(); if (!isset($options['query'])) { $options['query'] = []; } $options['query'] = $options['query'] += [ 'schema' => $annotation->schemaVersion, 'form' => 'cjson', ]; if ($this->authenticatedClient->hasAccount()) { $options['query']['account'] = (string) $this->authenticatedClient->getAccount()->getMpxId(); } if ('http' == $uri->getScheme()) { $uri = $uri->withScheme('https'); } $response = $this->authenticatedClient->requestAsync('GET', $uri, $options)->then( function (ResponseInterface $response) { return $this->deserialize($response->getBody(), $this->dataService->getClass()); } ); return $response; }
Load an object from mpx. @param \Psr\Http\Message\UriInterface $uri The URI to load from. This URI will always be converted to https, making it safe to use directly from the ID of an mpx object. @param array $options (optional) An array of HTTP client options. @return PromiseInterface A promise to return a \Lullabot\Mpx\DataService\ObjectInterface.
entailment
public function select(ObjectListQuery $objectListQuery = null, array $options = []): ObjectListIterator { return new ObjectListIterator($this->selectRequest($objectListQuery, $options)); }
Query for MPX data using with parameters. @param ObjectListQuery $objectListQuery (optional) The fields and values to filter by. Note these are exact matches. @param array $options (optional) An array of HTTP client options. @return ObjectListIterator An iterator over the full result set.
entailment
public function selectRequest(ObjectListQuery $objectListQuery = null, array $options = []): PromiseInterface { if (!$objectListQuery) { $objectListQuery = new ObjectListQuery(); } $annotation = $this->dataService->getAnnotation(); if (!isset($options['query'])) { $options['query'] = []; } $options['query'] = $options['query'] + $objectListQuery->toQueryParts() + [ 'schema' => $annotation->schemaVersion, 'form' => 'cjson', 'count' => true, ]; if ($this->authenticatedClient->hasAccount()) { $options['query']['account'] = (string) $this->authenticatedClient->getAccount()->getMpxId(); } $uri = $this->getBaseUri($annotation, true); $request = $this->authenticatedClient->requestAsync('GET', $uri, $options)->then( function (ResponseInterface $response) use ($objectListQuery) { return $this->deserializeObjectList($response, $objectListQuery); } ); return $request; }
Return a promise to an object list. @see \Lullabot\Mpx\DataService\DataObjectFactory::select @param ObjectListQuery $objectListQuery (optional) The fields and values to filter by. Note these are exact matches. @param array $options (optional) An array of HTTP client options. @return PromiseInterface A promise to return an ObjectList.
entailment
private function deserializeObjectList(ResponseInterface $response, ObjectListQuery $byFields): ObjectList { $data = $response->getBody(); /** @var ObjectList $list */ $list = $this->deserialize($data, ObjectList::class); // Set the json representation of each entry in the list. $decoded = \GuzzleHttp\json_decode($data, true); foreach ($list as $index => $item) { $entry = $decoded['entries'][$index]; if (isset($decoded['$xmlns'])) { $entry['$xmlns'] = $decoded['$xmlns']; } $item->setJson(\GuzzleHttp\json_encode($entry)); } $list->setObjectListQuery($byFields); $list->setDataObjectFactory($this); return $list; }
Deserialize an object list response. @param ResponseInterface $response The response to deserialize. @param ObjectListQuery $byFields The fields used to limit the response. @return ObjectList The deserialized list.
entailment
private function getBaseUri(DataService $annotation, bool $readonly = false): string { // Accounts are optional as you need to be able to load an account // before you can resolve services. if (!($base = $annotation->getBaseUri())) { // If no account is specified, we must use the ResolveAllUrls service instead. if (!$this->authenticatedClient->hasAccount()) { $resolver = new ResolveAllUrls($this->authenticatedClient, $this->cacheItemPool); return $resolver->resolve($annotation->getService($readonly))->getUrl().$annotation->getPath(); } $resolved = $this->resolveDomain->resolve($this->authenticatedClient->getAccount()); $base = $resolved->getUrl($annotation->getService($readonly)).$annotation->getPath(); } return $base; }
Get the base URI from an annotation or service registry. @param DataService $annotation The annotation data is being loaded for. @param bool $readonly (optional) Load from the read-only service. @return string The base URI.
entailment
private function getObjectSerializer(PropertyTypeExtractorInterface $dataServiceExtractor): Serializer { // First, we need an encoder that filters out null values. $encoders = [new CJsonEncoder()]; // Attempt normalizing each key in this order, including denormalizing recursively. $customFieldsNormalizer = new CustomFieldsNormalizer($this->dataService->getCustomFields()); $normalizers = [ new UnixMillisecondNormalizer(), new UriNormalizer(), $customFieldsNormalizer, new ObjectNormalizer( null, null, null, $dataServiceExtractor ), new ArrayDenormalizer(), ]; $serializer = new Serializer($normalizers, $encoders); $customFieldsNormalizer->setSerializer($serializer); return $serializer; }
@param PropertyTypeExtractorInterface $dataServiceExtractor @return Serializer
entailment
protected function _getOptions() { if (array_key_exists('name', $this->_properties)) { $options = Setting::options($this->_properties['name']); if (is_callable($options)) { return $options(); } return $options; } return false; }
_getOptionsArray Getter for `options`. Array's are json-decoded. @return array
entailment
public static function fromResponseData(array $data): self { // @todo fix this as idle != duration. // @todo We need to store the date this token was created. static::validateData($data); $lifetime = (int) floor(min($data['signInResponse']['duration'], $data['signInResponse']['idleTimeout']) / 1000); $token = new self($data['signInResponse']['userId'], $data['signInResponse']['token'], $lifetime); return $token; }
Create a token from an MPX signInResponse. @todo Use something !array for the type. @param array $data The MPX response data. @return \Lullabot\Mpx\Token A new MPX token.
entailment
public static function getConstants($html = false) { $result = []; foreach ((new \ReflectionClass(get_class()))->getConstants() as $constant) { $key = static::$cssPrefix . ' ' . static::$cssPrefix . '-' . $constant; $result[$key] = ($html) ? static::icon($constant) . '&nbsp;&nbsp;' . $constant : $constant; } return $result; }
Get all icon constants for dropdown list in example @param bool $html whether to render icon as array value prefix @return array
entailment
public function generateCore($config, $bar) { $this->crudGenerator->createModel($config); $this->crudGenerator->createService($config); if (strtolower($config['framework']) === 'laravel') { $this->crudGenerator->createRequest($config); } $bar->advance(); }
Generate core elements. @param array $config @param \Symfony\Component\Console\Helper\ProgressBar $bar
entailment
public function generateAppBased($config, $bar) { if (!$config['options-serviceOnly'] && !$config['options-apiOnly']) { $this->crudGenerator->createController($config); $this->crudGenerator->createViews($config); $this->crudGenerator->createRoutes($config); if ($config['options-withFacade']) { $this->crudGenerator->createFacade($config); } } $bar->advance(); }
Generate app based elements. @param array $config @param \Symfony\Component\Console\Helper\ProgressBar $bar
entailment
public function generateDB($config, $bar, $section, $table, $splitTable, $command) { if ($config['options-migration']) { $this->dbGenerator->createMigration( $config, $section, $table, $splitTable, $command ); if ($config['options-schema']) { $this->dbGenerator->createSchema( $config, $section, $table, $splitTable, $config['options-schema'] ); } } $bar->advance(); }
Generate db elements. @param \Symfony\Component\Console\Helper\ProgressBar $bar @param string $section @param string $table @param array $splitTable @param \Grafite\CrudMaker\Console\CrudMaker $command
entailment
public function generateAPI($config, $bar) { if ($config['options-api'] || $config['options-apiOnly']) { $this->crudGenerator->createApi($config); } $bar->advance(); }
Generate api elements. @param array $config @param \Symfony\Component\Console\Helper\ProgressBar $bar
entailment
public function correctViewNamespace($config) { $controllerFile = $config['_path_controller_'].'/'.$config['_ucCamel_casePlural_'].'Controller.php'; $controller = file_get_contents($controllerFile); $controller = str_replace("view('".$config['_sectionPrefix_'].$config['_lower_casePlural_'].".", "view('".$config['_sectionPrefix_'].$config['_lower_casePlural_']."::", $controller); file_put_contents($controllerFile, $controller); }
Corrects the namespace for the view. @param array $config
entailment
public function search($params) { $query = QueueManager::find()->orderBy('id desc'); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'ttr' => $this->ttr, 'delay' => $this->delay, 'priority' => $this->priority, 'result_id' => $this->result_id, // 'created_at' => $this->created_at, // 'updated_at' => $this->updated_at, 'start_execute' => $this->start_execute, 'end_execute' => $this->end_execute, ]); $this->dayCondition($query, 'created_at'); $this->dayCondition($query, 'updated_at'); $query->andFilterWhere(['like', 'name', $this->name]) ->andFilterWhere(['like', 'sender', $this->sender]) ->andFilterWhere(['like', 'status', $this->status]) ->andFilterWhere(['like', 'class', $this->class]) ->andFilterWhere(['like', 'properties', $this->properties]) ->andFilterWhere(['like', 'data', $this->data]) ->andFilterWhere(['like', 'result', $this->result]); return $dataProvider; }
Creates data provider instance with search query applied @param array $params @return ActiveDataProvider
entailment
public function register() { $this->app->register('Vinelab\Http\HttpServiceProvider'); $this->app['vinelab.itunes'] = $this->app->share(function () { return new LaravelAgent($this->app['config'], $this->app['cache'], $this->app['vinelab.httpclient']); }); $this->app->booting(function () { $loader = \Illuminate\Foundation\AliasLoader::getInstance(); $loader->alias('ITunes', 'Vinelab\ITunes\Facades\Agent'); }); }
Register the service provider.
entailment
public function getTypes($class, $property, array $context = []) { if ('entry' !== $property) { return parent::getTypes($class, $property, $context); } if (!isset($this->class)) { throw new \LogicException('setClass() must be called before using this extractor.'); } return [new Type('object', false, $this->class)]; }
{@inheritdoc}
entailment
public function acquireToken(int $duration = null, bool $reset = false): Token { if ($reset) { $this->tokenCachePool->deleteToken($this); } // We assume that the cache is backed by shared storage across multiple // requests. In that case, it's possible for another thread to set a // token between the above delete and the next try block. try { $token = $this->tokenCachePool->getToken($this); } catch (TokenNotFoundException $e) { $token = $this->signInWithLock($duration); } return $token; }
Get a current authentication token for the account. This method will automatically generate a new token if one does not exist. @todo Do we want to make this async? @param int $duration (optional) The number of seconds for which the token should be valid. @param bool $reset Force fetching a new token, even if one exists. @return Token A valid mpx authentication token.
entailment
protected function signIn($duration = null): Token { $options = $this->signInOptions($duration); $response = $this->client->request( 'GET', self::SIGN_IN_URL, $options ); $data = \GuzzleHttp\json_decode($response->getBody(), true); $token = $this->tokenFromResponse($data); $this->logger->info( 'Retrieved a new mpx token {token} for user {username} that expires on {date}.', [ 'token' => $token->getValue(), 'username' => $this->user->getMpxUsername(), 'date' => date(DATE_ISO8601, $token->getExpiration()), ] ); return $token; }
Sign in the user and return the current token. @param int $duration (optional) The number of seconds for which the token should be valid. @return Token
entailment
public function signOut() { // @todo Handle that the token may be expired. // @todo Handle and log that mpx may error on the signout. $this->client->request( 'GET', self::SIGN_OUT_URL, [ 'query' => [ 'schema' => '1.0', 'form' => 'json', '_token' => (string) $this->tokenCachePool->getToken($this), ], ] ); $this->tokenCachePool->deleteToken($this); }
Sign out the user.
entailment
protected function signInWithLock(int $duration = null): Token { if ($this->store) { $factory = new Factory($this->store); $factory->setLogger($this->logger); $lock = $factory->createLock($this->user->getMpxUsername(), 10); // Blocking means this will throw an exception on failure. $lock->acquire(true); } try { // It's possible another thread has signed in for us, so check for a token first. $token = $this->tokenCachePool->getToken($this); } catch (TokenNotFoundException $e) { // We have the lock, and there's no token, so sign in. $token = $this->signIn($duration); } return $token; }
Sign in to mpx, with a lock to prevent sign-in stampedes. @param int $duration (optional) The number of seconds that the sign-in token should be valid for. @return Token
entailment
private function tokenFromResponse(array $data): Token { $token = Token::fromResponseData($data); // Save the token to the cache and return it. $this->tokenCachePool->setToken($this, $token); return $token; }
Instantiate and cache a token. @param array $data The mpx signIn() response data. @return Token The new token.
entailment
private function signInOptions($duration = null): array { $options = []; $options['auth'] = [ $this->user->getMpxUsername(), $this->user->getMpxPassword(), ]; // @todo Make this a class constant. $options['query'] = [ 'schema' => '1.0', 'form' => 'json', ]; // @todo move these to POST. // https://docs.theplatform.com/help/wsf-signin-method#signInmethod-JSONPOSTexample if (!empty($duration)) { // API expects this value in milliseconds, not seconds. $options['query']['_duration'] = $duration * 1000; $options['query']['_idleTimeout'] = $duration * 1000; } return $options; }
Return the query parameters for signing in. @param int $duration The duration to sign in for. @return array An array of query parameters.
entailment
private function discoverCustomFields() { $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\CustomField $annotation */ $this->registerAnnotation($class); } }
Discovers custom fields.
entailment
private function classForFile(SplFileInfo $file): string { $subnamespace = str_replace('/', '\\', $file->getRelativePath()); if (!empty($subnamespace)) { $subnamespace .= '\\'; } $class = $this->namespace.'\\'.$subnamespace.$file->getBasename('.php'); return $class; }
Given a file path, return the PSR-4 class it should contain. @param SplFileInfo $file The file to generate the class name for. @return string The fully-qualified class name.
entailment
private function registerAnnotation($class) { /** @var CustomField $annotation */ if ($annotation = $this->annotationReader->getClassAnnotation( new \ReflectionClass($class), 'Lullabot\Mpx\DataService\Annotation\CustomField' )) { if (!is_subclass_of($class, CustomFieldInterface::class)) { throw new \RuntimeException(sprintf('%s must implement %s.', $class, CustomFieldInterface::class)); } $this->customFields[$annotation->service][$annotation->objectType][$annotation->namespace] = new DiscoveredCustomField( $class, $annotation ); } }
Register an annotation and it's custom fields. @param string $class The class to inspect for a CustomField annotation.
entailment
public function sync() { // @todo Add support for filtering. $query = [ 'clientId' => $this->clientId, 'form' => 'cjson', 'schema' => '1.10', ]; if ($this->authenticatedClient->hasAccount()) { $query['account'] = (string) $this->authenticatedClient->getAccount()->getMpxId(); } return $this->authenticatedClient->requestAsync('GET', $this->uri, [ 'query' => $query, ])->then(function (ResponseInterface $response) { $data = \GuzzleHttp\json_decode($response->getBody(), true); return $data[0]['id']; }); }
Return the last available sync ID to synchronize notifications. @see https://docs.theplatform.com/help/wsf-subscribing-to-change-notifications#tp-toc10 @return \GuzzleHttp\Promise\PromiseInterface A promise to return the last sync ID as an integer.
entailment
public function listen(int $since, int $maximum = 500) { $query = [ 'clientId' => $this->clientId, 'since' => $since, 'block' => 'true', 'form' => 'cjson', 'schema' => '1.10', 'filter' => $this->service->getAnnotation()->getObjectType(), 'size' => $maximum, ]; if ($this->authenticatedClient->hasAccount()) { $query['account'] = (string) $this->authenticatedClient->getAccount()->getMpxId(); } return $this->authenticatedClient->requestAsync('GET', $this->uri, [ 'query' => $query, ])->then(function (ResponseInterface $response) { return $this->deserializeResponse($response); }); }
Listen for notifications. This method always filters to the object type defined in the discovered data service passed in the constructor, such as 'Media'. @see https://docs.theplatform.com/help/media-media-data-service-api-reference @todo Add support for a configurable timeout? @see \Lullabot\Mpx\DataService\NotificationListener::sync @see \Lullabot\Mpx\DataService\Notification @param int $since The last sync ID. @param int $maximum (optional) The maximum number of notifications to return. Defaults to 500. @return \GuzzleHttp\Promise\PromiseInterface A promise returning an array of Notification objects.
entailment
protected function deserializeResponse(ResponseInterface $response) { // First, we need an encoder that filters out null values. $encoders = [new JsonEncoder()]; // Attempt normalizing each key in this order, including denormalizing recursively. $extractor = new NotificationTypeExtractor(); $extractor->setClass($this->service->getClass()); $normalizers = [ new UnixMillisecondNormalizer(), new UriNormalizer(), new ObjectNormalizer(null, null, null, $extractor), new ArrayDenormalizer(), ]; $serializer = new Serializer($normalizers, $encoders); // @todo Handle exception returns. return $serializer->deserialize($response->getBody(), Notification::class.'[]', 'json'); }
Deserialize a notification response. @param ResponseInterface $response @return Notification
entailment
public function output ($output) { $request = Craft::$app->getRequest(); if ( $request->isCpRequest || $request->isLivePreview || $request->getAcceptsJson() ) { return $output; } return $this->generateAndAttachLinkHeaders($output); }
Handle an incoming request. @param string $output @return mixed
entailment
protected function generateAndAttachLinkHeaders ($output) { $settings = Http2ServerPush::$plugin->getSettings(); $headers = $this->fetchLinkableNodes($output, $settings->includeImages) ->flatten(1) ->map(function ($url) { return $this->buildLinkHeaderString($url); }) ->filter() ->take($settings->limit) ->implode(','); if ( !empty(trim($headers)) ) { $this->addLinkHeader($headers); } return $output; }
@param string $output @return string
entailment
protected function getCrawler (string $output) { if ( $this->crawler ) { return $this->crawler; } return $this->crawler = new Crawler($output); }
Get the DomCrawler instance. @param string $output @return Crawler
entailment
protected function fetchLinkableNodes ($output, $includeImages = false) { $crawler = $this->getCrawler($output); $filter = 'link, script[src]'; if ( $includeImages ) { $filter .= ', img[src]'; } return new Collection($crawler->filter($filter)->extract([ 'src', 'href' ])); }
Get all nodes we are interested in pushing. @param string $output @return Collection
entailment
private function buildLinkHeaderString ($url) { $linkTypeMap = [ '.CSS' => 'style', '.JS' => 'script', '.BMP' => 'image', '.GIF' => 'image', '.JPG' => 'image', '.JPEG' => 'image', '.PNG' => 'image', '.TIFF' => 'image', ]; $type = (new Collection($linkTypeMap))->first(function ($type, $extension) use ($url) { return $this->contains(strtoupper($url), $extension); }); return is_null($type) ? null : "<{$url}>; rel=preload; as={$type}"; }
Build out header string based on asset extension. @param string $url @return string
entailment
private function addLinkHeader ($link) { $headers = Craft::$app->getResponse()->getHeaders(); if ( $headers->get('Link') ) { $link = $headers->get('Link') . ',' . $link; } $headers->set('Link', $link); }
Add Link Header @param $link
entailment
public function addSort(string $field, $descending = false): self { $this->fields[$field] = $field.($descending ? '|desc' : ''); return $this; }
Add a sort to this query. @param string $field The field to sort on, such as 'id' or 'title'. @param bool $descending (optional) True if results should be sorted descending, false otherwise. @return self
entailment
public function setFeedType(?SubFeed $subFeed): void { if ($subFeed && !$subFeed->getFeedType()) { throw new \InvalidArgumentException('The feedType field must be specified on the subfeed.'); } $this->feedTypeSubFeed = $subFeed; }
Specifies a subfeed of the main feed. This corresponds to a SubFeed.FeedType value of an item in the FeedConfig.subFeeds field. @param SubFeed $subFeed
entailment
public function toUri(): UriInterface { $uri = $this->uriToFeedComponent(); $uri = $this->appendSeoTerms($uri); return $uri; }
{@inheritdoc}
entailment
protected function uriToFeedComponent(): Uri { $uri = new Uri(static::BASE_URL.$this->account->getPid().'/'.$this->feedConfig->getPid()); if ($this->feedTypeSubFeed) { $uri = $uri->withPath($uri->getPath().'/'.$this->feedTypeSubFeed->getFeedType()); } if ($this->isReturnsFeed()) { $uri = $uri->withPath($uri->getPath().'/feed'); } return $uri; }
Return a new URI with all components up to the '/feed' component. @return Uri The new URI.
entailment
protected function appendSeoTerms(UriInterface $uri): UriInterface { if (!empty($this->seoTerms)) { $uri = $uri->withPath($uri->getPath().'/'.implode('/', $this->seoTerms)); } return $uri; }
Append the SEO terms to the end of a URI. @param UriInterface $uri The URI to append to. @return UriInterface
entailment
protected function registerAssets() { $view = $this->getView(); ChosenSelectAsset::register($view); $js = '$("#' . $this->options['id'] . '").chosen(' . $this->getPluginOptions() . ');'; $view->registerJs($js, $view::POS_END); }
Register client assets
entailment
public static function si($foreground, $background, $options = []) { return static::stack($options)->icon($foreground)->on($background); }
Shortcut for stack()->icon()->on() @see stack() @see component\Stack @param mixed $foreground @param mixed $background @param array $options @return component\Icon
entailment
public static function is($foreground, $background, $options = []) { $options['template'] = '{front}{back}'; return static::stack($options)->icon($background)->on($foreground); }
Shortcut for a stack with the larger icon on top @see stack() @see component\Stack @param mixed $foreground @param mixed $background @param array $options @return component\Icon
entailment
public static function ban($object, $options = []) { $foreground = static::i('ban')->addCssClass('text-danger'); return static::is($foreground, $object, $options); }
Shortcut for is() using 'ban' as the top icon @see stack() @see component\Stack @param mixed $foreground @param mixed $background @param array $options @return component\Icon
entailment
public function compile($outputfile) { if (empty($this->index)) { throw new \LogicException('Cannot compile when no index files are defined.'); } if (file_exists($outputfile)) { unlink($outputfile); } $name = basename($outputfile); $phar = new \Phar($outputfile, 0, $name); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); foreach ($this->files as $virtualfile => $fileinfo) { list($realfile, $strip) = $fileinfo; $content = file_get_contents($realfile); if ($strip) { $content = $this->stripWhitespace($content); } $phar->addFromString($virtualfile, $content); } foreach ($this->index as $type => $fileinfo) { list($virtualfile, $realfile) = $fileinfo; $content = file_get_contents($realfile); if ($type == 'cli') { $content = preg_replace('{^#!/usr/bin/env php\s*}', '', $content); } $phar->addFromString($virtualfile, $content); } $stub = $this->generateStub($name); $phar->setStub($stub); $phar->stopBuffering(); unset($phar); }
Compiles all files into a single PHAR file. @param string $outputfile The full name of the file to create @throws \LogicException if no index files are defined.
entailment
public function addFile($file, $strip = true) { $realfile = realpath($this->path . DIRECTORY_SEPARATOR . $file); $this->files[$file] = [$realfile, (bool) $strip]; }
Adds a file. @param string $file The name of the file relative to the project root @param bool $strip Strip whitespace (Default: TRUE)
entailment
public function addDirectory($directory, $exclude = null, $strip = true) { $realpath = realpath($this->path . DIRECTORY_SEPARATOR . $directory); $iterator = new \RecursiveDirectoryIterator($realpath, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS); if ((is_string($exclude) || is_array($exclude)) && !empty($exclude)) { $iterator = new \RecursiveCallbackFilterIterator($iterator, function ($current) use ($exclude, $realpath) { if ($current->isDir()) { return true; } $subpath = substr($current->getPathName(), strlen($realpath) + 1); return $this->filter($subpath, (array) $exclude); }); } $iterator = new \RecursiveIteratorIterator($iterator); foreach ($iterator as $file) { $virtualfile = substr($file->getPathName(), strlen($this->path) + 1); $this->addFile($virtualfile, $strip); } }
Adds files of the given directory recursively. @param string $directory The name of the directory relative to the project root @param string|array $exclude List of file name patterns to exclude (optional) @param bool $strip Strip whitespace (Default: TRUE)
entailment
public function addIndexFile($file, $type = 'cli') { $type = strtolower($type); if (!in_array($type, ['cli', 'web'])) { throw new \InvalidArgumentException(sprintf('Index file type "%s" is invalid, must be one of: cli, web', $type)); } $this->index[$type] = [$file, realpath($this->path . DIRECTORY_SEPARATOR . $file)]; }
Adds an index file. @param string $file The name of the file relative to the project root @param string $type The SAPI type (Default: 'cli')
entailment
protected function generateStub($name) { $stub = array('#!/usr/bin/env php', '<?php'); $stub[] = "Phar::mapPhar('$name');"; $stub[] = "if (PHP_SAPI == 'cli') {"; if (isset($this->index['cli'])) { $file = $this->index['cli'][0]; $stub[] = " require 'phar://$name/$file';"; } else { $stub[] = " exit('This program can not be invoked via the CLI version of PHP, use the Web interface instead.'.PHP_EOL);"; } $stub[] = '} else {'; if (isset($this->index['web'])) { $file = $this->index['web'][0]; $stub[] = " require 'phar://$name/$file';"; } else { $stub[] = " exit('This program can not be invoked via the Web interface, use the CLI version of PHP instead.'.PHP_EOL);"; } $stub[] = '}'; $stub[] = '__HALT_COMPILER();'; return join("\n", $stub); }
Generates the stub. @param string $name The internal Phar name @return string
entailment
protected function filter($path, array $patterns) { foreach ($patterns as $pattern) { if ($pattern[0] == '!' ? !fnmatch(substr($pattern, 1), $path) : fnmatch($pattern, $path)) { return false; } } return true; }
Filters the given path. @param array $patterns @return bool
entailment
private function filterRequestParameters(array $httpRequest) { //filter request for Sips parameters if (!array_key_exists(self::DATA_FIELD, $httpRequest) || $httpRequest[self::DATA_FIELD] == '') { throw new InvalidArgumentException('Data parameter not present in parameters.'); } $parameters = array(); $dataString = $httpRequest[self::DATA_FIELD]; $this->dataString = $dataString; $dataParams = explode('|', $dataString); foreach ($dataParams as $dataParamString) { $dataKeyValue = explode('=', $dataParamString, 2); $parameters[$dataKeyValue[0]] = $dataKeyValue[1]; } return $parameters; }
Filter http request parameters @param array $requestParameters
entailment
public function getParam($key) { if (method_exists($this, 'get'.$key)) { return $this->{'get'.$key}(); } // always use uppercase $key = strtoupper($key); $parameters = array_change_key_case($this->parameters, CASE_UPPER); if (!array_key_exists($key, $parameters)) { throw new InvalidArgumentException('Parameter ' . $key . ' does not exist.'); } return $parameters[$key]; }
Retrieves a response parameter @param string $param @throws \InvalidArgumentException
entailment
public function setStartIndex(int $startIndex): self { if ($startIndex < 1) { throw new \RangeException('The start index must be 1 or greater.'); } $this->startIndex = $startIndex; return $this; }
The start index of this range. @param int $startIndex @return self
entailment
public static function nextRange(ObjectList $list): self { $range = new self(); $start = $list->getStartIndex() + $list->getEntryCount(); $range->setStartIndex($start) ->setEndIndex($start - 1 + $list->getItemsPerPage()); return $range; }
Given an object list, return the range to load the next page of objects. @param ObjectList $list The list to find the next page for. @return Range A new range.
entailment
public static function nextRanges(ObjectList $list): array { $ranges = []; // The end index of the next list. We do this here in case there are no further ranges to return. $endIndex = $list->getStartIndex() + $list->getItemsPerPage() - 1; // The last index of the final list. $finalEndIndex = $list->getTotalResults(); while ($endIndex < $finalEndIndex) { // The start index of the next list. $startIndex = ($startIndex ?? $list->getStartIndex()) + $list->getEntryCount(); // We need to be sure we never return an end range greater than the total count of objects. $endIndex = min($startIndex + $list->getItemsPerPage() - 1, $finalEndIndex); $range = new self(); $range->setStartIndex($startIndex) ->setEndIndex($endIndex); $ranges[] = $range; } return $ranges; }
Given an object list, return the ranges for each subsequent page. @param ObjectList $list The list to generate ranges for. @return static[] An array of Range objects.
entailment
public function toQueryParts(): array { if (empty($this->startIndex) && empty($this->endIndex)) { return []; } // @todo PHP appears to leak memory in both json_decode() and unserialize() with large result sets. Our best // guess is that some amount of data causes PHP to allocate larger chunks, and perhaps that class of memory // isn't ever a candidate for garbage collection. In general, paging over result sets (like in // \Lullabot\Mpx\Tests\Functional\DataService\Media\MediaQueryTest) should use a constant amount of memory per // page. 250 comes from tests on macOS with PHP 7.2 - going to 300 results causes an obvious memory leak. if ($this->endIndex - $this->startIndex > 250) { @trigger_error('PHP may leak memory with large result pages. Consider reducing the number of results per page.', E_USER_DEPRECATED); } return ['range' => $this->startIndex.'-'.$this->endIndex]; }
Return an array of query parameters representing this range. @return array An array with a 'range' key, or an empty array if neither start or end is set.
entailment
public function valid() { // Initial setup if this is the first page. if (empty($this->list)) { $this->list = $this->promise->wait(); } $requested_page = floor($this->position / $this->list->getItemsPerPage()); while ($requested_page > $this->page) { // There is no next page to retrieve, but we just asked to go beyond the last page. if (!$next = $this->list->nextList()) { return false; } $this->list = $next->wait(); ++$this->page; } // Now, figure out the relative index. $this->relative = $this->position % $this->list->getItemsPerPage(); if (isset($this->list[$this->relative])) { return true; } // The last page is not completely full, but the relative position does // not exist. return false; }
{@inheritdoc}
entailment
public function renderItems() { $items = []; foreach ($this->items as $i => $item) { if (isset($item['visible']) && !$item['visible']) { continue; } $items[] = $this->renderItem($item); } // Begin custom code $hasActive = false; foreach ($this->items as $i => $child) { if($this->isItemActive($child)) { $hasActive = true; break; } } if(!$hasActive) { Html::addCssClass($this->options, 'collapse'); } // End custom code return Html::tag('ul', implode("\n", $items), $this->options); }
Customized widget for MetisMenu navigation dropdowns to not flicker on page load by precomputing if the menu should be open or not. Portions were added below to add the 'collapse' css class if there is an item active within the submenu.
entailment
private function getDocBlockFromProperty($class, $property) { // Use a ReflectionProperty instead of $class to get the parent class if applicable try { $reflectionProperty = new \ReflectionProperty($class, $property); } catch (\ReflectionException $e) { return; } return $this->docBlockFactory->create($reflectionProperty, $this->contextFactory->createFromReflector($reflectionProperty->getDeclaringClass())); }
Gets the DocBlock from a property. @param string $class @param string $property @return DocBlock|null
entailment
public function toUri(): UriInterface { $str = $this::BASE_URL.$this->account->getPid().'/'.$this->player->getPid(); if ($this->embed) { $str .= '/embed'; } if ($this->byGuid) { $ownerId = $this->media->getOwnerId(); $parts = explode('/', $ownerId); $numeric_id = end($parts); $uri = new Uri($str.'/select/media/guid/'.$numeric_id.'/'.$this->media->getGuid()); } else { $uri = new Uri($str.'/select/media/'.$this->media->getPid()); } $query_parts = []; // We use isset() so that if the values have never been explicitly set // the player configuration is used instead. if (isset($this->autoPlay)) { $query_parts['autoPlay'] = $this->autoPlay ? 'true' : 'false'; } if (isset($this->playAll)) { $query_parts['playAll'] = $this->playAll ? 'true' : 'false'; } $uri = $uri->withQuery(build_query($query_parts)); return $uri; }
Return the URL for this player and media. @return UriInterface
entailment
public function withAutoplay(bool $autoPlay): self { if ($this->autoPlay == $autoPlay) { return $this; } $url = clone $this; $url->autoPlay = $autoPlay; return $url; }
Override the player's autoplay setting for this URL. @see https://docs.theplatform.com/help/player-player-autoplay @param bool $autoPlay True to enable autoPlay, false otherwise. @return Url
entailment
public function withPlayAll(bool $playAll): self { if ($this->playAll == $playAll) { return $this; } $url = clone $this; $url->playAll = $playAll; return $url; }
Override the player's playAll setting for playlist auto-advance for this URL. @see https://docs.theplatform.com/help/player-player-playall @param bool $playAll @return Url
entailment
public function withEmbed(bool $embed): self { if ($this->embed == $embed) { return $this; } $url = clone $this; $url->embed = $embed; return $url; }
@param bool $embed @return Url
entailment
public function withMediaByGuid(): self { if ($this->byGuid) { return $this; } $url = clone $this; $url->byGuid = true; return $url; }
Return a Url using media reference GUIDs instead of media public IDs. @return Url
entailment
public function withMediaByPublicId(): self { if (!$this->byGuid) { return $this; } $url = clone $this; $url->byGuid = false; return $url; }
Return a Url using media public IDs instead of media reference Ids. @return Url
entailment
public static function shortenUrl($inputUrl) { if(!self::checkInput($inputUrl)) { return false; } $encodedUrl = rawurlencode($inputUrl); $contextOptions = array( 'ssl' => array( 'verify_peer' => false, //'verify_peer' => true, // You could skip all of the trouble by changing this to false, but it's WAY uncool for security reasons. //'cafile' => require 'base/ssl/cacert.pem', //'CN_match' => 'is.gd', // Change this to your certificates Common Name (or just comment this line out if not needed) //'ciphers' => 'HIGH:!SSLv2:!SSLv3', //'disable_compression' => true, ) ); $context = stream_context_create($contextOptions); $shortenedUrl = file_get_contents(self::ISGD_BASIC . $encodedUrl, false, $context); return self::checkResult($shortenedUrl); }
/* IsGdHelper::shortenUrl('www.example.com')
entailment