sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function loadFiles(array $files, $type = 'yaml')
{
$set = $this->createFixtureSet();
foreach ($files as $file) {
$set->addFile($file, $type);
}
$set->setDoPersist(false);
return $this->load($set);
}
|
Loads entites from file, does _not_ persist them.
@param array $files
@param string $type
@return array
|
entailment
|
public function load(FixtureSet $set, array $initialReferences = array())
{
$loaders = $this->createNeededLoaders($set);
// Objects are the loaded entities without "local".
$objects = array();
// References contain, _all_ objects loaded. Needed only for loading.
$references = $initialReferences;
// Load each file
foreach ($set->getFiles() as $file) {
// Use seed before each loading, so results will be more predictable.
$this->initSeedFromSet($set);
$loader = $loaders[$file['type']];
$loader->setReferences($references);
$this->logDebug(sprintf('Loading file: %s ...', $file['path']));
$newObjects = $loader->load($file['path']);
$references = $loader->getReferences();
$this->logDebug("Loaded ".count($newObjects)." file '" . $file['path'] . "'.");
$objects = array_merge($objects, $newObjects);
}
if ($set->getDoPersist()) {
$this->persist($objects, $set->getDoDrop());
$this->logDebug("Persisted " . count($objects) . " loaded objects.");
}
return $objects;
}
|
{@inheritDoc}
|
entailment
|
public function persist(array $entities, $drop = false)
{
if ($drop) {
$this->recreateSchema();
}
$this->persistObjects($this->getORM(), $entities);
}
|
{@inheritDoc}
|
entailment
|
public function addProcessor(ProcessorInterface $processor)
{
$this->processors[] = $processor;
$this->logDebug('Added processor: ' . get_class($processor));
}
|
Adds a processor for processing a entity before and after persisting.
@param ProcessorInterface $processor
|
entailment
|
public function addProvider($provider)
{
$this->providers[] = $provider;
$this->providers = array_unique($this->providers, SORT_REGULAR);
$this->logDebug('Added provider: ' . get_class($provider));
}
|
Adds a provider for Faker.
@param $provider
|
entailment
|
protected function configureLoader(LoaderInterface $loader)
{
if ($loader instanceof Base) {
$loader->setORM($this->getORM());
if ($this->logger) {
$loader->setLogger($this->logger);
}
}
if (is_callable(array($loader, 'addProvider'))) { // new in Alice 1.7.2
$loader->addProvider($this->providers);
} else { // BC path
$loader->setProviders($this->providers);
}
}
|
Sets all needed options and dependencies to a loader.
@param LoaderInterface $loader
|
entailment
|
protected function initSeedFromSet(FixtureSet $set)
{
if (is_numeric($set->getSeed())) {
mt_srand($set->getSeed());
$this->logDebug('Initialized with seed ' . $set->getSeed());
} else {
mt_srand();
$this->logDebug('Initialized with random seed');
}
}
|
Initializes the seed for random numbers, given by a fixture set.
|
entailment
|
protected function recreateSchema()
{
$schemaTool = $this->getSchemaTool();
$schemaTool->dropSchema();
$schemaTool->createSchema();
$this->logDebug('Recreated Schema');
}
|
Will drop and create the current ORM Schema.
|
entailment
|
protected function persistObjects(ORMInterface $persister, array $objects)
{
foreach ($this->processors as $proc) {
foreach ($objects as $obj) {
$proc->preProcess($obj);
}
}
$persister->persist($objects);
foreach ($this->processors as $proc) {
foreach ($objects as $obj) {
$proc->postProcess($obj);
}
}
}
|
Persists given objects using ORM persister, and calls registered processors.
@param ORMInterface $persister
@param $objects
|
entailment
|
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('h4cc_alice_fixtures');
$rootNode
->info('Global configuration, can be changed by each FixtureSet on its own.')
->beforeNormalization()
->ifTrue(function ($v) { return is_array($v) && !array_key_exists('managers', $v) && !array_key_exists('manager', $v); })
->then(function ($v) {
// Key that should not be rewritten to the manager config
$excludedKeys = array('default_manager' => true);
$manager = array();
foreach ($v as $key => $value) {
if (isset($excludedKeys[$key])) {
continue;
}
$manager[$key] = $v[$key];
unset($v[$key]);
}
$v['default_manager'] = isset($v['default_manager']) ? (string) $v['default_manager'] : 'default';
$v['managers'] = array($v['default_manager'] => $manager);
return $v;
})
->end()
->children()
->scalarNode('default_manager')->end()
->end()
->fixXmlConfig('manager')
->append($this->getManagersNode())
->end()
;
return $treeBuilder;
}
|
{@inheritDoc}
|
entailment
|
public function getLoader($type, $locale)
{
switch ($type) {
case 'yaml':
return $this->newLoaderYaml($locale);
case 'php':
return $this->newLoaderPHP($locale);
}
throw new \InvalidArgumentException("Unknown loader type '$type'.");
}
|
Returns a loader for a specific type and locale.
@param $type
@param $locale
@return BaseLoader|YamlLoader
@throws \InvalidArgumentException
|
entailment
|
public function dropSchema()
{
$this->foreachObjectManagers(function(DocumentManager $objectManager) {
$schemaManager = $objectManager->getSchemaManager();
$schemaManager->deleteIndexes();
$schemaManager->dropCollections();
// NOT Dropping Databases, because of potential permission problems.
// (After dropping your own database, only a admin can recreate it.)
//$schemaManager->dropDatabases();
});
}
|
{@inheritDoc}
|
entailment
|
public function createSchema()
{
$this->foreachObjectManagers(function(DocumentManager $objectManager) {
$schemaManager = $objectManager->getSchemaManager();
// We assume, that the database already exists and we have permissions for it.
$schemaManager->createCollections();
$schemaManager->ensureIndexes();
});
}
|
{@inheritDoc}
|
entailment
|
public function dropSchema()
{
$this->foreachObjectManagers(function(ObjectManager $objectManager) {
$schemaTool = new DoctrineSchemaTool($objectManager);
$schemaTool->dropDatabase();
});
}
|
{@inheritDoc}
|
entailment
|
public function createSchema()
{
$this->foreachObjectManagers(function(ObjectManager $objectManager) {
$metadata = $objectManager->getMetadataFactory()->getAllMetadata();
$schemaTool = new DoctrineSchemaTool($objectManager);
$schemaTool->createSchema($metadata);
});
}
|
{@inheritDoc}
|
entailment
|
public function persist(array $objects)
{
foreach ($objects as $object) {
$manager = $this->getManagerFor($object);
$this->managersToFlush->attach($manager);
$manager->persist($object);
}
$this->flush();
}
|
{@inheritDoc}
|
entailment
|
public function find($class, $id)
{
$entity = $this->getManagerFor($class)->find($class, $id);
if (!$entity) {
throw new \UnexpectedValueException('Entity with Id ' . $id . ' and Class ' . $class . ' not found');
}
return $entity;
}
|
{@inheritDoc}
|
entailment
|
public function remove(array $objects)
{
$objects = $this->merge($objects);
foreach ($objects as $object) {
$manager = $this->getManagerFor($object);
$this->managersToFlush->attach($manager);
$manager->remove($object);
}
$this->flush();
}
|
{@inheritDoc}
|
entailment
|
public function merge(array $objects)
{
$mergedObjects = array();
foreach($objects as $object) {
$mergedObjects[] = $this->getManagerFor($object)->merge($object);
}
return $mergedObjects;
}
|
{@inheritDoc}
|
entailment
|
public function detach(array $objects)
{
foreach ($objects as $object) {
$this->getManagerFor($object)->detach($object);
}
}
|
{@inheritDoc}
|
entailment
|
private function getSchemaToolServiceIdForCurrentConfig(array $currentManagerConfig, ContainerBuilder $container)
{
// If there is a schema_tool configured, use it.
if(!empty($currentManagerConfig['schema_tool'])) {
return $currentManagerConfig['schema_tool'];
}
$serviceId = sprintf(
'h4cc_alice_fixtures.orm.schema_tool.%s',
$this->getCleanDoctrineConfigName($currentManagerConfig['doctrine'])
);
if (!$container->has($serviceId)) {
$schemaToolDefinition = new Definition();
$schemaToolDefinition->setClass($this->getSchemaToolClass($currentManagerConfig['doctrine']));
$schemaToolDefinition->setArguments(array(
new Reference($this->getCleanDoctrineConfigName($currentManagerConfig['doctrine']))
));
$container->setDefinition($serviceId, $schemaToolDefinition);
}
return $serviceId;
}
|
Will return the configured schema_tool service id,
or will define a default one lazy and return its id.
@param array $currentManagerConfig
@param ContainerBuilder $container
@return string
|
entailment
|
protected function findSetsByDefaultNaming() {
// Get all existing paths from bundles.
$paths = array();
/** @var $bundle \Symfony\Component\HttpKernel\Bundle\BundleInterface */
foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) {
if(is_dir($path = $bundle->getPath().'/DataFixtures/Alice')) {
$paths[] = $path;
}
}
if(!$paths) {
return array();
}
// Find all Sets in these paths.
$finder = new Finder();
$finder->files()->name('*Set.php')->in($paths);
// Return paths to sets.
return array_keys(iterator_to_array($finder));
}
|
Returns a list of all *Bundle/DataFixtures/Alice/*Set.php files.
@return string[]
|
entailment
|
public function recognize($filename, array $languages = null, $pageSegMode = self::PAGE_SEG_MODE_AUTOMATIC_OCR)
{
if ($pageSegMode < 0 || $pageSegMode > 10) {
throw new \InvalidArgumentException(
'Page seg mode must be between 0 and 10'
);
}
$tempFile = tempnam(sys_get_temp_dir(), 'tesseract');
$arguments = array(
$filename,
$tempFile,
'-psm',
$pageSegMode
);
if (null !== $languages) {
$arguments[] = '-l';
$arguments[] = implode('+', $languages);
}
$this->execute($arguments);
$recognizedText = trim(\file_get_contents($tempFile . '.txt'));
if (file_exists($tempFile)) {
unlink($tempFile);
}
if (file_exists($tempFile . '.txt')) {
unlink($tempFile . '.txt');
}
return $recognizedText;
}
|
Perform OCR on an image file
@param string $filename
@param array $languages An array of language codes
@param int $pageSegMode Page segmentation mode
@return string Text recognized from the image
|
entailment
|
protected function execute(array $arguments)
{
\array_unshift($arguments, $this->path);
$builder = ProcessBuilder::create($arguments);
$process = $builder->getProcess();
$process->run();
if (!$process->isSuccessful()) {
throw CommandException::factory($process);
}
// E.g. tesseract --version returns output as error output
return $process->getOutput() ? $process->getOutput() : $process->getErrorOutput();
}
|
Execute command and return output
@param string $parameters
@return array
@throws \RuntimeException
|
entailment
|
public function serialize($value)
{
$this->reset();
$serializedData = $this->serializeData($value);
$encoded = json_encode($serializedData, $this->calculateEncodeOptions());
if ($encoded === false || json_last_error() != JSON_ERROR_NONE) {
if (json_last_error() != JSON_ERROR_UTF8) {
throw new JsonSerializerException('Invalid data to encode to JSON. Error: ' . json_last_error());
}
$serializedData = $this->encodeNonUtf8ToUtf8($serializedData);
$encoded = json_encode($serializedData, $this->calculateEncodeOptions());
if ($encoded === false || json_last_error() != JSON_ERROR_NONE) {
throw new JsonSerializerException('Invalid data to encode to JSON. Error: ' . json_last_error());
}
}
return $this->processEncodedValue($encoded);
}
|
Serialize the value in JSON
@param mixed $value
@return string JSON encoded
@throws JsonSerializerException
|
entailment
|
public function unserialize($value)
{
$this->reset();
$data = json_decode($value, true);
if ($data === null && json_last_error() != JSON_ERROR_NONE) {
throw new JsonSerializerException('Invalid JSON to unserialize.');
}
if (mb_strpos($value, static::UTF8ENCODED_IDENTIFIER_KEY) !== false) {
$data = $this->decodeNonUtf8FromUtf8($data);
}
return $this->unserializeData($data);
}
|
Unserialize the value from JSON
@param string $value
@return mixed
|
entailment
|
public function setUnserializeUndeclaredPropertyMode($value)
{
$availableOptions = [
static::UNDECLARED_PROPERTY_MODE_SET,
static::UNDECLARED_PROPERTY_MODE_IGNORE,
static::UNDECLARED_PROPERTY_MODE_EXCEPTION
];
if (!in_array($value, $availableOptions)) {
throw new InvalidArgumentException('Invalid value.');
}
$this->undefinedAttributeMode = $value;
return $this;
}
|
Set unserialization mode for undeclared class properties
@param integer $value One of the JsonSerializer::UNDECLARED_PROPERTY_MODE_*
@return self
@throws InvalidArgumentException When the value is not one of the UNDECLARED_PROPERTY_MODE_* options
|
entailment
|
protected function serializeData($value)
{
if (is_scalar($value) || $value === null) {
if (!$this->preserveZeroFractionSupport && is_float($value) && ctype_digit((string)$value)) {
// Because the PHP bug #50224, the float numbers with no
// precision numbers are converted to integers when encoded
$value = static::FLOAT_ADAPTER . '(' . $value . '.0)';
}
return $value;
}
if (is_resource($value)) {
throw new JsonSerializerException('Resource is not supported in JsonSerializer');
}
if (is_array($value)) {
return array_map(array($this, __FUNCTION__), $value);
}
if ($value instanceof \Closure) {
if (!$this->closureSerializer) {
throw new JsonSerializerException('Closure serializer not given. Unable to serialize closure.');
}
return array(
static::CLOSURE_IDENTIFIER_KEY => true,
'value' => $this->closureSerializer->serialize($value)
);
}
return $this->serializeObject($value);
}
|
Parse the data to be json encoded
@param mixed $value
@return mixed
@throws JsonSerializerException
|
entailment
|
protected function serializeObject($value)
{
if ($this->objectStorage->contains($value)) {
return array(static::CLASS_IDENTIFIER_KEY => '@' . $this->objectStorage[$value]);
}
$this->objectStorage->attach($value, $this->objectMappingIndex++);
$ref = new ReflectionClass($value);
$className = $ref->getName();
if (array_key_exists($className, $this->customObjectSerializerMap)) {
$data = array(static::CLASS_IDENTIFIER_KEY => $className);
$data += $this->customObjectSerializerMap[$className]->serialize($value);
return $data;
}
$paramsToSerialize = $this->getObjectProperties($ref, $value);
$data = array(static::CLASS_IDENTIFIER_KEY => $className);
if ($value instanceof \SplDoublyLinkedList) {
return $data + array('value' => $value->serialize());
}
$data += array_map(array($this, 'serializeData'), $this->extractObjectData($value, $ref, $paramsToSerialize));
return $data;
}
|
Extract the data from an object
@param object $value
@return array
|
entailment
|
protected function extractObjectData($value, $ref, $properties)
{
$data = array();
foreach ($properties as $property) {
try {
$propRef = $ref->getProperty($property);
$propRef->setAccessible(true);
$data[$property] = $propRef->getValue($value);
} catch (ReflectionException $e) {
$data[$property] = $value->$property;
}
}
return $data;
}
|
Extract the object data
@param object $value
@param ReflectionClass $ref
@param array $properties
@return array
|
entailment
|
protected function unserializeData($value)
{
if (is_scalar($value) || $value === null) {
return $value;
}
if (isset($value[static::CLASS_IDENTIFIER_KEY])) {
return $this->unserializeObject($value);
}
if (!empty($value[static::CLOSURE_IDENTIFIER_KEY])) {
if (!$this->closureSerializer) {
throw new JsonSerializerException('Closure serializer not provided to unserialize closure');
}
return $this->closureSerializer->unserialize($value['value']);
}
return array_map(array($this, __FUNCTION__), $value);
}
|
Parse the json decode to convert to objects again
@param mixed $value
@return mixed
|
entailment
|
protected function unserializeObject($value)
{
$className = $value[static::CLASS_IDENTIFIER_KEY];
unset($value[static::CLASS_IDENTIFIER_KEY]);
if ($className[0] === '@') {
$index = substr($className, 1);
return $this->objectMapping[$index];
}
if (array_key_exists($className, $this->customObjectSerializerMap)) {
$obj = $this->customObjectSerializerMap[$className]->unserialize($value);
$this->objectMapping[$this->objectMappingIndex++] = $obj;
return $obj;
}
if (!class_exists($className)) {
throw new JsonSerializerException('Unable to find class ' . $className);
}
if ($className === 'DateTime') {
$obj = $this->restoreUsingUnserialize($className, $value);
$this->objectMapping[$this->objectMappingIndex++] = $obj;
return $obj;
}
if (!$this->isSplList($className)) {
$ref = new ReflectionClass($className);
$obj = $ref->newInstanceWithoutConstructor();
} else {
$obj = new $className();
}
if ($obj instanceof \SplDoublyLinkedList) {
$obj->unserialize($value['value']);
$this->objectMapping[$this->objectMappingIndex++] = $obj;
return $obj;
}
$this->objectMapping[$this->objectMappingIndex++] = $obj;
foreach ($value as $property => $propertyValue) {
try {
$propRef = $ref->getProperty($property);
$propRef->setAccessible(true);
$propRef->setValue($obj, $this->unserializeData($propertyValue));
} catch (ReflectionException $e) {
switch ($this->undefinedAttributeMode) {
case static::UNDECLARED_PROPERTY_MODE_SET:
$obj->$property = $this->unserializeData($propertyValue);
break;
case static::UNDECLARED_PROPERTY_MODE_IGNORE:
break;
case static::UNDECLARED_PROPERTY_MODE_EXCEPTION:
throw new JsonSerializerException('Undefined attribute detected during unserialization');
break;
}
}
}
if (method_exists($obj, '__wakeup')) {
$obj->__wakeup();
}
return $obj;
}
|
Convert the serialized array into an object
@param array $value
@return object
@throws JsonSerializerException
|
entailment
|
public function authenticate(TokenInterface $token)
{
if (false == $this->supports($token)) {
return null;
}
try {
$user = $this->getUser($token);
/** @var $token SamlSpToken */
return $this->createAuthenticatedToken(
$token->getSamlSpInfo(),
$token->getAttributes(),
$user instanceof UserInterface ? $user->getRoles() : array(),
$user
);
} catch (AuthenticationException $ex) {
throw $ex;
} catch (\Exception $ex) {
throw new AuthenticationServiceException($ex->getMessage(), (int) $ex->getCode(), $ex);
}
}
|
Attempts to authenticate a TokenInterface object.
@param TokenInterface $token The TokenInterface instance to authenticate
@return TokenInterface An authenticated TokenInterface instance, never null
@throws AuthenticationException if the authentication fails
|
entailment
|
public function serialize()
{
return serialize(
array(
$this->providerID,
$this->authenticationServiceName,
$this->sessionIndex,
$this->nameID,
$this->nameIDFormat,
$this->createdOn,
)
);
}
|
(PHP 5 >= 5.1.0)<br/>
String representation of object
@link http://php.net/manual/en/serializable.serialize.php
@return string the string representation of the object or null
|
entailment
|
public function unserialize($serialized)
{
$data = unserialize($serialized);
// add a few extra elements in the array to ensure that we have enough keys when unserializing
// older data which does not include all properties.
$data = array_merge($data, array_fill(0, 4, null));
list(
$this->providerID,
$this->authenticationServiceName,
$this->sessionIndex,
$this->nameID,
$this->nameIDFormat,
$this->createdOn
) = $data;
}
|
(PHP 5 >= 5.1.0)<br/>
Constructs the object
@link http://php.net/manual/en/serializable.unserialize.php
@param string $serialized <p>
The string representation of the object.
</p>
@return void
|
entailment
|
public function manage(Request $request)
{
if (false == $relyingParty = $this->findRelyingPartySupportedRequest($request)) {
throw new \InvalidArgumentException('The relying party does not support the request');
}
return $relyingParty->manage($request);
}
|
{@inheritdoc}
|
entailment
|
protected function attemptAuthentication(Request $request)
{
$myRequest = $request->duplicate();
$this->copyOptionsToRequestAttributes($myRequest);
if (!$this->getRelyingParty()->supports($myRequest)) {
return null;
}
$result = $this->getRelyingParty()->manage($myRequest);
if ($result instanceof Response) {
return $result;
}
if ($result instanceof SamlSpInfo) {
$token = new SamlSpToken($this->providerKey);
$token->setSamlSpInfo($result);
try {
return $this->authenticationManager->authenticate($token);
} catch (AuthenticationException $e) {
$e->setToken($token);
throw $e;
}
}
return null;
}
|
Performs authentication.
@param Request $request A Request instance
@throws \Exception
@throws \Symfony\Component\Security\Core\Exception\AuthenticationException
@throws \RuntimeException
@return TokenInterface|Response|null The authenticated token, null if full authentication is not possible, or a Response
|
entailment
|
public function serialize()
{
return serialize(array($this->authenticationServiceID, $this->nameID, $this->attributes, $this->authnStatement));
}
|
{@inheritdoc}
|
entailment
|
public function unserialize($serialized)
{
list($this->authenticationServiceID, $this->nameID, $this->attributes, $this->authnStatement) = unserialize($serialized);
}
|
{@inheritdoc}
|
entailment
|
protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId)
{
$providerId = 'security.authentication.provider.aerial_ship_saml_sp.'.$id;
$provider = $container
->setDefinition($providerId, new DefinitionDecorator('security.authentication.provider.aerial_ship_saml_sp'))
->replaceArgument(0, $id);
if (isset($config['provider'])) {
$adapter = new DefinitionDecorator('aerial_ship_saml_sp.user_provider_adapter');
$adapter->replaceArgument(0, new Reference($userProviderId));
$adapterID = 'aerial_ship_saml_sp.user_provider_adapter.'.$id;
$container->setDefinition($adapterID, $adapter);
$provider
->replaceArgument(1, new Reference($adapterID))
->replaceArgument(2, new Reference('security.user_checker'))
;
}
if (!isset($config['create_user_if_not_exists'])) {
$config['create_user_if_not_exists'] = false;
}
$provider->replaceArgument(3, $config['create_user_if_not_exists']);
return $providerId;
}
|
Subclasses must return the id of a service which implements the
AuthenticationProviderInterface.
@param ContainerBuilder $container
@param string $id The unique id of the firewall
@param array $config The options array for this listener
@param string $userProviderId The id of the user provider
@return string never null, the id of the authentication provider
|
entailment
|
public function subscribe($channel, callable $handler)
{
$this->consumer->subscribe([$channel]);
$isSubscriptionLoopActive = true;
while ($isSubscriptionLoopActive) {
$message = $this->consumer->consume(120 * 1000);
if ($message === null) {
continue;
}
switch ($message->err) {
case RD_KAFKA_RESP_ERR_NO_ERROR:
$payload = Utils::unserializeMessagePayload($message->payload);
if ($payload === 'unsubscribe') {
$isSubscriptionLoopActive = false;
} else {
call_user_func($handler, $payload);
}
$this->consumer->commitAsync($message);
break;
case RD_KAFKA_RESP_ERR__PARTITION_EOF:
case RD_KAFKA_RESP_ERR__TIMED_OUT:
break;
default:
throw new \Exception($message->errstr(), $message->err);
}
}
}
|
Subscribe a handler to a channel.
@param string $channel
@param callable $handler
@throws \Exception
|
entailment
|
public function publish($channel, $message)
{
$topic = $this->producer->newTopic($channel);
$topic->produce(RD_KAFKA_PARTITION_UA, 0, Utils::serializeMessage($message));
}
|
Publish a message to a channel.
@param string $channel
@param mixed $message
|
entailment
|
protected function parseProcessors(array $config): array
{
$processors = [];
if (isset($config['processors']) && is_array($config['processors'])) {
foreach ($config['processors'] as $processor) {
$processors[] = $processor;
}
}
return $processors;
}
|
Extract the processors from the given configuration.
@param array $config
@return array
|
entailment
|
public function create($streamKey)
{
$url = $this->_baseURL . "/streams";
$params['key'] = $streamKey;
$body = json_encode($params);
try {
$this->_transport->send(HttpRequest::POST, $url, $body);
} catch (\Exception $e) {
return $e;
}
return new Stream($this->_transport, $this->_hub, $streamKey);
}
|
/*
PARAM
@streamKey: 流名.
RETURN
返回一个流对象.
|
entailment
|
public function batchLiveStatus($streamKeys)
{
$url = $this->_baseURL . "/livestreams";
$params['items'] = $streamKeys;
$body = json_encode($params);
return $this->_transport->send(HttpRequest::POST, $url, $body);
}
|
/*
PARAM
@streamKeys: 流名数组, 最大长度为100.
RETURN
@items: 数组. 每个item包含一个流的直播信息.
@key: 流名.
@startAt: 直播开始的 Unix 时间戳, 0 表示当前没在直播.
@clientIP: 直播的客户端 IP.
@bps: 直播的码率.
@fps: 直播的帧率.
|
entailment
|
public function info()
{
$resp=$this->_transport->send(HttpRequest::GET, $this->_baseURL);
$ret = array();
$ret["hub"] = $this->_hub;
$ret["key"] = $this->_key;
$ret["disabledTill"] = $resp["disabledTill"];
$ret["converts"] = $resp["converts"];
return $ret;
}
|
/*
RETURN
@hub: Hub名.
@key: 流名.
@disableTill: 禁用结束的时间, 0 表示不禁用, -1 表示永久禁用.
@converts: 实时转码规格.
|
entailment
|
public function disable($till = null)
{
$url = $this->_baseURL . "/disabled";
if (empty($till)) {
$params['disabledTill'] = -1;
} else {
$params['disabledTill'] = $till;
}
$body = json_encode($params);
return $this->_transport->send(HttpRequest::POST, $url, $body);
}
|
/*
PARAM
@till: Unix 时间戳, 在这之前流均不可用.
|
entailment
|
public function enable()
{
$url = $this->_baseURL . "/disabled";
$params['disabledTill'] = 0;
$body = json_encode($params);
return $this->_transport->send(HttpRequest::POST, $url, $body);
}
|
启用一个流.
|
entailment
|
public function liveStatus()
{
$url = $this->_baseURL . "/live";
return $this->_transport->send(HttpRequest::GET, $url);
}
|
/*
RETURN
@startAt: 直播开始的 Unix 时间戳, 0 表示当前没在直播.
@clientIP: 直播的客户端 IP.
@bps: 直播的码率.
@fps: 直播的帧率.
|
entailment
|
public function historyActivity($start = null, $end = null)
{
$url = $this->_baseURL . "/historyrecord";
$flag = "?";
if (!empty($start)) {
$url = $url . $flag . "start=" . $start;
$flag = "&";
}
if (!empty($end)) {
$url = $url . $flag . "end=" . $end;
}
return $this->_transport->send(HttpRequest::GET, $url);
}
|
/*
PARAM
@start: Unix 时间戳, 限定了查询的时间范围, 0 值表示不限定, 系统会返回所有时间的直播历史.
@end: Unix 时间戳, 限定了查询的时间范围, 0 值表示不限定, 系统会返回所有时间的直播历史.
RETURN
@items: 数组. 每个item包含一次推流的开始及结束时间.
@start: Unix 时间戳, 直播开始时间.
@end: Unix 时间戳, 直播结束时间.
|
entailment
|
public function save($start = null, $end = null)
{
$url = $this->_baseURL . "/saveas";
if (!empty($start)) {
$params['start'] = $start;
}
if (!empty($end)) {
$params['end'] = $end;
}
$body = json_encode($params);
return $this->_transport->send(HttpRequest::POST, $url, $body);
}
|
/*
PARAM
@start: Unix 时间戳, 起始时间, 0 值表示不指定, 则不限制起始时间.
@end: Unix 时间戳, 结束时间, 0 值表示当前时间.
RETURN
@fname: 保存到bucket里的文件名, 由系统生成.
|
entailment
|
public function saveas($options = null)
{
$url = $this->_baseURL . "/saveas";
if (!empty($options)) {
$body = json_encode($options);
} else {
$body = null;
}
return $this->_transport->send(HttpRequest::POST, $url, $body);
}
|
/*
PARAM
@fname: 保存的文件名, 不指定会随机生成.
@start: Unix 时间戳, 起始时间, 0 值表示不指定, 则不限制起始时间.
@end: Unix 时间戳, 结束时间, 0 值表示当前时间.
@format: 保存的文件格式, 默认为m3u8.
@pipeline: dora 的私有队列, 不指定则用默认队列.
@notify: 保存成功后的回调地址.
@expireDays: 对应ts文件的过期时间.
-1 表示不修改ts文件的expire属性.
0 表示修改ts文件生命周期为永久保存.
>0 表示修改ts文件的的生命周期为ExpireDays.
RETURN
@fname: 保存到bucket里的文件名.
@persistentID: 异步模式时,持久化异步处理任务ID,通常用不到该字段.
|
entailment
|
public function updateConverts($profiles)
{
$url = $this->_baseURL . "/converts";
$params['converts'] = $profiles;
$body = json_encode($params);
return $this->_transport->send(HttpRequest::POST, $url, $body);
}
|
/*
PARAM
@profiles: 实时转码规格. array("480p", "720p")
|
entailment
|
public function createAdmin($login, $password, $roles = array())
{
$login = urlencode($login);
$data = (string) $password;
if (strlen($login) < 1) {
throw new InvalidArgumentException("Login can't be empty");
}
if (strlen($data) < 1) {
throw new InvalidArgumentException("Password can't be empty");
}
$url = '/_node/' . urlencode($this->node) . '/_config/admins/' . urlencode($login);
try {
$raw = $this->client->query(
"PUT", $url, array(), json_encode($data)
);
} catch (Exception $e) {
throw $e;
}
$resp = Couch::parseRawResponse($raw);
if ($resp['status_code'] != 200) {
throw new CouchException($raw);
}
$dsn = $this->client->dsn_part();
$dsn["user"] = $login;
$dsn["pass"] = $password;
$client = new CouchClient($this->build_url($dsn), $this->usersdb, $this->client->options());
$user = new stdClass();
$user->name = $login;
$user->type = "user";
$user->roles = $roles;
$user->_id = "org.couchdb.user:" . $login;
return $client->storeDoc($user);
}
|
Creates a new CouchDB server administrator
@param string $login administrator login
@param string $password administrator password
@param array $roles add additionnal roles to the new admin
@return stdClass CouchDB server response
@throws InvalidArgumentException|Exception|CouchException
|
entailment
|
public function deleteAdmin($login)
{
$login = urlencode($login);
if (strlen($login) < 1) {
throw new InvalidArgumentException("Login can't be empty");
}
try {
$client = new CouchClient($this->client->dsn(), $this->usersdb);
$doc = $client->getDoc("org.couchdb.user:" . $login);
$client->deleteDoc($doc);
} catch (Exception $e) {
}
$url = '/_node/' . urlencode($this->node) . '/_config/admins/' . urlencode($login);
$raw = $this->client->query(
"DELETE", $url
);
$resp = Couch::parseRawResponse($raw);
if ($resp['status_code'] != 200) {
throw new CouchException($raw);
}
return $resp["body"];
}
|
Permanently removes a CouchDB Server administrator
@param string $login administrator login
@return stdClass CouchDB server response
@throws InvalidArgumentException|CouchException
|
entailment
|
public function createUser($login, $password, $roles = array())
{
$password = (string) $password;
if (strlen($login) < 1) {
throw new InvalidArgumentException("Login can't be empty");
}
if (strlen($password) < 1) {
throw new InvalidArgumentException("Password can't be empty");
}
$user = new stdClass();
$user->salt = sha1(microtime() . mt_rand(1000000, 9999999), false);
$user->password_sha = sha1($password . $user->salt, false);
$user->name = $login;
$user->type = "user";
$user->roles = $roles;
$user->_id = "org.couchdb.user:" . $login;
$client = new CouchClient($this->client->dsn(), $this->usersdb, $this->client->options());
return $client->storeDoc($user);
}
|
create a user
@param string $login user login
@param string $password user password
@param array $roles add additionnal roles to the new user
@return stdClass CouchDB user creation response (the same as a document storage response)
@throws InvalidArgumentException
|
entailment
|
public function deleteUser($login)
{
if (strlen($login) < 1) {
throw new InvalidArgumentException("Login can't be empty");
}
$client = new CouchClient($this->client->dsn(), $this->usersdb);
$doc = $client->getDoc("org.couchdb.user:" . $login);
return $client->deleteDoc($doc);
}
|
Permanently removes a CouchDB User
@param string $login user login
@return stdClass CouchDB server response
@throws InvalidArgumentException
|
entailment
|
public function getUser($login)
{
if (strlen($login) < 1) {
throw new InvalidArgumentException("Login can't be empty");
}
$client = new CouchClient($this->client->dsn(), $this->usersdb, $this->client->options());
return $client->getDoc("org.couchdb.user:" . $login);
}
|
returns the document of a user
@param string $login login of the user to fetch
@return stdClass CouchDB document
@throws InvalidArgumentException
|
entailment
|
public function getAllUsers($include_docs = false)
{
$client = new CouchClient($this->client->dsn(), $this->usersdb, $this->client->options());
if ($include_docs) {
$client->include_docs(true);
}
return $client->startkey("org.couchdb.user:")->endkey("org.couchdb.user?")->getAllDocs()->rows;
}
|
returns all users
@param boolean $include_docs if set to true, users documents will also be included
@return array users array : each row is a stdObject with "id", "rev" and optionally "doc" properties
|
entailment
|
public function addRoleToUser($user, $role)
{
if (is_string($user)) {
$user = $this->getUser($user);
} elseif (!property_exists($user, "_id") || !property_exists($user, "roles")) {
throw new InvalidArgumentException("user parameter should be the login or a user document");
}
if (!in_array($role, $user->roles)) {
$user->roles[] = $role;
$client = clone($this->client);
$client->useDatabase($this->usersdb);
$client->storeDoc($user);
}
return true;
}
|
Add a role to a user document
@param string|stdClass $user the user login (as a string) or the user document ( fetched by getUser() method )
@param string $role the role to add in the list of roles the user belongs to
@return boolean true if the user $user now belongs to the role $role
@throws InvalidArgumentException
|
entailment
|
public function getSecurity()
{
$dbname = $this->client->getDatabaseName();
$raw = $this->client->query(
"GET", "/" . $dbname . "/_security"
);
$resp = Couch::parseRawResponse($raw);
if ($resp['status_code'] != 200) {
throw new CouchException($raw);
}
if (!property_exists($resp['body'], "admins")) {
$resp["body"]->admins = new stdClass();
$resp["body"]->admins->names = array();
$resp["body"]->admins->roles = array();
$resp["body"]->readers = new stdClass();
$resp["body"]->readers->names = array();
$resp["body"]->readers->roles = array();
}
return $resp['body'];
}
|
returns the security object of a database
@link http://wiki.apache.org/couchdb/Security_Features_Overview
@return stdClass security object of the database
@throws CouchException
|
entailment
|
public function setSecurity($security)
{
if (!is_object($security)) {
throw new InvalidArgumentException("Security should be an object");
}
$dbname = $this->client->getDatabaseName();
$raw = $this->client->query(
"PUT", "/" . $dbname . "/_security", array(), json_encode($security)
);
$resp = Couch::parseRawResponse($raw);
if ($resp['status_code'] == 200) {
return $resp['body'];
}
throw new CouchException($raw);
}
|
set the security object of a database
@link http://wiki.apache.org/couchdb/Security_Features_Overview
@param stdClass $security the security object to apply to the database
@return stdClass CouchDB server response ( { "ok": true } )
@throws InvalidArgumentException|CouchException
|
entailment
|
public function addDatabaseReaderUser($login)
{
if (strlen($login) < 1) {
throw new InvalidArgumentException("Login can't be empty");
}
$sec = $this->getSecurity();
if (in_array($login, $sec->readers->names)) {
return true;
}
array_push($sec->readers->names, $login);
$back = $this->setSecurity($sec);
if (is_object($back) && property_exists($back, "ok") && $back->ok == true) {
return true;
}
return false;
}
|
add a user to the list of readers for the current database
@param string $login user login
@return boolean true if the user has successfuly been added
@throws InvalidArgumentException
|
entailment
|
public function addDatabaseReaderRole($role)
{
if (strlen($role) < 1) {
throw new InvalidArgumentException("Role can't be empty");
}
$sec = $this->getSecurity();
if (in_array($role, $sec->readers->roles)) {
return true;
}
array_push($sec->readers->roles, $role);
$back = $this->setSecurity($sec);
if (is_object($back) && property_exists($back, "ok") && $back->ok == true) {
return true;
}
return false;
}
|
add a role to the list of readers for the current database
@param string $role role name
@return boolean true if the role has successfuly been added
@throws InvalidArgumentException
|
entailment
|
private function rmFromArray($needle, $haystack)
{
$back = array();
foreach ($haystack as $one) {
if ($one != $needle) {
$back[] = $one;
}
}
return $back;
}
|
/ /roles
|
entailment
|
final public function getFunctionName(\Twig_Node_Module $module)
{
if (null === $this->functionNamingStrategy) {
$this->functionNamingStrategy = new DefaultFunctionNamingStrategy();
}
return $this->functionNamingStrategy->getFunctionName($module);
}
|
Returns the function name for the given template name.
@param \Twig_Node_Module $templateName
@return string
|
entailment
|
public function createRoom($ownerId, $roomName = null)
{
$params['owner_id'] = $ownerId;
if (!empty($roomName)) {
$params['room_name'] = $roomName;
}
$body = json_encode($params);
try {
$ret = $this->_transport->send(HttpRequest::POST, $this->_baseURL, $body);
} catch (\Exception $e) {
return $e;
}
return $ret;
}
|
/*
ownerId: 要创建房间的所有者
roomName: 房间名称
|
entailment
|
public function getRoom($roomName)
{
$url = $this->_baseURL . '/' . $roomName;
try {
$ret = $this->_transport->send(HttpRequest::GET, $url);
} catch (\Exception $e) {
return $e;
}
return $ret;
}
|
/*
roomName: 房间名称
|
entailment
|
public function deleteRoom($roomName)
{
$url = $this->_baseURL . '/' . $roomName;
try {
$ret = $this->_transport->send(HttpRequest::DELETE, $url);
} catch (\Exception $e) {
return $e;
}
return $ret;
}
|
/*
roomName: 房间名称
|
entailment
|
public function getRoomUserNum($roomName)
{
$url = sprintf("%s/%s/users", $this->_baseURL, $roomName);
try {
$ret = $this->_transport->send(HttpRequest::GET, $url);
} catch (\Exception $e) {
return $e;
}
return $ret;
}
|
/*
获取房间的人数
roomName: 房间名称
|
entailment
|
public function kickingPlayer($roomName, $UserId)
{
$url = sprintf("%s/%s/users/%s", $this->_baseURL, $roomName, $UserId);
try {
$ret = $this->_transport->send(HttpRequest::DELETE, $url);
} catch (\Exception $e) {
return $e;
}
return $ret;
}
|
/*
踢出玩家
roomName: 房间名称
userId: 请求加入房间的用户ID
|
entailment
|
public function roomToken($roomName, $userId, $perm, $expireAt)
{
$ver = Config::getInstance()->RTCAPI_VERSION;
if ($ver === 'v2') {
$params['version']="2.0";
}
$params['room_name'] = $roomName;
$params['user_id'] = $userId;
$params['perm'] = $perm;
$params['expire_at'] = $expireAt;
$roomAccessString = json_encode($params);
$encodedRoomAccess = Utils::base64UrlEncode($roomAccessString);
$sign = hash_hmac('sha1', $encodedRoomAccess, $this->_mac->_secretKey, true);
$encodedSign = Utils::base64UrlEncode($sign);
return $this->_mac->_accessKey . ":" . $encodedSign . ":" . $encodedRoomAccess;
}
|
/*
roomName: 房间名称
userId: 请求加入房间的用户ID
perm: 该用户的房间管理权限,"admin"或"user",房间主播为"admin",拥有将其他用户移除出房间等特权。
expireAt: int64类型,鉴权的有效时间,传入秒为单位的64位Unix时间,token将在该时间后失效。
|
entailment
|
public function to($url)
{
$this->opts['source'] = $this->client->getDatabaseUri();
$this->opts['target'] = $url;
return $this->_launch();
}
|
replicate from local TO specified url (push replication)
@param string $url url of the remote couchDB server
@return object couchDB server response to replication request
|
entailment
|
public function from($url)
{
$this->opts['target'] = $this->client->getDatabaseUri();
$this->opts['source'] = $url;
return $this->_launch();
}
|
Replicate to local FROM specified url (push replication)
@param string $url url of the remote couchDB server
@return object couchDB server response to replication request
|
entailment
|
public static function http_build_query_for_curl($arrays, &$new = array(), $prefix = null)
{
if (is_object($arrays)) {
$arrays = get_object_vars($arrays);
}
foreach ($arrays as $key => $value) {
$k = isset($prefix) ? $prefix . '[' . $key . ']' : $key;
if (!$value instanceof \CURLFile and (is_array($value) or is_object($value))) {
self::http_build_query_for_curl($value, $new, $k);
} else {
$new[$k] = $value;
}
}
}
|
This function is useful for serializing multidimensional arrays, and avoid getting
the "Array to string conversion" notice
|
entailment
|
private static function encodeUrl($url)
{
$url_parsed = parse_url($url);
$scheme = $url_parsed['scheme'] . '://';
$host = $url_parsed['host'];
$port = (isset($url_parsed['port']) ? $url_parsed['port'] : null);
$path = (isset($url_parsed['path']) ? $url_parsed['path'] : null);
$query = (isset($url_parsed['query']) ? $url_parsed['query'] : null);
if ($query != null) {
$query = '?' . http_build_query(self::getArrayFromQuerystring($url_parsed['query']));
}
if ($port && $port[0] != ":") {
$port = ":" . $port;
}
$result = $scheme . $host . $port . $path . $query;
return $result;
}
|
Ensure that a URL is encoded and safe to use with cURL
@param string $url URL to encode
@return string
|
entailment
|
public static function send($httpMethod, $url, $body = null, $headers = array())
{
if ($headers == null) {
$headers = array();
}
$annexHeaders = array();
$finalHeaders = array_merge($headers, self::$defaultHeaders);
foreach ($finalHeaders as $key => $val) {
$annexHeaders[] = self::getHeader($key, $val);
}
$lowerCaseFinalHeaders = array_change_key_case($finalHeaders);
$ch = curl_init();
if ($httpMethod != self::GET) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod);
if (is_array($body) || $body instanceof Traversable) {
self::http_build_query_for_curl($body, $postBody);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
} elseif (is_array($body)) {
if (strpos($url, '?') !== false) {
$url .= "&";
} else {
$url .= "?";
}
self::http_build_query_for_curl($body, $postBody);
$url .= urldecode(http_build_query($postBody));
}
curl_setopt($ch, CURLOPT_URL, self::encodeUrl($url));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, $annexHeaders);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::$verifyPeer);
curl_setopt($ch, CURLOPT_ENCODING, ""); // If an empty string, "", is set, a header containing all supported encoding types is sent.
if (self::$socketTimeout != null) {
curl_setopt($ch, CURLOPT_TIMEOUT, self::$socketTimeout);
}
$response = curl_exec($ch);
$error = curl_error($ch);
if ($error) {
throw new \Exception($error);
}
// Split the full response in its headers and body
$curl_info = curl_getinfo($ch);
$header_size = $curl_info["header_size"];
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$httpCode = $curl_info["http_code"];
if ($httpCode != 200) {
throw new \Exception("\nhttpcode:".$httpCode."\nmessage".$body);
}
return new HttpResponse($httpCode, $body, $header);
}
|
Send a cURL request
@param string $httpMethod HTTP method to use
@param string $url URL to send the request to
@param mixed $body request body
@param array $headers additional headers to send
@throws Exception if a cURL error occurs
@return HttpResponse
|
entailment
|
private function get_headers_from_curl_response($headers)
{
$headers = explode("\r\n", $headers);
array_shift($headers);
foreach ($headers as $line) {
if (strstr($line, ': ')) {
list($key, $value) = explode(': ', $line);
$result[$key] = $value;
}
}
return $result;
}
|
Retrieve the cURL response headers from the
header string and convert it into an array
@param string $headers header string from cURL response
@return array
|
entailment
|
public static function parseRawResponse($raw_data, $json_as_array = FALSE)
{
if (!strlen($raw_data))
throw new InvalidArgumentException("no data to parse");
while (!substr_compare($raw_data, "HTTP/1.1 100 Continue\r\n\r\n", 0, 25)) {
$raw_data = substr($raw_data, 25);
}
$response = array('body' => null);
list($headers, $body) = explode("\r\n\r\n", $raw_data, 2);
$headers_array = explode("\n", $headers);
$status_line = reset($headers_array);
$status_array = explode(' ', $status_line, 3);
$response['status_code'] = trim($status_array[1]);
$response['status_message'] = trim($status_array[2]);
if (strlen($body)) {
$response['body'] = preg_match('@Content-Type:\s+application/json@i', $headers) ? json_decode($body, $json_as_array) : $body;
}
return $response;
}
|
parse a CouchDB server response and sends back an array
the array contains keys :
status_code : the HTTP status code returned by the server
status_message : the HTTP message related to the status code
body : the response body (if any). If CouchDB server response Content-Type is application/json
the body will by json_decode()d
@static
@param string $raw_data data sent back by the server
@param boolean $json_as_array is true, the json response will be decoded as an array. Is false, it's decoded as an object
@return array CouchDB response
@throws InvalidArgumentException
|
entailment
|
public static function getName($type)
{
switch ($type) {
case static::T_UNSPECIFIED:
return 'Unspecified/unknown address';
case static::T_RESERVED:
return 'Reserved/internal use only';
case static::T_THISNETWORK:
return 'Refer to source hosts on "this" network';
case static::T_LOOPBACK:
return 'Internet host loopback address';
case static::T_ANYCASTRELAY:
return 'Relay anycast address';
case static::T_LIMITEDBROADCAST:
return '"Limited broadcast" destination address';
case static::T_MULTICAST:
return 'Multicast address assignments - Indentify a group of interfaces';
case static::T_LINKLOCAL:
return '"Link local" address, allocated for communication between hosts on a single link';
case static::T_LINKLOCAL_UNICAST:
return 'Link local unicast / Linked-scoped unicast';
case static::T_DISCARDONLY:
return 'Discard only';
case static::T_DISCARD:
return 'Discard';
case static::T_PRIVATENETWORK:
return 'For use in private networks';
case static::T_PUBLIC:
return 'Public address';
default:
return $type === null ? 'Unknown type' : sprintf('Unknown type (%s)', $type);
}
}
|
Get the name of a type.
@param int $type
@return string
|
entailment
|
public function getAddressType(AddressInterface $address)
{
$result = null;
if ($this->range->contains($address)) {
foreach ($this->exceptions as $exception) {
$result = $exception->getAddressType($address);
if ($result !== null) {
break;
}
}
if ($result === null) {
$result = $this->type;
}
}
return $result;
}
|
Get the assigned type for a specific address.
@param \IPLib\Address\AddressInterface $address
@return int|null return NULL of the address is outside this address; a \IPLib\Range\Type::T_ constant otherwise
|
entailment
|
public function getRangeType(RangeInterface $range)
{
$myStart = $this->range->getComparableStartString();
$rangeEnd = $range->getComparableEndString();
if ($myStart > $rangeEnd) {
$result = null;
} else {
$myEnd = $this->range->getComparableEndString();
$rangeStart = $range->getComparableStartString();
if ($myEnd < $rangeStart) {
$result = null;
} elseif ($rangeStart < $myStart || $rangeEnd > $myEnd) {
$result = false;
} else {
$result = null;
foreach ($this->exceptions as $exception) {
$result = $exception->getRangeType($range);
if ($result !== null) {
break;
}
}
if ($result === null) {
$result = $this->getType();
}
}
}
return $result;
}
|
Get the assigned type for a specific address range.
@param \IPLib\Range\RangeInterface $range
@return int|null|false return NULL of the range is fully outside this range; false if it's partly crosses this range (or it contains mixed types); a \IPLib\Range\Type::T_ constant otherwise
|
entailment
|
public static function fromString($range)
{
$result = null;
if (is_string($range)) {
$parts = explode('/', $range);
if (count($parts) === 2) {
$address = Factory::addressFromString($parts[0]);
if ($address !== null) {
if (preg_match('/^[0-9]{1,9}$/', $parts[1])) {
$networkPrefix = (int) $parts[1];
if ($networkPrefix >= 0) {
$addressBytes = $address->getBytes();
$totalBytes = count($addressBytes);
$numDifferentBits = $totalBytes * 8 - $networkPrefix;
if ($numDifferentBits >= 0) {
$numSameBytes = $networkPrefix >> 3;
$sameBytes = array_slice($addressBytes, 0, $numSameBytes);
$differentBytesStart = ($totalBytes === $numSameBytes) ? array() : array_fill(0, $totalBytes - $numSameBytes, 0);
$differentBytesEnd = ($totalBytes === $numSameBytes) ? array() : array_fill(0, $totalBytes - $numSameBytes, 255);
$startSameBits = $networkPrefix % 8;
if ($startSameBits !== 0) {
$varyingByte = $addressBytes[$numSameBytes];
$differentBytesStart[0] = $varyingByte & bindec(str_pad(str_repeat('1', $startSameBits), 8, '0', STR_PAD_RIGHT));
$differentBytesEnd[0] = $differentBytesStart[0] + bindec(str_repeat('1', 8 - $startSameBits));
}
$result = new static(
Factory::addressFromBytes(array_merge($sameBytes, $differentBytesStart)),
Factory::addressFromBytes(array_merge($sameBytes, $differentBytesEnd)),
$networkPrefix
);
}
}
}
}
}
}
return $result;
}
|
Try get the range instance starting from its string representation.
@param string|mixed $range
@return static|null
|
entailment
|
public function contains(AddressInterface $address)
{
$result = false;
if ($address->getAddressType() === $this->getAddressType()) {
$cmp = $address->getComparableString();
$from = $this->getComparableStartString();
if ($cmp >= $from) {
$to = $this->getComparableEndString();
if ($cmp <= $to) {
$result = true;
}
}
}
return $result;
}
|
{@inheritdoc}
@see \IPLib\Range\RangeInterface::contains()
|
entailment
|
public function containsRange(RangeInterface $range)
{
$result = false;
if ($range->getAddressType() === $this->getAddressType()) {
$myStart = $this->getComparableStartString();
$itsStart = $range->getComparableStartString();
if ($itsStart >= $myStart) {
$myEnd = $this->getComparableEndString();
$itsEnd = $range->getComparableEndString();
if ($itsEnd <= $myEnd) {
$result = true;
}
}
}
return $result;
}
|
{@inheritdoc}
@see \IPLib\Range\RangeInterface::containsRange()
|
entailment
|
public static function get6to4()
{
if (self::$sixToFour === null) {
self::$sixToFour = self::fromString('2002::/16');
}
return self::$sixToFour;
}
|
Get the 6to4 address IPv6 address range.
@return self
|
entailment
|
public static function fromString($range)
{
$result = null;
if (is_string($range) && strpos($range, '*') !== false) {
$matches = null;
if ($range === '*.*.*.*') {
$result = new static(IPv4::fromString('0.0.0.0'), IPv4::fromString('255.255.255.255'), 4);
} elseif (strpos($range, '.') !== false && preg_match('/^[^*]+((?:\.\*)+)$/', $range, $matches)) {
$asterisksCount = strlen($matches[1]) >> 1;
if ($asterisksCount > 0) {
$missingDots = 3 - substr_count($range, '.');
if ($missingDots > 0) {
$range .= str_repeat('.*', $missingDots);
$asterisksCount += $missingDots;
}
}
$fromAddress = IPv4::fromString(str_replace('*', '0', $range));
if ($fromAddress !== null) {
$fixedBytes = array_slice($fromAddress->getBytes(), 0, -$asterisksCount);
$otherBytes = array_fill(0, $asterisksCount, 255);
$toAddress = IPv4::fromBytes(array_merge($fixedBytes, $otherBytes));
$result = new static($fromAddress, $toAddress, $asterisksCount);
}
} elseif ($range === '*:*:*:*:*:*:*:*') {
$result = new static(IPv6::fromString('::'), IPv6::fromString('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'), 8);
} elseif (strpos($range, ':') !== false && preg_match('/^[^*]+((?::\*)+)$/', $range, $matches)) {
$asterisksCount = strlen($matches[1]) >> 1;
$fromAddress = IPv6::fromString(str_replace('*', '0', $range));
if ($fromAddress !== null) {
$fixedWords = array_slice($fromAddress->getWords(), 0, -$asterisksCount);
$otherWords = array_fill(0, $asterisksCount, 0xffff);
$toAddress = IPv6::fromWords(array_merge($fixedWords, $otherWords));
$result = new static($fromAddress, $toAddress, $asterisksCount);
}
}
}
return $result;
}
|
Try get the range instance starting from its string representation.
@param string|mixed $range
@return static|null
|
entailment
|
public function toString($long = false)
{
switch (true) {
case $this->fromAddress instanceof \IPLib\Address\IPv4:
$chunks = explode('.', $this->fromAddress->toString());
$chunks = array_slice($chunks, 0, -$this->asterisksCount);
$chunks = array_pad($chunks, 4, '*');
$result = implode('.', $chunks);
break;
case $this->fromAddress instanceof \IPLib\Address\IPv6:
if ($long) {
$chunks = explode(':', $this->fromAddress->toString(true));
$chunks = array_slice($chunks, 0, -$this->asterisksCount);
$chunks = array_pad($chunks, 8, '*');
$result = implode(':', $chunks);
} else {
$chunks = explode(':', $this->toAddress->toString(false));
$chunkCount = count($chunks);
$chunks = array_slice($chunks, 0, -$this->asterisksCount);
$chunks = array_pad($chunks, $chunkCount, '*');
$result = implode(':', $chunks);
}
break;
default:
throw new \Exception('@todo'); // @codeCoverageIgnore
}
return $result;
}
|
{@inheritdoc}
@see \IPLib\Range\RangeInterface::toString()
|
entailment
|
public function getRangeType()
{
if ($this->rangeType === null) {
$addressType = $this->getAddressType();
if ($addressType === AddressType::T_IPv6 && Subnet::get6to4()->containsRange($this)) {
$this->rangeType = Factory::rangeFromBoundaries($this->fromAddress->toIPv4(), $this->toAddress->toIPv4())->getRangeType();
} else {
switch ($addressType) {
case AddressType::T_IPv4:
$defaultType = IPv4::getDefaultReservedRangeType();
$reservedRanges = IPv4::getReservedRanges();
break;
case AddressType::T_IPv6:
$defaultType = IPv6::getDefaultReservedRangeType();
$reservedRanges = IPv6::getReservedRanges();
break;
default:
throw new \Exception('@todo'); // @codeCoverageIgnore
}
$rangeType = null;
foreach ($reservedRanges as $reservedRange) {
$rangeType = $reservedRange->getRangeType($this);
if ($rangeType !== null) {
break;
}
}
$this->rangeType = $rangeType === null ? $defaultType : $rangeType;
}
}
return $this->rangeType === false ? null : $this->rangeType;
}
|
{@inheritdoc}
@see \IPLib\Range\RangeInterface::getRangeType()
|
entailment
|
public static function fromString($address, $mayIncludePort = true)
{
$result = null;
if (is_string($address) && strpos($address, '.')) {
$rx = '([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})';
if ($mayIncludePort) {
$rx .= '(?::\d+)?';
}
$matches = null;
if (preg_match('/^'.$rx.'$/', $address, $matches)) {
$ok = true;
$nums = array();
for ($i = 1; $ok && $i <= 4; ++$i) {
$ok = false;
$n = (int) $matches[$i];
if ($n >= 0 && $n <= 255) {
$ok = true;
$nums[] = (string) $n;
}
}
if ($ok) {
$result = new static(implode('.', $nums));
}
}
}
return $result;
}
|
Parse a string and returns an IPv4 instance if the string is valid, or null otherwise.
@param string|mixed $address the address to parse
@param bool $mayIncludePort set to false to avoid parsing addresses with ports
@return static|null
|
entailment
|
public static function fromBytes(array $bytes)
{
$result = null;
if (count($bytes) === 4) {
$chunks = array_map(
function ($byte) {
return (is_int($byte) && $byte >= 0 && $byte <= 255) ? (string) $byte : false;
},
$bytes
);
if (in_array(false, $chunks, true) === false) {
$result = new static(implode('.', $chunks));
}
}
return $result;
}
|
Parse an array of bytes and returns an IPv4 instance if the array is valid, or null otherwise.
@param int[]|array $bytes
@return static|null
|
entailment
|
public function getBytes()
{
if ($this->bytes === null) {
$this->bytes = array_map(
function ($chunk) {
return (int) $chunk;
},
explode('.', $this->address)
);
}
return $this->bytes;
}
|
{@inheritdoc}
@see \IPLib\Address\AddressInterface::getBytes()
|
entailment
|
public static function getReservedRanges()
{
if (self::$reservedRanges === null) {
$reservedRanges = array();
foreach (array(
// RFC 5735
'0.0.0.0/8' => array(RangeType::T_THISNETWORK, array('0.0.0.0/32' => RangeType::T_UNSPECIFIED)),
// RFC 5735
'10.0.0.0/8' => array(RangeType::T_PRIVATENETWORK),
// RFC 5735
'127.0.0.0/8' => array(RangeType::T_LOOPBACK),
// RFC 5735
'169.254.0.0/16' => array(RangeType::T_LINKLOCAL),
// RFC 5735
'172.16.0.0/12' => array(RangeType::T_PRIVATENETWORK),
// RFC 5735
'192.0.0.0/24' => array(RangeType::T_RESERVED),
// RFC 5735
'192.0.2.0/24' => array(RangeType::T_RESERVED),
// RFC 5735
'192.88.99.0/24' => array(RangeType::T_ANYCASTRELAY),
// RFC 5735
'192.168.0.0/16' => array(RangeType::T_PRIVATENETWORK),
// RFC 5735
'198.18.0.0/15' => array(RangeType::T_RESERVED),
// RFC 5735
'198.51.100.0/24' => array(RangeType::T_RESERVED),
// RFC 5735
'203.0.113.0/24' => array(RangeType::T_RESERVED),
// RFC 5735
'224.0.0.0/4' => array(RangeType::T_MULTICAST),
// RFC 5735
'240.0.0.0/4' => array(RangeType::T_RESERVED, array('255.255.255.255/32' => RangeType::T_LIMITEDBROADCAST)),
) as $range => $data) {
$exceptions = array();
if (isset($data[1])) {
foreach ($data[1] as $exceptionRange => $exceptionType) {
$exceptions[] = new AssignedRange(Subnet::fromString($exceptionRange), $exceptionType);
}
}
$reservedRanges[] = new AssignedRange(Subnet::fromString($range), $data[0], $exceptions);
}
self::$reservedRanges = $reservedRanges;
}
return self::$reservedRanges;
}
|
{@inheritdoc}
@see \IPLib\Address\AddressInterface::getReservedRanges()
|
entailment
|
public function getRangeType()
{
if ($this->rangeType === null) {
$rangeType = null;
foreach (static::getReservedRanges() as $reservedRange) {
$rangeType = $reservedRange->getAddressType($this);
if ($rangeType !== null) {
break;
}
}
$this->rangeType = $rangeType === null ? static::getDefaultReservedRangeType() : $rangeType;
}
return $this->rangeType;
}
|
{@inheritdoc}
@see \IPLib\Address\AddressInterface::getRangeType()
|
entailment
|
public function toIPv6()
{
$myBytes = $this->getBytes();
return IPv6::fromString('2002:'.sprintf('%02x', $myBytes[0]).sprintf('%02x', $myBytes[1]).':'.sprintf('%02x', $myBytes[2]).sprintf('%02x', $myBytes[3]).'::');
}
|
Create an IPv6 representation of this address.
@return \IPLib\Address\IPv6
|
entailment
|
public function getComparableString()
{
if ($this->comparableString === null) {
$chunks = array();
foreach ($this->getBytes() as $byte) {
$chunks[] = sprintf('%03d', $byte);
}
$this->comparableString = implode('.', $chunks);
}
return $this->comparableString;
}
|
{@inheritdoc}
@see \IPLib\Address\AddressInterface::getComparableString()
|
entailment
|
public function getNextAddress()
{
$overflow = false;
$bytes = $this->getBytes();
for ($i = count($bytes) - 1; $i >= 0; --$i) {
if ($bytes[$i] === 255) {
if ($i === 0) {
$overflow = true;
break;
}
$bytes[$i] = 0;
} else {
++$bytes[$i];
break;
}
}
return $overflow ? null : static::fromBytes($bytes);
}
|
{@inheritdoc}
@see \IPLib\Address\AddressInterface::getNextAddress()
|
entailment
|
public static function addressFromString($address, $mayIncludePort = true, $mayIncludeZoneID = true)
{
$result = null;
if ($result === null) {
$result = Address\IPv4::fromString($address, $mayIncludePort);
}
if ($result === null) {
$result = Address\IPv6::fromString($address, $mayIncludePort, $mayIncludeZoneID);
}
return $result;
}
|
Parse an IP address string.
@param string $address the address to parse
@param bool $mayIncludePort set to false to avoid parsing addresses with ports
@param bool $mayIncludeZoneID set to false to avoid parsing IPv6 addresses with zone IDs (see RFC 4007)
@return \IPLib\Address\AddressInterface|null
|
entailment
|
public static function addressFromBytes(array $bytes)
{
$result = null;
if ($result === null) {
$result = Address\IPv4::fromBytes($bytes);
}
if ($result === null) {
$result = Address\IPv6::fromBytes($bytes);
}
return $result;
}
|
Convert a byte array to an address instance.
@param int[]|array $bytes
@return \IPLib\Address\AddressInterface|null
|
entailment
|
public static function rangeFromString($range)
{
$result = null;
if ($result === null) {
$result = Range\Subnet::fromString($range);
}
if ($result === null) {
$result = Range\Pattern::fromString($range);
}
if ($result === null) {
$result = Range\Single::fromString($range);
}
return $result;
}
|
Parse an IP range string.
@param string $range
@return \IPLib\Range\RangeInterface|null
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.