This is a helper class for working with arrays.
Inheritance: extends Webiny\Component\StdLib\StdObject\AbstractStdObject, implements IteratorAggregate, implements ArrayAccess, implements Countable, use trait ManipulatorTrait, use trait ValidatorTrait
コード例 #1
0
ファイル: EntityPool.php プロジェクト: Nkelliny/Framework
 /**
  * Remove instance from pool
  *
  * @param $instance
  *
  * @return bool
  */
 public function remove(EntityAbstract $instance)
 {
     $entityPool = $this->pool->key(get_class($instance), $this->arr(), true);
     $entityPool->removeKey($instance->getId()->getValue());
     unset($instance);
     return true;
 }
コード例 #2
0
ファイル: UrlObject.php プロジェクト: Nkelliny/Framework
 /**
  * Build a UrlObject from array parts.
  *
  * @param ArrayObject|array $parts Url parts, possible keys are: 'scheme', 'host', 'port', 'path' and 'query'
  *
  * @throws UrlObjectException
  * @return UrlObject
  */
 static function buildUrl($parts)
 {
     $parts = new ArrayObject($parts);
     ###################
     ### PARSE PARTS ###
     ###################
     // scheme
     $scheme = $parts->key('scheme', '', true);
     // host
     $host = $parts->key('host', '', true);
     // port
     $port = $parts->key('port', '', true);
     // path
     $path = $parts->key('path', '', true);
     // parse query string
     $query = '';
     if ($parts->keyExists('query')) {
         if (self::isString($parts->key('query'))) {
             parse_str($parts->key('query'), $queryData);
         } else {
             $queryData = $parts->key('query');
         }
         if (self::isArray($queryData)) {
             $query = $queryData;
         }
     }
     ###################
     ### BUILD URL   ###
     ###################
     $url = '';
     // scheme
     if ($scheme && $scheme != '') {
         $url .= $scheme . '://';
     }
     // host
     if ($host && $host != '') {
         $url .= $host;
     }
     // port
     if ($port != '') {
         $url .= ':' . $port;
     }
     // path
     if ($path != '') {
         $url .= $path;
     }
     // query
     if (self::isArray($query)) {
         $query = http_build_query($query);
         if ($query != "") {
             $url .= '?' . $query;
         }
     }
     try {
         return new UrlObject($url);
     } catch (\Exception $e) {
         throw new UrlObjectException($e->getMessage());
     }
 }
コード例 #3
0
 /**
  * Constructor
  *
  * @param array|ArrayObject $config
  *
  * @throws StorageException
  */
 public function __construct($config)
 {
     if (is_array($config)) {
         $config = new ArrayObject($config);
     }
     if (!$config instanceof ArrayObject) {
         throw new StorageException('Storage driver config must be an array or ArrayObject!');
     }
     $this->helper = LocalHelper::getInstance();
     $this->directory = $this->helper->normalizeDirectoryPath($config->key('Directory', '', true));
     $this->publicUrl = $config->key('PublicUrl', '', true);
     $this->dateFolderStructure = $config->key('DateFolderStructure', false, true);
     $this->create = $config->key('Create', false, true);
 }
コード例 #4
0
ファイル: AbstractEntity.php プロジェクト: webiny/entity
 /**
  * Get entity attribute
  *
  * @param string $attribute
  *
  * @throws EntityException
  * @return AbstractAttribute
  */
 public function getAttribute($attribute)
 {
     if (!$this->attributes->keyExists($attribute)) {
         throw new EntityException(EntityException::ATTRIBUTE_NOT_FOUND, [$attribute, get_class($this)]);
     }
     return $this->attributes[$attribute];
 }
コード例 #5
0
ファイル: Webiny.php プロジェクト: Nkelliny/Framework
 /**
  * Adds a log record.
  *
  * @param  integer $level   The logging level
  * @param  string  $message The log message
  * @param  array   $context The log context
  *
  * @throws LoggerException
  * @return Boolean Whether the record has been processed
  */
 protected function addRecord($level, $message, array $context = array())
 {
     if ($this->handlers->count() < 1) {
         throw new LoggerException('To log a record you must add at least one HandlerAbstract object to handle the messages.');
     }
     $record = new Record();
     $record->setLoggerName($this->name);
     $record->setMessage((string) $message);
     $record->setContext($context);
     $record->setLevel($level);
     $record->setDatetime($this->datetime("now"));
     // check if any handler will handle this message
     $canHandle = false;
     foreach ($this->handlers as $handler) {
         if ($handler->canHandle($record)) {
             $canHandle = true;
             break;
         }
     }
     if (!$canHandle) {
         return false;
     }
     /* @var $handler Webiny\HandlerAbstract */
     foreach ($this->handlers as $handler) {
         if ($handler->canHandle($record)) {
             $bubble = $handler->process(clone $record);
             if (!$bubble) {
                 break;
             }
         }
     }
     return true;
 }
コード例 #6
0
ファイル: DateTimeObject.php プロジェクト: Webiny/Framework
 /**
  * Checks if $format is a valid format for $dateElement.
  *
  * @param string $dateElement Possible values are: date, year, month, day, time, hour, minutes, seconds, meridiem.
  * @param string $format For list of possible formats check: http://php.net/manual/en/function.date.php
  *
  * @return mixed
  * @throws DateTimeObjectException
  */
 private function validateFormatFor($dateElement, $format)
 {
     if (!self::$formatters->key($dateElement)->inArray($format)) {
         throw new DateTimeObjectException(DateTimeObjectException::MSG_INVALID_FORMAT_FOR_ELEMENT, [$format, "get" . ucfirst($dateElement)]);
     }
     return $format;
 }
コード例 #7
0
ファイル: ValidatorTrait.php プロジェクト: Nkelliny/Framework
 /**
  * Checks if $key exists in current array as index. If it exists, true is returned.
  * If the $key doesn't exist, $default is returned.
  * This method supports nested keys access: 'level1.level2.level3'
  *
  * @param string|StringObject $key     Array key. Eg: 'level1.level2.level3'
  * @param mixed               $default If key is not found, $default is returned.
  *
  * @return bool|mixed True is returned if the key exists, otherwise $default is returned.
  */
 public function keyExistsNested($key, $default = false)
 {
     $key = StdObjectWrapper::toString($key);
     if (strpos($key, '.') !== false) {
         $keys = explode('.', trim($key, '.'), 2);
         if (!isset($this->val()[$keys[0]])) {
             return $default;
         }
         $sourceArray = new ArrayObject($this->val()[$keys[0]]);
         return $sourceArray->keyExistsNested($keys[1], $default);
     }
     if (array_key_exists($key, $this->val())) {
         return true;
     }
     return $default;
 }
コード例 #8
0
ファイル: Entity.php プロジェクト: Webiny/Framework
 /**
  * Remove instance from pool
  *
  * @param $instance
  *
  * @return bool
  */
 public function remove(AbstractEntity $instance)
 {
     $entityPool = $this->pool->key(get_class($instance), $this->arr(), true);
     $entityPool->removeKey($instance->id);
     unset($instance);
     return true;
 }
コード例 #9
0
ファイル: ServiceManager.php プロジェクト: Webiny/Framework
 /**
  * Instantiate service using given service name
  *
  * @param string $serviceName
  *
  * @return object
  * @throws ServiceManagerException
  */
 private function instantiateService($serviceName)
 {
     // Make sure service is registered
     if (!$this->registeredServices->keyExists($serviceName)) {
         throw new ServiceManagerException(ServiceManagerException::SERVICE_DEFINITION_NOT_FOUND, [$serviceName]);
     }
     // Get service config from registered services array
     $config = $this->registeredServices->key($serviceName);
     // Check circular referencing
     if ($this->references->keyExists($serviceName)) {
         throw new ServiceManagerException(ServiceManagerException::SERVICE_CIRCULAR_REFERENCE, [$serviceName]);
     }
     // Set service name reference for circular referencing checks
     $this->references->key($serviceName, $serviceName);
     // Compile ConfigObject into ServiceConfig
     $configCompiler = new ConfigCompiler($serviceName, $config, $this->parameters);
     $this->compiledConfig->key($serviceName, $configCompiler->compile());
     /**
      * @var $config ServiceConfig
      */
     $config = $this->compiledConfig->key($serviceName);
     // Construct service container and get service instance
     $serviceCreator = new ServiceCreator($config);
     $service = $serviceCreator->getService();
     // Unset service name reference
     $this->references->removeKey($serviceName);
     // Store instance if this service has a CONTAINER scope
     if ($config->getScope() == ServiceScope::CONTAINER) {
         $this->instantiatedServices->key($serviceName, $service);
     }
     return $service;
 }
コード例 #10
0
ファイル: CacheControl.php プロジェクト: Webiny/Framework
 /**
  * Sets or adds an entry to cache control headers.
  *
  * @param string $key   Cache control header name.
  * @param string $value Cache control header value.
  *
  * @throws ResponseException
  * @return $this
  */
 public function setCacheControlEntry($key, $value)
 {
     if (!$this->validateCacheControlHeader($key)) {
         throw new ResponseException('Invalid cache control header "' . $key . '".');
     }
     $this->cacheControl->key($key, $value);
     return $this;
 }
コード例 #11
0
ファイル: Response.php プロジェクト: Webiny/Framework
 /**
  * Sets the response as not modified.
  *
  * @return $this
  */
 public function setAsNotModified()
 {
     $this->setStatusCode(304);
     $this->setContent('');
     // remove headers that MUST NOT be included with 304 Not Modified responses
     $headersToRemove = ['Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified'];
     foreach ($headersToRemove as $header) {
         $this->headers->removeKey($header);
     }
     return $this;
 }
コード例 #12
0
ファイル: ConfigObject.php プロジェクト: Webiny/Framework
 /**
  * Build internal object data using given $config
  *
  * @param array|ArrayObject $config
  */
 private function buildInternalData($config)
 {
     $this->data = $this->arr();
     $array = StdObjectWrapper::toArray($config);
     foreach ($array as $key => $value) {
         if ($this->isArray($value)) {
             $this->data->key($key, new static($value, false));
         } else {
             $this->data->key($key, $value, true);
         }
     }
 }
コード例 #13
0
ファイル: RoleHierarchy.php プロジェクト: Webiny/Framework
 /**
  * Private function that parses the hierarchy array and builds up a hierarchy map
  *
  * @param array $hierarchy Role hierarchy array from system configuration.
  */
 private function buildRoleMap($hierarchy)
 {
     $this->map = $this->arr();
     foreach ($hierarchy as $main => $roles) {
         $hierarchy[$main] = $this->arr((array) $roles);
     }
     $hierarchy = $this->arr($hierarchy);
     foreach ($hierarchy as $main => $roles) {
         $this->map->append($main, $roles->val());
         $additionalRoles = clone $roles;
         $parsed = $this->arr();
         $role = '';
         while ($additionalRoles->count() > 0 && $additionalRoles->removeFirst($role)) {
             if (!$hierarchy->keyExists($role)) {
                 continue;
             }
             $parsed->append($role);
             $innerRole = $this->arr($this->map->key($main));
             $innerRole->merge($hierarchy[$role]->val());
             $this->map->append($main, $innerRole->val());
             $additionalRoles->merge($hierarchy->key($role)->diff($parsed->val())->val());
         }
     }
 }
コード例 #14
0
ファイル: S3StorageDriver.php プロジェクト: Webiny/Framework
 /**
  * Constructor
  *
  * @param array|ArrayObject $config
  *
  * @throws StorageException
  */
 public function __construct($config)
 {
     if (is_array($config)) {
         $config = new ArrayObject($config);
     }
     if (!$config instanceof ArrayObject) {
         throw new StorageException('Storage driver config must be an array or ArrayObject!');
     }
     $bridge = Storage::getConfig()->get('Bridges.AmazonS3', '\\Webiny\\Component\\Amazon\\S3');
     $accessKeyId = $config->key('AccessKeyId');
     $secretAccessKey = $config->key('SecretAccessKey');
     $region = $config->key('Region');
     $endpoint = $config->key('Endpoint');
     $this->s3Client = new $bridge($accessKeyId, $secretAccessKey, $region, $endpoint);
     $this->bucket = $config->key('Bucket');
     $this->cdnDomain = $config->key('CdnDomain');
     $this->meta = $config->key('Meta');
 }
コード例 #15
0
ファイル: ManipulatorTrait.php プロジェクト: Webiny/Framework
 /**
  * Set or get given $value for given $key.
  *
  * @param string $key Key to set/get
  * @param mixed  $value Value to set
  * @param bool   $setOnlyIfNotExists Set default value or not
  */
 private function handleNestedValue($key, $value, $setOnlyIfNotExists)
 {
     $array = $this->val();
     if (strpos($key, '.') !== false) {
         $keys = explode('.', trim($key, '.'), 2);
         if (!isset($array[$keys[0]])) {
             $array[$keys[0]] = [];
         }
         $targetArray = new ArrayObject($array[$keys[0]]);
         $targetArray->keyNested($keys[1], $value, $setOnlyIfNotExists);
         $this->keyNested($keys[0], $targetArray->val());
     } else {
         $array[$key] = $value;
         $this->val($array);
     }
 }
コード例 #16
0
ファイル: JsonResponseTest.php プロジェクト: Webiny/Framework
 public function testArrayObjectConstructor()
 {
     $arrayObject = new ArrayObject(['foo' => 'value']);
     $jr = new JsonResponse($arrayObject);
     $this->assertSame(json_encode($arrayObject->val()), $jr->getContent());
 }
コード例 #17
0
ファイル: EntityTest.php プロジェクト: webiny/entity
 /**
  * This test runs a simple populate on entity with no validators.
  *
  * It tests:
  * - all attribute types
  * - all reference attributes: many2one, one2many and many2many
  * - it tests both on-fly creation and linking with existing entities
  */
 public function testPopulateNoValidationAllNew()
 {
     $many2one = new Many2One();
     $many2one->char = 'many2oneExisting';
     $many2one->save();
     $many2many = new Many2Many();
     $many2many->char = 'many2many1';
     $many2many->save();
     $many2many2 = new Many2Many();
     $many2many2->char = 'many2many2';
     $many2many2->save();
     $data = ['boolean' => true, 'char' => 'char', 'skip' => 'this value will not be set', 'integer' => 12, 'calculation' => 5, 'float' => 20.35, 'date' => '2016-03-14', 'datetime' => '2016-03-14T13:45:20+0000', 'arr' => [1, 2, 3], 'object' => ['key1' => 'value', 'key2' => 12], 'geoPoint' => ['lat' => 50, 'lng' => 100, 'stripThisKey' => 'whatever'], 'many2oneNew' => ['char' => 'many2oneNew'], 'many2oneExisting' => $many2one, 'one2many' => [['char' => 'one2many1'], ['char' => 'one2many2']], 'many2many' => [$many2many->id, $many2many2]];
     $class = Lib\Classes::ENTITY_NO_VALIDATION;
     $entity = new $class();
     $entity->populate($data)->save();
     // Test current $entity state
     $this->assertEntityStateNoValidation($entity);
     // Load entity from DB and test state again
     $id = $entity->id;
     Entity::getInstance()->remove($entity);
     $entity = $class::findById($id);
     $this->assertEntityStateNoValidation($entity);
     // Test toArray conversion
     $array = new ArrayObject($entity->toArray('*,float:2,arr,object[key1],dynamicWithParams:4,many2oneNew[char,relations.integer],one2many,many2many', 2));
     $this->assertEquals('char', $array->keyNested('char'));
     $this->assertEquals(4, $array->keyNested('float'));
     $this->assertArrayNotHasKey('boolean', $array->val());
     $this->assertArrayNotHasKey('skip', $array->val());
     $this->assertEquals([1, 2, 3], $array->keyNested('arr'));
     $this->assertEquals('value', $array->keyNested('object.key1'));
     $this->assertNull($array->keyNested('object.key2'));
     // GeoPoint should return an array of lat/lng values
     $this->assertEquals(50, $array->keyNested('geoPoint.lat'));
     $this->assertEquals(100, $array->keyNested('geoPoint.lng'));
     // If return value of dynamic attribute is AbstractEntity or EntityCollection,
     // EntityDataExtractor should call toArray() an those objects
     $this->assertEquals(24, $array->key('dynamicWithDefaultParams'));
     $this->assertEquals(48, $array->key('dynamicWithParams'));
     $this->assertInternalType('array', $array->key('dynamicEntity'));
     $this->assertInternalType('array', $array->key('dynamicEntityCollection'));
     $this->assertCount(2, $array->key('dynamicEntityCollection'));
     $this->assertEquals('many2oneExisting', $array->keyNested('dynamicEntityCollection.0.char'));
     $this->assertEquals('many2oneNew', $array->keyNested('dynamicEntityCollection.1.char'));
     // GeoPoint attribute should strips all values not related to mongo Point
     $this->assertArrayNotHasKey('stripThisKey', $array->keyNested('geoPoint'));
     $this->assertEquals('many2oneNew', $array->keyNested('many2oneNew.char'));
     $this->assertEquals(12, $array->keyNested('many2oneNew.relations.0.integer'));
     $this->assertEquals('one2many1', $array->keyNested('one2many.0.char'));
     $this->assertEquals('one2many2', $array->keyNested('one2many.1.char'));
     $this->assertEquals('many2many1', $array->keyNested('many2many.0.char'));
     $this->assertEquals('many2many2', $array->keyNested('many2many.1.char'));
 }
コード例 #18
0
ファイル: Plugin.php プロジェクト: Webiny/Framework
 /**
  * Return the attribute value under the defined $key.
  *
  * @param string $key          Attribute key.
  * @param mixed  $defaultValue Default value that the method should return if $key is not found among the attributes.
  *
  * @return mixed
  */
 public function getAttribute($key, $defaultValue = false)
 {
     return $this->attributes->key($key, $defaultValue, true);
 }
コード例 #19
0
ファイル: MongoResult.php プロジェクト: Nkelliny/Framework
 /**
  * (PHP 5 &gt;= 5.1.0)<br/>
  * Count elements of an object
  * @link http://php.net/manual/en/countable.count.php
  * @return int The custom count as an integer.
  * </p>
  * <p>
  * The return value is cast to an integer.
  */
 public function count()
 {
     return $this->data->count();
 }
コード例 #20
0
ファイル: RouteCollection.php プロジェクト: Webiny/Framework
 /**
  * Returns an array of all routes within the collection.
  *
  * @return array
  */
 public function all()
 {
     return $this->routes->val();
 }
コード例 #21
0
ファイル: Session.php プロジェクト: Webiny/Framework
 /**
  * Get all session values.
  *
  * @return array Key-value array of all session entries.
  */
 public function getAll()
 {
     return $this->sessionBag->val();
 }
コード例 #22
0
 /**
  * Generate a hash value from the current string using the defined algorithm.
  *
  * @param string $algo Name of the algorithm used for calculation (md5, sha1, ripemd160,...).
  *
  * @throws StringObjectException
  * @return $this
  */
 public function hash($algo = 'sha1')
 {
     $algos = new ArrayObject(hash_algos());
     if (!$algos->inArray($algo)) {
         throw new StringObjectException(StringObjectException::MSG_INVALID_HASH_ALGO, [$algo]);
     }
     $this->val(hash($algo, $this->val()));
     return $this;
 }
コード例 #23
0
ファイル: RouteOption.php プロジェクト: Webiny/Framework
 /**
  * Returns all the attributes.
  *
  * @return array
  */
 public function getAttributes()
 {
     return $this->attributes->val();
 }
コード例 #24
0
ファイル: ConfigCompiler.php プロジェクト: Webiny/Framework
 /**
  * Extend $config with $parentConfig
  *
  * @param ArrayObject $config       Child config object
  * @param ArrayObject $parentConfig Parent config object
  *
  * @return ArrayObject
  */
 private function extendConfig(ArrayObject $config, ArrayObject $parentConfig)
 {
     $configCalls = null;
     $overrideCalls = false;
     // Get calls arrays
     if ($config->keyExists('Calls')) {
         $configCalls = $config->key('Calls');
     } elseif ($config->keyExists('!Calls')) {
         $configCalls = $config->key('!Calls');
         $overrideCalls = true;
     }
     $parentCalls = $parentConfig->key('Calls', [], true);
     // Merge basic values
     $config = $parentConfig->merge($config);
     // Remove unnecessary keys
     $config->removeKey('Parent')->removeKey('Abstract')->removeKey('Calls');
     // Merge calls
     if (!$this->isNull($configCalls) && !$this->isNull($parentCalls)) {
         if ($overrideCalls) {
             $config->key('!Calls', $configCalls);
             return;
         }
         foreach ($configCalls as $call) {
             $call = $this->arr($call);
             if ($call->keyExists(2)) {
                 $parentCalls[$call[2]] = $call->val();
             } else {
                 $parentCalls[] = $call->val();
             }
         }
         $config->key('Calls', $parentCalls);
     } elseif ($this->isNull($configCalls) && !$this->isNull($parentCalls)) {
         $config->key('Calls', $parentCalls);
     } elseif (!$this->isNull($configCalls) && $this->isNull($parentCalls)) {
         $config->key('Calls', $configCalls);
     }
     return $config;
 }
コード例 #25
0
ファイル: ArrayObjectTest.php プロジェクト: Webiny/Framework
 /**
  * @dataProvider mergeArrays
  */
 public function testMergeSmart($original, $merge, $result)
 {
     $a = new ArrayObject($original);
     $b = new ArrayObject($merge);
     $this->assertEquals($result, $a->mergeSmart($b)->val());
 }
コード例 #26
0
ファイル: ManipulatorTrait.php プロジェクト: Webiny/Framework
 /**
  * Set url query param.
  *
  * @param StringObject|ArrayObject|string|array $query  Query params.
  * @param bool                                  $append Do you want to append or overwrite current query param.
  *                                                      In case when you are appending values, the values from $query,
  *                                                      that already exist in the current query, will be overwritten
  *                                                      by the ones inside the $query.
  *
  * @throws UrlObjectException
  * @return $this
  */
 public function setQuery($query, $append = false)
 {
     if ($this->isStdObject($query)) {
         $query = $query->val();
     }
     if ($append && $this->query != '') {
         if ($this->isString($this->query)) {
             $currentQuery = new StringObject($this->query);
             $currentQuery = $currentQuery->parseString();
         } else {
             $currentQuery = new ArrayObject($this->query);
         }
         if ($this->isStdObject($query)) {
             if (StdObjectWrapper::isArrayObject($append)) {
                 $query = $query->val();
             } else {
                 if (StdObjectWrapper::isStringObject($query)) {
                     $query = $query->parseString()->val();
                 } else {
                     throw new UrlObjectException(UrlObjectException::MSG_INVALID_ARG, ['$query', 'StringObject|ArrayObject|string|array']);
                 }
             }
         } else {
             if ($this->isString($query)) {
                 $query = new StringObject($query);
                 $query = $query->parseString()->val();
             }
         }
         $currentQuery->merge($query);
         $query = $currentQuery->val();
     }
     $this->query = $query;
     $this->rebuildUrl();
     return $this;
 }
コード例 #27
0
ファイル: EventManager.php プロジェクト: Webiny/Framework
 /**
  * Get array of event listeners
  *
  * @param $eventName
  *
  * @return array
  */
 public function getEventListeners($eventName)
 {
     return $this->events->key($eventName, [], true);
 }