sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function validConfig() { foreach ($this->struct_config as $key => $value) { if ($value['obrigatorio'] && !isset($this->config->$key)) { throw new Olx_Auth_Exception("Valor obrigatório não preenchido no config [$key]."); } } }
@see Client:createAuthUrl @return bool Valida se todas as informações necessárias estão no config para que seja gerada a url de autenticação
entailment
public function getBase() { return [ 'oauth_consumer_key' => $this->config->getClientCredentialsIdentifier(), 'oauth_nonce' => $this->nonceGenerator->generate(), 'oauth_signature_method' => $this->signer->getMethod(), 'oauth_timestamp' => "{$this->getCurrentTimestamp()}", 'oauth_version' => $this->getVersion(), ]; }
{@inheritdoc}
entailment
public function forTemporaryCredentials() { $parameters = $this->getBase(); if ($this->config->hasCallbackUri()) { $parameters['oauth_callback'] = $this->config->getCallbackUri(); } $parameters['oauth_signature'] = $this->getSignature($parameters, $this->config->getTemporaryCredentialsUri()); return $parameters; }
{@inheritdoc}
entailment
public function forTokenCredentials(TemporaryCredentials $temporaryCredentials, $verificationCode) { $parameters = $this->getBase(); $parameters['oauth_token'] = $temporaryCredentials->getIdentifier(); $requestOptions = [ 'form_params' => ['oauth_verifier' => $verificationCode], ]; $parameters['oauth_signature'] = $this->getSignature( $parameters, $this->config->getTokenCredentialsUri(), $temporaryCredentials, $requestOptions ); return $parameters; }
{@inheritdoc}
entailment
public function forProtectedResource(TokenCredentials $tokenCredentials, $httpMethod, $uri, array $requestOptions = []) { $parameters = $this->getBase(); $parameters['oauth_token'] = $tokenCredentials->getIdentifier(); $parameters['oauth_signature'] = $this->getSignature( $parameters, $this->config->buildUri($uri), $tokenCredentials, $requestOptions, $httpMethod ); return $parameters; }
{@inheritdoc}
entailment
public function getSignature(array $protocolParameters, $uri, ServerIssuedCredentials $serverIssuedCredentials = null, array $requestOptions = [], $httpMethod = 'POST') { $signatureParameters = $this->signatureParameters($protocolParameters, $requestOptions); return $this->setupSigner($serverIssuedCredentials) ->sign($uri, $signatureParameters, $httpMethod); }
{@inheritdoc}
entailment
public function signatureParameters(array $protocolParameters, array $requestOptions = []) { $parameters = $protocolParameters; if ($this->requestOptionsHas($requestOptions, 'query')) { $parameters = array_merge($parameters, $requestOptions['query']); } if ($this->requestOptionsHas($requestOptions, 'form_params')) { $parameters = array_merge($parameters, $requestOptions['form_params']); } return $parameters; }
Build the signature parameters to be signed. @param array $protocolParameters @param array $requestOptions @return array
entailment
public function setupSigner(ServerIssuedCredentials $serverIssuedCredentials = null) { if ($this->shouldSignWithClientCredentials()) { $this->signer->setClientCredentials($this->config->getClientCredentials()); } if ($this->shouldSignWithServerIssuedCredentials($serverIssuedCredentials)) { $this->signer->setServerIssuedCredentials($serverIssuedCredentials); } return $this->signer; }
Setup the signer. @param \Risan\OAuth1\Credentials\ServerIssuedCredentials|null $serverIssuedCredentials @return \Risan\OAuth1\Signature\SignerInterface
entailment
public function requestOptionsHas(array $requestOptions, $key) { return isset($requestOptions[$key]) && is_array($requestOptions[$key]) && count($requestOptions[$key]) > 0; }
Check if request options has the given key option. @param array $requestOptions @param string $key @return bool
entailment
public function generate($length = 32) { $nonce = ''; while (($currentNonceLength = strlen($nonce)) < $length) { $size = $length - $currentNonceLength; $randomString = $this->base64EncodedRandomBytes($size); $nonce .= substr($this->extractAlphaNumericFromBase64EncodedString($randomString), 0, $size); } return $nonce; }
{@inheritdoc}
entailment
public function build($httpMethod, $uri, array $parameters = []) { $uri = $this->uriParser->toPsrUri($uri); $components = []; $components[] = rawurlencode($this->buildMethodComponent($httpMethod)); $components[] = rawurlencode($this->buildUriComponent($uri)); parse_str($uri->getQuery(), $queryParameters); $components[] = rawurlencode($this->buildParametersComponent(array_merge($queryParameters, $parameters))); return implode('&', $components); }
{@inheritdoc}
entailment
public function buildUriComponent($uri) { $uri = $this->uriParser->toPsrUri($uri); return $this->uriParser->buildFromParts([ 'scheme' => $uri->getScheme(), 'host' => $uri->getHost(), 'port' => $uri->getPort(), 'path' => $uri->getPath(), ]); }
{@inheritdoc}
entailment
public function normalizeParameters(array $parameters) { $normalized = []; // [1] Encode both the keys and values. // Decode it frist, in case the given data is already encoded. foreach ($parameters as $key => $value) { $key = rawurlencode(rawurldecode($key)); if (is_array($value)) { $normalized[$key] = $this->normalizeParameters($value); } else { $normalized[$key] = rawurlencode(rawurldecode($value)); } } // [2] Sort by the encoded key. ksort($normalized); return $normalized; }
Normalize the given request parameters. @param array $parameters @return array
entailment
public function buildQueryString(array $parameters, array $initialQueryParameters = [], $previousKey = null) { $queryParameters = $initialQueryParameters; foreach ($parameters as $key => $value) { if (null !== $previousKey) { $key = "{$previousKey}[{$key}]"; } if (is_array($value)) { $queryParameters = $this->buildQueryString($value, $queryParameters, $key); } else { $queryParameters[] = "{$key}={$value}"; } } return null !== $previousKey ? $queryParameters : implode('&', $queryParameters); }
Build query string from the given parameters. @param array $parameters @param array $initialQueryParameters @param string $previousKey @return string
entailment
public function forTokenCredentials(TemporaryCredentials $temporaryCredentials, $verificationCode) { return $this->normalizeProtocolParameters( $this->protocolParameter->forTokenCredentials($temporaryCredentials, $verificationCode) ); }
{@inheritdoc}
entailment
public function forProtectedResource(TokenCredentials $tokenCredentials, $httpMethod, $uri, array $requestOptions = []) { return $this->normalizeProtocolParameters( $this->protocolParameter->forProtectedResource($tokenCredentials, $httpMethod, $uri, $requestOptions) ); }
{@inheritdoc}
entailment
public function request($method, $uri, array $options = []) { return $this->guzzle->request($method, $uri, $options); }
{@inheritdoc}
entailment
public function send(RequestInterface $request) { return $this->request( $request->getMethod(), $request->getUri(), $request->getOptions() ); }
{@inheritdoc}
entailment
public function createTemporaryCredentialsFromResponse(ResponseInterface $response) { $parameters = $this->getParametersFromResponse($response); $missingParameterKey = $this->getMissingParameterKey($parameters, [ 'oauth_token', 'oauth_token_secret', 'oauth_callback_confirmed', ]); if (null !== $missingParameterKey) { throw new CredentialsException("Unable to parse temporary credentials response. Missing parameter: {$missingParameterKey}."); } if ('true' !== $parameters['oauth_callback_confirmed']) { throw new CredentialsException('Unable to parse temporary credentials response. Callback URI is not valid.'); } return new TemporaryCredentials($parameters['oauth_token'], $parameters['oauth_token_secret']); }
{@inheritdoc}
entailment
public function createTokenCredentialsFromResponse(ResponseInterface $response) { $parameters = $this->getParametersFromResponse($response); $missingParameterKey = $this->getMissingParameterKey($parameters, [ 'oauth_token', 'oauth_token_secret', ]); if (null !== $missingParameterKey) { throw new CredentialsException("Unable to parse token credentials response. Missing parameter: {$missingParameterKey}."); } return new TokenCredentials($parameters['oauth_token'], $parameters['oauth_token_secret']); }
{@inheritdoc}
entailment
public function getParametersFromResponse(ResponseInterface $response) { $contents = $response->getBody()->getContents(); $parameters = []; parse_str($contents, $parameters); return $parameters; }
Get parameters from response. @param \Psr\Http\Message\ResponseInterface $response @return array
entailment
public function getMissingParameterKey(array $parameters, array $requiredKeys = []) { foreach ($requiredKeys as $key) { if (! isset($parameters[$key])) { return $key; } } }
Get missing parameter's key. @param array $parameters @param array $requiredKeys @return string|null
entailment
public function register(Container $container) { foreach ($this->getOrmDefaults() as $key => $value) { if (!isset($container[$key])) { $container[$key] = $value; } } $container['orm.em.default_options'] = array( 'connection' => 'default', 'mappings' => array(), 'types' => array() ); $container['orm.ems.options.initializer'] = $container->protect(function () use ($container) { static $initialized = false; if ($initialized) { return; } $initialized = true; if (!isset($container['orm.ems.options'])) { $container['orm.ems.options'] = array('default' => isset($container['orm.em.options']) ? $container['orm.em.options'] : array()); } $tmp = $container['orm.ems.options']; foreach ($tmp as $name => &$options) { $options = array_replace($container['orm.em.default_options'], $options); if (!isset($container['orm.ems.default'])) { $container['orm.ems.default'] = $name; } } $container['orm.ems.options'] = $tmp; }); $container['orm.em_name_from_param_key'] = $container->protect(function ($paramKey) use ($container) { $container['orm.ems.options.initializer'](); if (isset($container[$paramKey])) { return $container[$paramKey]; } return $container['orm.ems.default']; }); $container['orm.ems'] = function ($container) { $container['orm.ems.options.initializer'](); $ems = new Container(); foreach ($container['orm.ems.options'] as $name => $options) { if ($container['orm.ems.default'] === $name) { // we use shortcuts here in case the default has been overridden $config = $container['orm.em.config']; } else { $config = $container['orm.ems.config'][$name]; } $ems[$name] = function ($ems) use ($container, $options, $config) { return EntityManager::create( $container['dbs'][$options['connection']], $config, $container['dbs.event_manager'][$options['connection']] ); }; } return $ems; }; $container['orm.ems.config'] = function ($container) { $container['orm.ems.options.initializer'](); $configs = new Container(); foreach ($container['orm.ems.options'] as $name => $options) { $config = new Configuration; $container['orm.cache.configurer']($name, $config, $options); $config->setProxyDir($container['orm.proxies_dir']); $config->setProxyNamespace($container['orm.proxies_namespace']); $config->setAutoGenerateProxyClasses($container['orm.auto_generate_proxies']); $config->setCustomStringFunctions($container['orm.custom.functions.string']); $config->setCustomNumericFunctions($container['orm.custom.functions.numeric']); $config->setCustomDatetimeFunctions($container['orm.custom.functions.datetime']); $config->setCustomHydrationModes($container['orm.custom.hydration_modes']); $config->setClassMetadataFactoryName($container['orm.class_metadata_factory_name']); $config->setDefaultRepositoryClassName($container['orm.default_repository_class']); $config->setEntityListenerResolver($container['orm.entity_listener_resolver']); $config->setRepositoryFactory($container['orm.repository_factory']); $config->setNamingStrategy($container['orm.strategy.naming']); $config->setQuoteStrategy($container['orm.strategy.quote']); $chain = $container['orm.mapping_driver_chain.locator']($name); foreach ((array) $options['mappings'] as $entity) { if (!is_array($entity)) { throw new \InvalidArgumentException( "The 'orm.em.options' option 'mappings' should be an array of arrays." ); } if (isset($entity['alias'])) { $config->addEntityNamespace($entity['alias'], $entity['namespace']); } switch ($entity['type']) { case 'annotation': $useSimpleAnnotationReader = isset($entity['use_simple_annotation_reader']) ? $entity['use_simple_annotation_reader'] : true; $driver = $config->newDefaultAnnotationDriver((array) $entity['path'], $useSimpleAnnotationReader); $chain->addDriver($driver, $entity['namespace']); break; case 'yml': $driver = new YamlDriver($entity['path']); $chain->addDriver($driver, $entity['namespace']); break; case 'simple_yml': $driver = new SimplifiedYamlDriver(array($entity['path'] => $entity['namespace'])); $chain->addDriver($driver, $entity['namespace']); break; case 'xml': $driver = new XmlDriver($entity['path']); $chain->addDriver($driver, $entity['namespace']); break; case 'simple_xml': $driver = new SimplifiedXmlDriver(array($entity['path'] => $entity['namespace'])); $chain->addDriver($driver, $entity['namespace']); break; case 'php': $driver = new StaticPHPDriver($entity['path']); $chain->addDriver($driver, $entity['namespace']); break; default: throw new \InvalidArgumentException(sprintf('"%s" is not a recognized driver', $entity['type'])); break; } } $config->setMetadataDriverImpl($chain); foreach ((array) $options['types'] as $typeName => $typeClass) { if (Type::hasType($typeName)) { Type::overrideType($typeName, $typeClass); } else { Type::addType($typeName, $typeClass); } } $configs[$name] = $config; } return $configs; }; $container['orm.cache.configurer'] = $container->protect(function ($name, Configuration $config, $options) use ($container) { $config->setMetadataCacheImpl($container['orm.cache.locator']($name, 'metadata', $options)); $config->setQueryCacheImpl($container['orm.cache.locator']($name, 'query', $options)); $config->setResultCacheImpl($container['orm.cache.locator']($name, 'result', $options)); $config->setHydrationCacheImpl($container['orm.cache.locator']($name, 'hydration', $options)); }); $container['orm.cache.locator'] = $container->protect(function ($name, $cacheName, $options) use ($container) { $cacheNameKey = $cacheName . '_cache'; if (!isset($options[$cacheNameKey])) { $options[$cacheNameKey] = $container['orm.default_cache']; } if (isset($options[$cacheNameKey]) && !is_array($options[$cacheNameKey])) { $options[$cacheNameKey] = array( 'driver' => $options[$cacheNameKey], ); } if (!isset($options[$cacheNameKey]['driver'])) { throw new \RuntimeException("No driver specified for '$cacheName'"); } $driver = $options[$cacheNameKey]['driver']; $cacheInstanceKey = 'orm.cache.instances.'.$name.'.'.$cacheName; if (isset($container[$cacheInstanceKey])) { return $container[$cacheInstanceKey]; } $cache = $container['orm.cache.factory']($driver, $options[$cacheNameKey]); if (isset($options['cache_namespace']) && $cache instanceof CacheProvider) { $cache->setNamespace($options['cache_namespace']); } return $container[$cacheInstanceKey] = $cache; }); $container['orm.cache.factory.backing_memcache'] = $container->protect(function () { return new \Memcache; }); $container['orm.cache.factory.memcache'] = $container->protect(function ($cacheOptions) use ($container) { if (empty($cacheOptions['host']) || empty($cacheOptions['port'])) { throw new \RuntimeException('Host and port options need to be specified for memcache cache'); } /** @var \Memcache $memcache */ $memcache = $container['orm.cache.factory.backing_memcache'](); $memcache->connect($cacheOptions['host'], $cacheOptions['port']); $cache = new MemcacheCache; $cache->setMemcache($memcache); return $cache; }); $container['orm.cache.factory.backing_memcached'] = $container->protect(function () { return new \Memcached; }); $container['orm.cache.factory.memcached'] = $container->protect(function ($cacheOptions) use ($container) { if (empty($cacheOptions['host']) || empty($cacheOptions['port'])) { throw new \RuntimeException('Host and port options need to be specified for memcached cache'); } /** @var \Memcached $memcached */ $memcached = $container['orm.cache.factory.backing_memcached'](); $memcached->addServer($cacheOptions['host'], $cacheOptions['port']); $cache = new MemcachedCache; $cache->setMemcached($memcached); return $cache; }); $container['orm.cache.factory.backing_redis'] = $container->protect(function () { return new \Redis; }); $container['orm.cache.factory.redis'] = $container->protect(function ($cacheOptions) use ($container) { if (empty($cacheOptions['host']) || empty($cacheOptions['port'])) { throw new \RuntimeException('Host and port options need to be specified for redis cache'); } /** @var \Redis $redis */ $redis = $container['orm.cache.factory.backing_redis'](); $redis->connect($cacheOptions['host'], $cacheOptions['port']); if (isset($cacheOptions['password'])) { $redis->auth($cacheOptions['password']); } $cache = new RedisCache; $cache->setRedis($redis); return $cache; }); $container['orm.cache.factory.array'] = $container->protect(function () { return new ArrayCache; }); $container['orm.cache.factory.apc'] = $container->protect(function () { return new ApcCache; }); $container['orm.cache.factory.xcache'] = $container->protect(function () { return new XcacheCache; }); $container['orm.cache.factory.filesystem'] = $container->protect(function ($cacheOptions) { if (empty($cacheOptions['path'])) { throw new \RuntimeException('FilesystemCache path not defined'); } $cacheOptions += array( 'extension' => FilesystemCache::EXTENSION, 'umask' => 0002, ); return new FilesystemCache($cacheOptions['path'], $cacheOptions['extension'], $cacheOptions['umask']); }); $container['orm.cache.factory.couchbase'] = $container->protect(function($cacheOptions){ $host=''; $bucketName=''; $user=''; $password=''; if (empty($cacheOptions['host'])) { $host='127.0.0.1'; } if (empty($cacheOptions['bucket'])) { $bucketName='default'; } if (!empty($cacheOptions['user'])) { $user=$cacheOptions['user']; } if (!empty($cacheOptions['password'])) { $password=$cacheOptions['password']; } $couchbase = new \Couchbase($host,$user,$password,$bucketName); $cache = new CouchbaseCache(); $cache->setCouchbase($couchbase); return $cache; }); $container['orm.cache.factory'] = $container->protect(function ($driver, $cacheOptions) use ($container) { $cacheFactoryKey = 'orm.cache.factory.'.$driver; if (!isset($container[$cacheFactoryKey])) { throw new \RuntimeException("Factory '$cacheFactoryKey' for cache type '$driver' not defined (is it spelled correctly?)"); } return $container[$cacheFactoryKey]($cacheOptions); }); $container['orm.mapping_driver_chain.locator'] = $container->protect(function ($name = null) use ($container) { $container['orm.ems.options.initializer'](); if (null === $name) { $name = $container['orm.ems.default']; } $cacheInstanceKey = 'orm.mapping_driver_chain.instances.'.$name; if (isset($container[$cacheInstanceKey])) { return $container[$cacheInstanceKey]; } return $container[$cacheInstanceKey] = $container['orm.mapping_driver_chain.factory']($name); }); $container['orm.mapping_driver_chain.factory'] = $container->protect(function ($name) use ($container) { return new MappingDriverChain; }); $container['orm.add_mapping_driver'] = $container->protect(function (MappingDriver $mappingDriver, $namespace, $name = null) use ($container) { $container['orm.ems.options.initializer'](); if (null === $name) { $name = $container['orm.ems.default']; } /** @var MappingDriverChain $driverChain */ $driverChain = $container['orm.mapping_driver_chain.locator']($name); $driverChain->addDriver($mappingDriver, $namespace); }); $container['orm.strategy.naming'] = function($container) { return new DefaultNamingStrategy; }; $container['orm.strategy.quote'] = function($container) { return new DefaultQuoteStrategy; }; $container['orm.entity_listener_resolver'] = function($container) { return new DefaultEntityListenerResolver; }; $container['orm.repository_factory'] = function($container) { return new DefaultRepositoryFactory; }; $container['orm.em'] = function ($container) { $ems = $container['orm.ems']; return $ems[$container['orm.ems.default']]; }; $container['orm.em.config'] = function ($container) { $configs = $container['orm.ems.config']; return $configs[$container['orm.ems.default']]; }; }
Register ORM service. @param Container $container
entailment
public function appendQueryParameters(UriInterface $uri, array $parameters = []) { parse_str($uri->getQuery(), $existedParameters); $mergedParameters = array_merge($existedParameters, $parameters); return $uri->withQuery(http_build_query($mergedParameters)); }
{@inheritdoc}
entailment
public function toPsrUri($uri) { if ($uri instanceof UriInterface) { return $uri; } elseif (is_string($uri)) { return new Uri($uri); } throw new InvalidArgumentException('URI must be a string or an instance of \Psr\Http\Message\UriInterface.'); }
{@inheritdoc}
entailment
public static function create(ProviderInterface $provider, array $config) { return OAuth1Factory::create( array_merge($provider->getUriConfig(), $config), $provider->getSigner() ); }
/* Create the new OAuth1Interface instance based on the provider config. @param \Risan\OAuth1\Provider\ProviderInterface $provider @param array $config @return \Risan\OAuth1\OAuth1Interface
entailment
public function getKey() { $key = ''; if ($this->clientCredentials instanceof ClientCredentials) { $key .= rawurlencode($this->clientCredentials->getSecret()); } // Keep the ampersand even if both keys are empty. $key .= '&'; if ($this->serverIssuedCredentials instanceof ServerIssuedCredentials) { $key .= rawurlencode($this->serverIssuedCredentials->getSecret()); } return $key; }
Get the key for signing. @return string
entailment
public function requestTemporaryCredentials() { $response = $this->httpClient->send($this->requestFactory->createForTemporaryCredentials()); return $this->credentialsFactory->createTemporaryCredentialsFromResponse($response); }
{@inheritdoc}
entailment
public function requestTokenCredentials(TemporaryCredentials $temporaryCredentials, $temporaryIdentifier, $verificationCode) { if ($temporaryCredentials->getIdentifier() !== $temporaryIdentifier) { throw new InvalidArgumentException('The given temporary credentials identifier does not match the temporary credentials.'); } $response = $this->httpClient->send( $this->requestFactory->createForTokenCredentials($temporaryCredentials, $verificationCode) ); return $this->credentialsFactory->createTokenCredentialsFromResponse($response); }
{@inheritdoc}
entailment
public function request($method, $uri, array $options = []) { if (null === $this->getTokenCredentials()) { throw new CredentialsException('No token credential has been set.'); } return $this->httpClient->send( $this->requestFactory->createForProtectedResource($this->getTokenCredentials(), $method, $uri, $options) ); }
{@inheritdoc}
entailment
public function setFromArray(array $uris) { $this->validateUris($uris); $this->temporaryCredentials = $this->parser->toPsrUri($uris['temporary_credentials_uri']); $this->authorization = $this->parser->toPsrUri($uris['authorization_uri']); $this->tokenCredentials = $this->parser->toPsrUri($uris['token_credentials_uri']); if (isset($uris['base_uri'])) { $this->setBase($this->parser->toPsrUri($uris['base_uri'])); } if (isset($uris['callback_uri'])) { $this->callback = $this->parser->toPsrUri($uris['callback_uri']); } return $this; }
Set URIs from an array. @param array $uris @return \Risan\OAuth1\Config\UriConfig
entailment
public function validateUris(array $uris) { $requiredParams = [ 'temporary_credentials_uri', 'authorization_uri', 'token_credentials_uri', ]; foreach ($requiredParams as $param) { if (! isset($uris[$param])) { throw new InvalidArgumentException("Missing URI configuration: {$param}."); } } return true; }
Validate the given URI array. @param array $uris @return bool @throws \InvalidArgumentException
entailment
public function setBase(UriInterface $uri) { if (! $this->parser->isAbsolute($uri)) { throw new InvalidArgumentException('The base URI must be absolute.'); } $this->base = $uri; return $this; }
Set the base URI. @param \Psr\Http\Message\UriInterface $uri @return \Risan\OAuth1\Config\UriConfig @throws \InvalidArgumentException
entailment
public function build($uri) { $uri = $this->parser->toPsrUri($uri); if ($this->shouldBeResolvedToAbsoluteUri($uri)) { $uri = $this->parser->resolve($this->base(), $uri); } return $this->parser->isMissingScheme($uri) ? $uri->withScheme('http') : $uri; }
{@inheritdoc}
entailment
public function createFromArray(array $config) { $requiredParams = [ 'client_credentials_identifier', 'client_credentials_secret', 'temporary_credentials_uri', 'authorization_uri', 'token_credentials_uri', ]; foreach ($requiredParams as $param) { if (! isset($config[$param])) { throw new InvalidArgumentException("Missing OAuth1 client configuration: {$param}."); } } $clientCredentials = new ClientCredentials( $config['client_credentials_identifier'], $config['client_credentials_secret'] ); $uriConfig = new UriConfig($config, new UriParser()); return new Config($clientCredentials, $uriConfig); }
{@inheritdoc}
entailment
public static function create(array $config, $signer = null) { if (null === $signer) { $signer = new HmacSha1Signer(); } if (! $signer instanceof SignerInterface) { throw new InvalidArgumentException('The signer must implement the \Risan\OAuth1\Signature\SignerInterface.'); } $configFactory = new ConfigFactory(); $protocolParameter = new ProtocolParameter( $configFactory->createFromArray($config), $signer, new NonceGenerator() ); $authorizationHeader = new AuthorizationHeader($protocolParameter); $requestFactory = new RequestFactory($authorizationHeader, new UriParser()); return new OAuth1(new HttpClient(), $requestFactory, new CredentialsFactory()); }
Create the new OAuth1Interface instance. @param array $config @param \Risan\OAuth1\Signature\SignerInterface|null $signer @return \Risan\OAuth1\OAuth1Interface
entailment
public function buildBaseString($uri, array $parameters = [], $httpMethod = 'POST') { return $this->getBaseStringBuilder()->build($httpMethod, $uri, $parameters); }
Build the signature base string. @param \Psr\Http\Message\UriInterface|string $uri @param array $parameters @param string $httpMethod @return string
entailment
public function getBaseStringBuilder() { if ($this->baseStringBuilder instanceof BaseStringBuilderInterface) { return $this->baseStringBuilder; } return $this->baseStringBuilder = new BaseStringBuilder(new UriParser()); }
Get the BaseStringBuilder instance. @return \Risan\OAuth1\Signature\BaseStringBuilderInterface
entailment
public function createForTemporaryCredentials() { return $this->create('POST', (string) $this->getConfig()->getTemporaryCredentialsUri(), [ 'headers' => [ 'Authorization' => $this->authorizationHeader->forTemporaryCredentials(), ], ]); }
{@inheritdoc}
entailment
public function buildAuthorizationUri(TemporaryCredentials $temporaryCredentials) { return $this->uriParser->appendQueryParameters( $this->getConfig()->getAuthorizationUri(), ['oauth_token' => $temporaryCredentials->getIdentifier()] ); }
{@inheritdoc}
entailment
public function createForTokenCredentials(TemporaryCredentials $temporaryCredentials, $verificationCode) { return $this->create('POST', (string) $this->getConfig()->getTokenCredentialsUri(), [ 'headers' => [ 'Authorization' => $this->authorizationHeader->forTokenCredentials($temporaryCredentials, $verificationCode), ], 'form_params' => [ 'oauth_verifier' => $verificationCode, ], ]); }
{@inheritdoc}
entailment
public function createForProtectedResource(TokenCredentials $tokenCredentials, $method, $uri, array $options = []) { return $this->create($method, (string) $this->getConfig()->buildUri($uri), array_replace_recursive([ 'headers' => [ 'Authorization' => $this->authorizationHeader->forProtectedResource($tokenCredentials, $method, $uri, $options), ], ], $options)); }
{@inheritdoc}
entailment
public function sign($uri, array $parameters = [], $httpMethod = 'POST') { $baseString = $this->buildBaseString($uri, $parameters, $httpMethod); return base64_encode($this->hash($baseString)); }
{@inheritdoc}
entailment
public function setFrom($from) { $recipients = $this->normalizeRecipients($from); //see RFC2822 3.6.2 'Originator fields' - multiple 'From' is allowed... foreach ($recipients as $email => $name) { $this->mailer->adapter->setFrom($email, $name); //...but anyway PHPMailer consideres it should be single 'From', so we stop processing array break; } return $this; }
Sets the message sender. @param string|array $from sender email address. You may pass an array of addresses if this message is from multiple people. You may also specify sender name in addition to email address using format: `[email => name]`. @return static self reference.
entailment
public function setTo($to) { $recipients = $this->normalizeRecipients($to); foreach ($recipients as $email => $name) { $this->mailer->adapter->addAddress($email, $name); } return $this; }
Sets the message recipient(s). @param string|array $to receiver email address. You may pass an array of addresses if multiple recipients should receive this message. You may also specify receiver name in addition to email address using format: `[email => name]`. @return static self reference.
entailment
public function setReplyTo($replyTo) { $recipients = $this->normalizeRecipients($replyTo); foreach ($recipients as $email => $name) { $this->mailer->adapter->addReplyTo($email, $name); } return $this; }
Sets the reply-to address of this message. @param string|array $replyTo the reply-to address. You may pass an array of addresses if this message should be replied to multiple people. You may also specify reply-to name in addition to email address using format: `[email => name]`. @return static self reference.
entailment
public function setCc($cc) { $recipients = $this->normalizeRecipients($cc); foreach ($recipients as $email => $name) { $this->mailer->adapter->addCC($email, $name); } return $this; }
Sets the Cc (additional copy receiver) addresses of this message. @param string|array $cc copy receiver email address. You may pass an array of addresses if multiple recipients should receive this message. You may also specify receiver name in addition to email address using format: `[email => name]`. @return static self reference.
entailment
public function setBcc($bcc) { $recipients = $this->normalizeRecipients($bcc); foreach ($recipients as $email => $name) { $this->mailer->adapter->addBCC($email, $name); } return $this; }
Sets the Bcc (hidden copy receiver) addresses of this message. @param string|array $bcc hidden copy receiver email address. You may pass an array of addresses if multiple recipients should receive this message. You may also specify receiver name in addition to email address using format: `[email => name]`. @return static self reference.
entailment
public function setHtmlBody($input) { if (array_key_exists('ishtml', $this->mailer->config) && $this->mailer->config['ishtml'] === false || (empty($this->mailer->htmlView) && empty($this->mailer->htmlLayout)) ) { //prevent sending html messages if it is explicitly denied in application config or no view and layout is set $this->setTextBody($input); } else { if (preg_match('|<body[^>]*>(.*?)</body>|is', $input) != 1) { //html was not already rendered by view - lets do it if (empty($this->mailer->htmlView)) { $html = $this->mailer->render($this->mailer->htmlLayout, ['content' => $input, 'message' => $this], false); } else { //The most simple case is supposed here - your html view file should use '$text' variable $html = $this->mailer->render($this->mailer->htmlView, ['text' => $input, 'message' => $this], $this->mailer->htmlLayout); } } else { $html = $input; } //TODO: check usage and default behavior of '$basedir' argument (used for images) $this->mailer->adapter->msgHTML($html, $basedir = '', true); } return $this; }
Sets message HTML content. @param string $input message HTML content. @return static self reference. Note: PHPMailer autocreates both html-body and alt-body (and normalizes text for alt-body), so we need not to set additionally text body to create 'multipart/alternative' content-type. We also try to make possible to call [[setHtmlBody()]] from elsewhere, not only from [[compose()]], for simple cases, when we have no params to pass to the view to build html, just text. Another usecase is when you don't want to render views and layouts and build html message on-the-fly. Othervise you do everything via Mailer [[compose()]] function, passing params their.
entailment
public function attach($path, array $options = []) { $name = isset($options['fileName']) ? $options['fileName'] : ''; $type = isset($options['contentType']) ? $options['contentType'] : ''; $encoding = isset($options['encoding']) ? $options['encoding'] : 'base64'; $disposition = isset($options['disposition']) ? $options['disposition'] : 'attachment'; $this->mailer->adapter->addAttachment(\Yii::getAlias($path, false), $name, $encoding, $type, $disposition); return $this; }
Attaches existing file to the email message. @param string $path full file name or path alias @param array $options options for embed file. Valid options are: - fileName: name, which should be used to attach file. - contentType: attached file MIME type. @return static self reference.
entailment
public function attachContent($content, array $options = []) { $filename = isset($options['fileName']) ? $options['fileName'] : (md5(uniqid('', true)) . '.txt'); //fallback $type = isset($options['contentType']) ? $options['contentType'] : ''; $encoding = isset($options['encoding']) ? $options['encoding'] : 'base64'; $disposition = isset($options['disposition']) ? $options['disposition'] : 'attachment'; $this->mailer->adapter->addStringAttachment($content, $filename, $encoding, $type, $disposition); return $this; }
Attach specified content as file for the email message. @param string $content attachment file content. @param array $options options for embed file. Valid options are: - fileName: name, which should be used to attach file. - contentType: attached file MIME type. @return static self reference.
entailment
public function embed($path, array $options = []) { $name = isset($options['fileName']) ? $options['fileName'] : ''; $type = isset($options['contentType']) ? $options['contentType'] : ''; $encoding = isset($options['encoding']) ? $options['encoding'] : 'base64'; $disposition = isset($options['disposition']) ? $options['disposition'] : 'inline'; $cid = md5($path). '@phpmailer.0'; //RFC2392 S 2 $this->mailer->adapter->addEmbeddedImage(\Yii::getAlias($path, false), $cid, $name, $encoding, $type, $disposition); return $cid; }
Attach a file and return it's CID source. This method should be used when embedding images or other data in a message. @param string $path full file name or path alias @param array $options options for embed file. Valid options are: - fileName: name, which should be used to attach file. - contentType: attached file MIME type. @return string attachment CID.
entailment
public function embedContent($content, array $options = []) { $name = isset($options['fileName']) ? $options['fileName'] : (md5(uniqid('', true)) . '.jpg'); //fallback $type = isset($options['contentType']) ? $options['contentType'] : ''; $encoding = isset($options['encoding']) ? $options['encoding'] : 'base64'; $disposition = isset($options['disposition']) ? $options['disposition'] : 'inline'; $cid = md5($name). '@phpmailer.0'; //RFC2392 S 2 $this->mailer->adapter->addStringEmbeddedImage($content, $cid, $name, $encoding, $type, $disposition); return $cid; }
Attach a content as file and return it's CID source. This method should be used when embedding images or other data in a message. @param string $content attachment file content. @param array $options options for embed file. Valid options are: - fileName: name, which should be used to attach file. - contentType: attached file MIME type. @return string attachment CID.
entailment
private function reformatArray($source) { $result = array(); foreach ($source as $data) { $result[$data[0]] = (isset($data[1])) ? $data[1] : ''; } return $result; }
Reformat PHPMailer's recipients arrays for Yii debug purposes @param array $source @return array
entailment
private function normalizeRecipients($addr) { $recipients = array(); if (is_string($addr)) { //consider it as 'email' $recipients[$addr] = ''; } elseif (is_array($addr)) { foreach ($addr as $key => $value) { if (is_int($key)) { //consider it as numeric array of 'emails' $recipients[$value] = ''; } else { //consider it as ['email' => 'name'] pairs $recipients[$key] = $value; } } } return $recipients; }
Creates uniform recipients array for phpMailer's [[addAnAddress]] method (as 'email' => 'name' pairs), because in \yii\mail\MessageInterface by design recipients may be defined in different ways @param string|array $addr copy receiver email address. @return array
entailment
public function init() { $this->adapter = new Adapter(); if (!is_array($this->config)) { throw new InvalidConfigException('Mailer config should be set in terms of array'); } if (!empty($this->config)) { //special handling of language $this->adapter->setLanguage(ArrayHelper::remove($this->config, 'language', Yii::$app->language)); //special handling of callback (see definition of \PHPMailer::$action_function) $this->adapter->setCallback(ArrayHelper::remove($this->config, 'callback', 'zyx\phpmailer\Mailer::processResult')); //special hadling of charset. Note: PHPMailer in [[createBody()]] overrides charset and sets 'us-ascii' if no 8-bit chars are found! $this->adapter->setCharset(!empty($this->messageConfig['charset']) ? $this->messageConfig['charset'] : ArrayHelper::remove($this->config, 'charset', Yii::$app->charset)); //special handling of our 'global' isHTML switch $this->adapter->isHTML((bool)ArrayHelper::remove($this->config, 'ishtml', false)); //set other properties, compliant with PHPMailer's configuration public properties foreach (get_object_vars($this->adapter) as $prop => $value) { $key = strtolower($prop); if (array_key_exists($key, $this->config)) { $this->adapter->$prop = $this->config[$key]; } } } //Set current message date initially - a workaround for MessageDate bug in PHPMailer <= 5.2.7 //see https://github.com/PHPMailer/PHPMailer/pull/227 if (version_compare($this->adapter->getVersion(), '5.2.7', '<=') && $this->adapter->getMessageDate() == '') { $this->adapter->setMessageDate(); } }
For example, you may predefine in 'messageConfig' default contents of 'From' field: ~~~ 'mail' => [ ... 'messageConfig' => [ 'from' => ['[email protected]' => 'My Example Site'] ], ... ]; ~~~
entailment
public static function processResult($result, $to = '', $cc = '', $bcc = '', $subject = '', $body = '', $from = '') { self::$success = $result; if (YII_DEBUG) { $msg = ' - Sending email. '; //native PHPMailer's way to pass results to [[doCallback()]] function is a little bit strange $msg .= (!empty($to)) ? ('To: ' . (is_array($to) ? implode(';', $to) : $to) . '.') : ''; $msg .= (!empty($cc)) ? ('Cc: ' . (is_array($cc) ? implode(';', $cc) : $cc) . '.') : ''; $msg .= (!empty($bcc)) ? ('Bcc: ' . (is_array($bcc) ? implode(';', $bcc) : $bcc) . '.') : ''; $msg .= ' Subject: "' . $subject . '"'; if ($result) { Yii::info('OK' . $msg, __METHOD__); } else { Yii::warning('FAILED' . $msg, __METHOD__); } } }
This is a callback function to retrieve result returned by PHPMailer @var bool $result result of the send action @var string $to email address of the recipient @var string $cc cc email addresses @var string $bcc bcc email addresses @var string $subject the subject @var string $body the email body @var string $from email address of sender
entailment
public function msgText($text) { $this->isHTML(false); $text = self::html2text($text, true); $text = self::normalizeBreaks($text); $this->Body = $text; }
Sets message plain text content. @param string $text message plain text conten @return void
entailment
public function getAuthorizeUrl($api_settings = '', $callback_url = 'https://api.vk.com/blank.html', $test_mode = false) { $parameters = array( 'client_id' => $this->app_id, 'scope' => $api_settings, 'redirect_uri' => $callback_url, 'response_type' => 'code' ); if ($test_mode) $parameters['test_mode'] = 1; return $this->createUrl(self::AUTHORIZE_URL, $parameters); }
Returns authorization link with passed parameters. @param string $api_settings @param string $callback_url @param bool $test_mode @return string
entailment
public function getAccessToken($code, $callback_url = 'https://api.vk.com/blank.html') { if (!is_null($this->access_token) && $this->auth) { throw new VKException('Already authorized.'); } $parameters = array( 'client_id' => $this->app_id, 'client_secret' => $this->api_secret, 'code' => $code, 'redirect_uri' => $callback_url ); $rs = json_decode($this->request( $this->createUrl(self::ACCESS_TOKEN_URL, $parameters)), true); if (isset($rs['error'])) { throw new VKException($rs['error'] . (!isset($rs['error_description']) ?: ': ' . $rs['error_description'])); } else { $this->auth = true; $this->access_token = $rs['access_token']; return $rs; } }
Returns access token by code received on authorization link. @param string $code @param string $callback_url @throws VKException @return array
entailment
public function checkAccessToken($access_token = null) { $token = is_null($access_token) ? $this->access_token : $access_token; if (is_null($token)) return false; $rs = $this->api('getUserSettings', array('access_token' => $token)); return isset($rs['response']); }
Check for validity access token. @param string $access_token @return bool
entailment
public function api($method, $parameters = array(), $format = 'array', $requestMethod = 'get') { $parameters['timestamp'] = time(); $parameters['api_id'] = $this->app_id; $parameters['random'] = rand(0, 10000); if (!array_key_exists('access_token', $parameters) && !is_null($this->access_token)) { $parameters['access_token'] = $this->access_token; } if (!array_key_exists('v', $parameters) && !is_null($this->api_version)) { $parameters['v'] = $this->api_version; } ksort($parameters); $sig = ''; foreach ($parameters as $key => $value) { $sig .= $key . '=' . $value; } $sig .= $this->api_secret; $parameters['sig'] = md5($sig); if ($method == 'execute' || $requestMethod == 'post') { $rs = $this->request( $this->getApiUrl($method, $format == 'array' ? 'json' : $format), "POST", $parameters); } else { $rs = $this->request($this->createUrl( $this->getApiUrl($method, $format == 'array' ? 'json' : $format), $parameters)); } return $format == 'array' ? json_decode($rs, true) : $rs; }
Execute API method with parameters and return result. @param string $method @param array $parameters @param string $format @param string $requestMethod @return mixed
entailment
private function request($url, $method = 'GET', $postfields = array()) { curl_setopt_array($this->ch, array( CURLOPT_USERAGENT => 'VK/1.0 (+https://github.com/vladkens/VK))', CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_POST => ($method == 'POST'), CURLOPT_POSTFIELDS => $postfields, CURLOPT_URL => $url )); return curl_exec($this->ch); }
Executes request on link. @param string $url @param string $method @param array $postfields @return string
entailment
public function beforeValidate() { if ($this->owner->{$this->attribute} instanceof UploadedFile) { $this->file = $this->owner->{$this->attribute}; return; } $this->file = UploadedFile::getInstance($this->owner, $this->attribute); if (empty($this->file)) { $this->file = UploadedFile::getInstanceByName($this->attribute); } if ($this->file instanceof UploadedFile) { $this->owner->{$this->attribute} = $this->file; } }
Before validate event.
entailment
public function beforeSave() { if ($this->file instanceof UploadedFile) { if (true !== $this->owner->isNewRecord) { /** @var ActiveRecord $oldModel */ $oldModel = $this->owner->findOne($this->owner->primaryKey); $behavior = static::getInstance($oldModel, $this->attribute); $behavior->cleanFiles(); } $this->owner->{$this->attribute} = implode('.', array_filter([$this->file->baseName, $this->file->extension]) ); } else { if (true !== $this->owner->isNewRecord && empty($this->owner->{$this->attribute})) { $this->owner->{$this->attribute} = ArrayHelper::getValue($this->owner->oldAttributes, $this->attribute, null); } } }
Before save event. @throws \yii\base\InvalidConfigException
entailment
public static function getInstance(Model $model, $attribute) { foreach ($model->behaviors as $behavior) { if ($behavior instanceof self && $behavior->attribute == $attribute) { return $behavior; } } throw new InvalidCallException('Missing behavior for attribute ' . VarDumper::dumpAsString($attribute)); }
Returns behavior instance for specified object and attribute @param Model $model @param string $attribute @return static
entailment
public function resolvePath($path) { $path = Yii::getAlias($path); $pi = pathinfo($this->owner->{$this->attribute}); $fileName = ArrayHelper::getValue($pi, 'filename'); $extension = strtolower(ArrayHelper::getValue($pi, 'extension')); return preg_replace_callback('|\[\[([\w\_/]+)\]\]|', function ($matches) use ($fileName, $extension) { $name = $matches[1]; switch ($name) { case 'extension': return $extension; case 'filename': return $fileName; case 'basename': return implode('.', array_filter([$fileName, $extension])); case 'app_root': return Yii::getAlias('@app'); case 'web_root': return Yii::getAlias('@webroot'); case 'base_url': return Yii::getAlias('@web'); case 'model': $r = new \ReflectionClass($this->owner->className()); return lcfirst($r->getShortName()); case 'attribute': return lcfirst($this->attribute); case 'id': case 'pk': $pk = implode('_', $this->owner->getPrimaryKey(true)); return lcfirst($pk); case 'id_path': return static::makeIdPath($this->owner->getPrimaryKey()); case 'parent_id': return $this->owner->{$this->parentRelationAttribute}; } if (preg_match('|^attribute_(\w+)$|', $name, $am)) { $attribute = $am[1]; return $this->owner->{$attribute}; } if (preg_match('|^md5_attribute_(\w+)$|', $name, $am)) { $attribute = $am[1]; return md5($this->owner->{$attribute}); } return '[[' . $name . ']]'; }, $path); }
Replaces all placeholders in path variable with corresponding values @param string $path @return string
entailment
public function afterSave() { if ($this->file instanceof UploadedFile !== true) { return; } $path = $this->getUploadedFilePath($this->attribute); FileHelper::createDirectory(pathinfo($path, PATHINFO_DIRNAME), 0775, true); if (!$this->file->saveAs($path)) { throw new FileUploadException($this->file->error, 'File saving error.'); } $this->owner->trigger(static::EVENT_AFTER_FILE_SAVE); }
After save event.
entailment
public function getUploadedFilePath($attribute) { $behavior = static::getInstance($this->owner, $attribute); if (!$this->owner->{$attribute}) { return ''; } return $behavior->resolvePath($behavior->filePath); }
Returns file path for attribute. @param string $attribute @return string
entailment
public function getUploadedFileUrl($attribute) { if (!$this->owner->{$attribute}) { return null; } $behavior = static::getInstance($this->owner, $attribute); return $behavior->resolvePath($behavior->fileUrl); }
Returns file url for the attribute. @param string $attribute @return string|null
entailment
public function resolveProfilePath($path, $profile) { $path = $this->resolvePath($path); return preg_replace_callback('|\[\[([\w\_/]+)\]\]|', function ($matches) use ($profile) { $name = $matches[1]; switch ($name) { case 'profile': return $profile; } return '[[' . $name . ']]'; }, $path); }
Resolves profile path for thumbnail profile. @param string $path @param string $profile @return string
entailment
public function createThumbs() { $path = $this->getUploadedFilePath($this->attribute); foreach ($this->thumbs as $profile => $config) { $thumbPath = static::getThumbFilePath($this->attribute, $profile); if (is_file($path) && !is_file($thumbPath)) { // setup image processor function if (isset($config['processor']) && is_callable($config['processor'])) { $processor = $config['processor']; unset($config['processor']); } else { $processor = function (GD $thumb) use ($config) { $thumb->adaptiveResize($config['width'], $config['height']); }; } $thumb = new GD($path, $config); call_user_func($processor, $thumb, $this->attribute); FileHelper::createDirectory(pathinfo($thumbPath, PATHINFO_DIRNAME), 0775, true); $thumb->save($thumbPath); } } }
Creates image thumbnails
entailment
public function doesStringEndWith(string $string, string $test): bool { $strlen = strlen($string); $testlen = strlen($test); if ($testlen > $strlen) { return false; } return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0; }
From https://stackoverflow.com/questions/619610/whats-the-most-efficient-test-of-whether-a-php-string-ends-with-another-string
entailment
private function replace(array $data): string { $widget = explode(':', $data[1]); if (class_exists($class = $widget[0]) && method_exists($class, $method = $widget[1])) { return call_user_func([$class, $method]); } return ''; }
Replaces widget short code on appropriate widget @param $data @return string
entailment
public function search(array $params): ActiveDataProvider { $query = CmsModel::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => $this->pageSize, ], ]); $dataProvider->setSort([ 'defaultOrder' => ['id' => SORT_DESC], ]); $this->load($params); if (!$this->validate()) { return $dataProvider; } $query->andFilterWhere(['id' => $this->id]); $query->andFilterWhere(['status' => $this->status]); $query->andFilterWhere(['comment_available' => $this->comment_available]); $query->andFilterWhere(['like', 'url', $this->url]); $query->andFilterWhere(['like', 'title', $this->title]); return $dataProvider; }
Creates data provider instance with search query applied @param $params @return ActiveDataProvider
entailment
public function actionIndex() { $searchModel = Yii::createObject($this->searchClass); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render($this->indexView, [ 'dataProvider' => $dataProvider, 'searchModel' => $searchModel, ]); }
List of all cms models. @return mixed
entailment
public function actionCreate() { $model = Yii::createObject($this->modelClass); if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->session->setFlash('success', Yii::t('yii2mod.cms', 'Page has been created.')); return $this->redirect(['index']); } return $this->render($this->createView, [ 'model' => $model, ]); }
Creates a new CmsModel. If creation is successful, the browser will be redirected to the 'index' page. @return mixed
entailment
public function actionUploadImage(): Response { $model = Yii::createObject($this->attachmentModelClass); $model->file = UploadedFile::getInstanceByName('file'); if (!$model->save()) { throw new UnprocessableEntityHttpException($model->getFirstError('file')); } return $this->asJson([ 'link' => $model->getFileUrl('origin'), ]); }
Upload an image @return Response @throws UnprocessableEntityHttpException
entailment
public function actionDeleteImage(): Response { $model = $this->findModel($this->attachmentModelClass, Yii::$app->request->post('id')); $model->delete(); return $this->asJson([ 'status' => 'success', ]); }
Delete the image @return Response @throws UnprocessableEntityHttpException
entailment
public function actionImages(): Response { $result = []; foreach (AttachmentModel::find()->each() as $attachment) { $result[] = [ 'id' => $attachment->id, 'url' => $attachment->getFileUrl('origin'), 'thumb' => $attachment->getFileUrl('thumbnail'), ]; } return $this->asJson($result); }
Return list of all images @return Response
entailment
protected function findModel($modelClass, $condition) { if (($model = $modelClass::findOne($condition)) !== null) { return $model; } else { throw new NotFoundHttpException(Yii::t('yii2mod.cms', 'The requested page does not exist.')); } }
Finds the model based on its primary key value. If the model is not found, a 404 HTTP exception will be thrown. @param string|ActiveRecord $modelClass @param $condition @return ActiveRecord the loaded model @throws NotFoundHttpException if the model cannot be found
entailment
public function run() { $model = $this->findModel(); $model->content = $this->parseBaseTemplateParams($model->content); return $this->controller->render($this->view, [ 'model' => $model, 'commentWidgetParams' => $this->commentWidgetParams, ]); }
Run action @throws \yii\web\NotFoundHttpException @return string
entailment
protected function parseBaseTemplateParams(string $pageContent) { $params = $this->getBaseTemplateParams(); $p = []; foreach ($params as $name => $value) { $p['{' . $name . '}'] = $value; } return strtr($pageContent, $p); }
Parse base template params, like {homeUrl} @param $pageContent @return string
entailment
protected function getBaseTemplateParams() { return ArrayHelper::merge($this->baseTemplateParams, [ 'homeUrl' => Yii::$app->urlManager->baseUrl, 'siteName' => Yii::$app->name, ]); }
Return base template params If one of this params exist in page content, it will be parsed @return array
entailment
protected function findModel(): CmsModel { if (($model = CmsModel::findOne($this->pageId)) !== null) { return $model; } throw new NotFoundHttpException(Yii::t('yii2mod.cms', 'The requested page does not exist.')); }
Find CmsModel @return CmsModel @throws NotFoundHttpException
entailment
public function parseRequest($manager, $request) { $pathInfo = $request->getPathInfo(); $url = preg_replace('#/$#', '', $pathInfo); $page = (new CmsModel())->findPage($url); if (!empty($page)) { $params['pageAlias'] = $url; $params['pageId'] = $page->id; return [$this->route, $params]; } return parent::parseRequest($manager, $request); }
Parse request @param \yii\web\UrlManager $manager @param \yii\web\Request $request @return array|bool
entailment
public function init() { if ($this->form->enableClientScript === true && $this->form->enableClientValidation === true) { Html::addCssClass($this->inputOptions, ['inputValidation' => 'validate']); } if ($this->model->hasErrors()) { Html::addCssClass($this->inputOptions, $this->form->errorCssClass); } if ($this->showCharacterCounter === true) { $this->inputOptions['showCharacterCounter'] = true; } }
Initializes the widget.
entailment
protected function initAutoComplete(&$options = []) { $autocomplete = ArrayHelper::getValue($options, 'autocomplete', []); // not Materialize autocomplete structure if (!is_array($autocomplete) || empty($autocomplete)) { return; } ArrayHelper::remove($options, 'autocomplete'); $view = $this->form->getView(); Html::addCssClass($options, ['autocomplete' => 'has-autocomplete']); MaterializePluginAsset::register($view); $autocompleteData['data'] = $autocomplete; $pluginOptions = Json::htmlEncode($autocompleteData); $js = "M.Autocomplete.init(document.querySelectorAll('.has-autocomplete', $pluginOptions))"; $view->registerJs($js); }
Initializes the Materialize autocomplete feature. @param array $options the tag options as name-value-pairs. To use the Materialize autocomplete feature, set the option key `autocomplete` to an array. The array keys are the strings to be matched and the values are optional image URLs. If an image URL is provided, a thumbnail is shown next to the string in the autocomplete suggestion list: ```php ... 'autocomplete' => [ 'George' => 'http://lorempixel.com/40/40/people', 'Fiona' => null // no thumbnail ], ... ``` To use the HTML5 autocomplete feature, set this option to `on`. To explicitely disable the HTML5 autocomplete, set this option to `off`. Either `on` or `off` disables the Materialize autocomplete feature. @see https://materializecss.com/autocomplete.html
entailment
protected function initCharacterCounter(&$options = []) { $showCharacterCounter = ArrayHelper::getValue($options, 'showCharacterCounter', false); if ($showCharacterCounter) { Html::addCssClass($this->inputOptions, ['character-counter' => 'has-character-counter']); $js = "M.CharacterCounter.init(document.querySelectorAll('.has-character-counter'))"; $view = $this->form->getView(); $view->registerJs($js); } }
Initializes the Materialize character counter feature. @param array $options the tag options as name-value-pairs. @see https://materializecss.com/text-inputs.html#character-counter
entailment
public function icon() { if ($this->icon === null) { $this->parts['{icon}'] = ''; return $this; } $this->parts['{icon}'] = Icon::widget([ 'name' => ArrayHelper::getValue($this->icon, 'name', null), 'position' => 'prefix', 'options' => ArrayHelper::getValue($this->icon, 'options', []) ]); return $this; }
Renders an icon. @return ActiveField the field itself. @throws \Exception
entailment
public function checkbox($options = [], $enclosedByLabel = true) { Html::addCssClass($this->options, ['class' => 'checkbox']); Html::removeCssClass($this->options, 'input-field'); $this->parts['{input}'] = Html::activeCheckbox($this->model, $this->attribute, $options); $this->parts['{label}'] = ''; if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) { $this->addErrorClassIfNeeded($options); } $this->addAriaAttributes($options); $this->adjustLabelFor($options); return $this; }
Renders a checkbox. @param array $options the tag options in terms of name-value pairs. See parent class for more details. @param bool $enclosedByLabel whether to enclose the checkbox within the label. This defaults to `false` as it is Materialize standard to not wrap the checkboxes in labels. @return $this
entailment
public function checkboxList($items, $options = []) { $this->template = "{icon}\n{label}\n{input}\n{hint}\n{error}"; if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) { $this->addErrorClassIfNeeded($options); } Html::addCssClass($this->labelOptions, ['checkboxlist-label' => 'label-checkbox-list']); $this->addAriaAttributes($options); $this->parts['{input}'] = Html::activeCheckboxList($this->model, $this->attribute, $items, $options); return $this; }
Renders a list of checkboxes. A checkbox list allows multiple selections. As a result, the corresponding submitted value is an array. The selection of the checkbox list is taken from the value of the model attribute. @param array $items the data item used to generate the checkboxes. The array values are the labels, while the array keys are the corresponding checkbox values. @param array $options options (name => config) for the checkbox list. For the list of available options please refer to the `$options` parameter of [[\macgyer\yii2materializecss\lib\Html::activeCheckboxList()]]. @return $this the field object itself.
entailment
public function colorInput($options = []) { Html::addCssClass($options, ['input' => 'color']); $this->initAutoComplete($options); return parent::input('color', $options); }
Renders a color input. @param array $options the tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [\yii\helpers\BaseHtml::encode()](http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#encode()-detail). The following special options are recognized: - autocomplete: string|array, see [[initAutoComplete()]] for details. @return ActiveField the field itself.
entailment
public function dateInput($options = []) { Html::addCssClass($options, ['input' => 'date']); $this->initAutoComplete($options); return parent::input('date', $options); }
Renders a date input. @param array $options the tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [\yii\helpers\BaseHtml::encode()](http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#encode()-detail). The following special options are recognized: - autocomplete: string|array, see [[initAutoComplete()]] for details. @return ActiveField the field itself.
entailment
public function datetimeInput($options = []) { Html::addCssClass($options, ['input' => 'datetime']); $this->initAutoComplete($options); return parent::input('datetime', $options); }
Renders a datetime input. @param array $options the tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [\yii\helpers\BaseHtml::encode()](http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#encode()-detail). The following special options are recognized: - autocomplete: string|array, see [[initAutoComplete()]] for details. @return ActiveField the field itself.
entailment
public function datetimeLocalInput($options = []) { Html::addCssClass($options, ['input' => 'datetime-local']); $this->initAutoComplete($options); return parent::input('datetime-local', $options); }
Renders a datetime local input. @param array $options the tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [\yii\helpers\BaseHtml::encode()](http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#encode()-detail). The following special options are recognized: - autocomplete: string|array, see [[initAutoComplete()]] for details. @return ActiveField the field itself.
entailment
public function dropDownList($items, $options = []) { $view = $this->form->view; MaterializePluginAsset::register($view); $id = $this->getInputId(); $js = "M.FormSelect.init(document.querySelector('#$id'))"; $view->registerJs($js); return parent::dropDownList($items, $options); }
Renders a drop-down list. @param array $items the option data items @param array $options the tag options in terms of name-value pairs. @return $this the field object itself. @see http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#dropDownList()-detail
entailment
public function emailInput($options = []) { Html::addCssClass($options, ['input' => 'email']); $this->initAutoComplete($options); return parent::input('email', $options); }
Renders an email input. @param array $options the tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [\yii\helpers\BaseHtml::encode()](http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#encode()-detail). The following special options are recognized: - autocomplete: string|array, see [[initAutoComplete()]] for details. @return ActiveField the field itself.
entailment
public function monthInput($options = []) { Html::addCssClass($options, ['input' => 'month']); $this->initAutoComplete($options); return parent::input('month', $options); }
Renders a month input. @param array $options the tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [\yii\helpers\BaseHtml::encode()](http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#encode()-detail). The following special options are recognized: - autocomplete: string|array, see [[initAutoComplete()]] for details. @return ActiveField the field itself.
entailment
public function numberInput($options = []) { Html::addCssClass($options, ['input' => 'number']); $this->initAutoComplete($options); return parent::input('number', $options); }
Renders a number input. @param array $options the tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [\yii\helpers\BaseHtml::encode()](http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#encode()-detail). The following special options are recognized: - autocomplete: string|array, see [[initAutoComplete()]] for details. @return ActiveField the field itself.
entailment