public function beforeFilter(Event $event) { parent::beforeFilter($event); $session = $this->request->session(); $lang = 'en'; if (isset($this->request->params['lang'])) { $lang = $this->request->params['lang']; } else { if ($session->check('Config.language')) { $lang = $session->read('Config.language'); } } $session->write('Config.language', $lang); // Change current language by post request if ($this->request->is('post') && isset($this->request->data['language'])) { $newLang = $this->request->data['language']; $transUrl = $this->translateUrl($newLang); $this->redirect($transUrl); } $this->set('lang', $lang); $this->set('controller', $this->name); I18n::locale($lang); Time::setToStringFormat('YYYY-MM-dd HH:mm:ss'); Type::build('datetime')->useLocaleParser(); $this->Auth->config(['unauthorizedRedirect' => false]); $this->Auth->allow(['login', 'init']); $user = $this->Auth->user(); if (isset($user)) { $username = $user['username']; $this->set(['is_authorized' => true, 'username' => $username]); } else { $this->set('is_authorized', false); } }
/** * {@inheritDoc} */ public function __construct($name = null) { parent::__construct($name); if (!class_exists(static::$dateTimeClass)) { static::$dateTimeClass = 'DateTime'; } }
/** * Setup * * @return void */ public function setUp() { parent::setUp(); $this->type = Type::build('encryptedsecurity'); $this->driver = $this->getMockBuilder('Cake\\Database\\Driver')->getMock(); $this->crypted = base64_encode(Security::encrypt('string', Configure::read('Security.key'))); }
/** * Setup * * @return void */ public function setUp() { parent::setUp(); Type::map('binary', BinaryType::class); $this->type = Type::build('binary'); $this->driver = $this->getMockBuilder(Driver::class)->getMock(); }
/** * Setup * * @return void */ public function setUp() { parent::setUp(); $this->type = Type::build('float'); $this->driver = $this->getMock('Cake\\Database\\Driver'); $this->locale = I18n::locale(); I18n::locale($this->locale); }
/** * {@inheritDoc} */ public function __construct($name = null) { parent::__construct($name); if (!class_exists(static::$dateTimeClass)) { static::$dateTimeClass = 'DateTime'; } $this->_datetimeInstance = new static::$dateTimeClass(); }
/** * Build the map of property => marshalling callable. * * @param array $data The data being marshalled. * @param array $options List of options containing the 'associated' key. * @throws \InvalidArgumentException When associations do not exist. * @return array */ protected function _buildPropertyMap($data, $options) { $map = []; $schema = $this->_table->schema(); // Is a concrete column? foreach (array_keys($data) as $prop) { $columnType = $schema->columnType($prop); if ($columnType) { $map[$prop] = function ($value, $entity) use($columnType) { return Type::build($columnType)->marshal($value); }; } } // Map associations if (!isset($options['associated'])) { $options['associated'] = []; } $include = $this->_normalizeAssociations($options['associated']); foreach ($include as $key => $nested) { if (is_int($key) && is_scalar($nested)) { $key = $nested; $nested = []; } $assoc = $this->_table->association($key); // If the key is not a special field like _ids or _joinData // it is a missing association that we should error on. if (!$assoc) { if (substr($key, 0, 1) !== '_') { throw new \InvalidArgumentException(sprintf('Cannot marshal data for "%s" association. It is not associated with "%s".', $key, $this->_table->alias())); } continue; } if (isset($options['forceNew'])) { $nested['forceNew'] = $options['forceNew']; } if (isset($options['isMerge'])) { $callback = function ($value, $entity) use($assoc, $nested) { $options = $nested + ['associated' => []]; return $this->_mergeAssociation($entity->get($assoc->property()), $assoc, $value, $options); }; } else { $callback = function ($value, $entity) use($assoc, $nested) { $options = $nested + ['associated' => []]; return $this->_marshalAssociation($assoc, $value, $options); }; } $map[$assoc->property()] = $callback; } $behaviors = $this->_table->behaviors(); foreach ($behaviors->loaded() as $name) { $behavior = $behaviors->get($name); if ($behavior instanceof PropertyMarshalInterface) { $map += $behavior->buildMarshalMap($this, $map, $options); } } return $map; }
/** * Setup * * @return void */ public function setUp() { parent::setUp(); $this->type = Type::build('float'); $this->driver = $this->getMockBuilder('Cake\\Database\\Driver')->getMock(); $this->locale = I18n::locale(); $this->numberClass = FloatType::$numberClass; I18n::locale($this->locale); }
/** * Build the behaviour * * @param array $config Passed configuration * @return void */ public function initialize(array $config) { Type::map('proffer.file', '\\Proffer\\Database\\Type\\FileType'); $schema = $this->_table->schema(); foreach (array_keys($this->config()) as $field) { $schema->columnType($field, 'proffer.file'); } $this->_table->schema($schema); }
/** * Initialize hook * * @param array $config The config for this behavior. * @return void */ public function initialize(array $config) { $this->config(Hash::normalize($config)); Type::map('upload.file', 'Josegonzalez\\Upload\\Database\\Type\\FileType'); $schema = $this->_table->schema(); foreach (array_keys($this->config()) as $field) { $schema->columnType($field, 'upload.file'); } $this->_table->schema($schema); }
/** * __construct * * @param Table $table Table. * @param array $config Config. */ public function __construct(Table $table, array $config = []) { parent::__construct($table, $config); Type::map('Utils.File', 'Utils\\Database\\Type\\FileType'); $schema = $table->schema(); foreach ($this->getFieldList() as $field => $settings) { $schema->columnType($field, 'Utils.File'); } $table->schema($schema); $this->_Table = $table; }
/** * Initialize hook * * @param array $config The config for this behavior * @return void */ public function initialize(array $config) { $this->_initializedConfig = $config; $this->config($config); Type::map('upload.file', 'Dala00\\Upload\\Database\\Type\\FileType'); $schema = $this->_table->schema(); foreach ($config['fields'] as $field => $settings) { $schema->columnType($field, 'upload.file'); } $this->_table->schema($schema); $this->fileSystem(new DefaultFileSystem()); }
/** * Returns an array with the types that require values to * be casted to expressions, out of the list of type names * passed as parameter. * * @param array $types List of type names * @return array */ protected function _requiresToExpressionCasting($types) { $result = []; $types = array_filter($types); foreach ($types as $k => $type) { $object = Type::build($type); if ($object instanceof ExpressionTypeInterface) { $result[$k] = $object; } } return $result; }
/** * {@inheritDoc} * * @return void */ public function lock($by = null, $session = null) { if ($this->isLocked() && $by !== $this->lockOwner()) { throw new LockingException('This entity is already locked'); } $this->set('locked_time', Type::build('datetime')->marshal(time())); if ($by !== null) { $this->set('locked_by', $by); } if ($session !== null) { $this->set('locked_session', $session); } }
/** * Constructor * * Merges config with the default and store in the config property * * @param \Cake\ORM\Table $table The table this behavior is attached to. * @param array $config The config for this behavior. */ public function __construct(Table $table, array $config = []) { if (isset($config['columns']) && is_string($config['columns'])) { $config['columns'] = [$config['columns']]; } parent::__construct($table, $config); if (!Type::map('serialized')) { Type::map('serialized', 'CMS\\Database\\Type\\SerializedType'); } foreach ($this->config('columns') as $column) { $this->_table->schema()->columnType($column, 'serialized'); } }
/** * Build the behaviour * @param array $config Passed configuration * @return void */ public function initialize(array $config) { // get config $config = $this->_config; // load the file type & schema Type::map('unimatrix.file', '\\Unimatrix\\Utility\\Database\\Type\\FileType'); $schema = $this->_table->schema(); // go through each field and change the column type to our file type foreach ($config['fields'] as $field => $path) { $schema->columnType($field . $config['suffix'], 'unimatrix.file'); } // update schema $this->_table->schema($schema); }
/** * Builds the type map * * @param \Cake\Database\TypeMap $typeMap Contains the types to use for converting results * @param \Cake\Database\Driver $driver The driver to use for the type conversion */ public function __construct(TypeMap $typeMap, Driver $driver) { $this->_driver = $driver; $map = $typeMap->toArray(); $types = Type::buildAll(); $result = []; foreach ($types as $k => $type) { if ($type instanceof OptionalConvertInterface && !$type->requiresToPhpCast()) { unset($types[$k]); } } foreach ($map as $field => $type) { if (isset($types[$type])) { $result[$field] = $types[$type]; } } $this->_typeMap = $result; }
/** * JsonableBehavior::initialize() * * @param array $config * @return void */ public function initialize(array $config = []) { Type::map('array', 'Tools\\Database\\Type\\ArrayType'); if (empty($this->_config['fields'])) { throw new Exception('Fields are required'); } if (!is_array($this->_config['fields'])) { $this->_config['fields'] = (array) $this->_config['fields']; } if (!is_array($this->_config['map'])) { $this->_config['map'] = (array) $this->_config['map']; } if (!empty($this->_config['map']) && count($this->_config['fields']) !== count($this->_config['map'])) { throw new Exception('Fields and Map need to be of the same length if map is specified.'); } foreach ($this->_config['fields'] as $field) { $this->_table->schema()->columnType($field, 'array'); } }
/** * Initialize hook * * @param array $config The config for this behavior. * @return void */ public function initialize(array $config) { $configs = []; foreach ($config as $field => $settings) { if (is_int($field)) { $configs[$settings] = []; } else { $configs[$field] = $settings; } } $this->config($configs); $this->config('className', null); Type::map('upload.file', 'Josegonzalez\\Upload\\Database\\Type\\FileType'); $schema = $this->_table->schema(); foreach (array_keys($this->config()) as $field) { $schema->columnType($field, 'upload.file'); } $this->_table->schema($schema); }
/** * @param array $config * @throws \Exception * @return void */ public function initialize(array $config = []) { if (empty($this->_config['fields'])) { throw new Exception('Fields are required'); } if (!is_array($this->_config['fields'])) { $this->_config['fields'] = (array) $this->_config['fields']; } if (!is_array($this->_config['map'])) { $this->_config['map'] = (array) $this->_config['map']; } if (!empty($this->_config['map']) && count($this->_config['fields']) !== count($this->_config['map'])) { throw new Exception('Fields and Map need to be of the same length if map is specified.'); } foreach ($this->_config['fields'] as $field) { $this->_table->schema()->columnType($field, 'array'); } if ($this->_config['encodeParams']['options'] === null) { $options = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_ERROR_INF_OR_NAN | JSON_PARTIAL_OUTPUT_ON_ERROR; $this->_config['encodeParams']['options'] = $options; } Type::map('array', ArrayType::class); }
* Inflector::rules('transliteration', ['/å/' => 'aa']); */ /** * Plugins need to be loaded manually, you can either load them one by one or all of them in a single call * Uncomment one of the lines below, as you need. make sure you read the documentation on Plugin to use more * advanced ways of loading plugins * * Plugin::loadAll(); // Loads all plugins at once * Plugin::load('Migrations'); //Loads a single plugin named Migrations * */ Plugin::load('Migrations'); // Only try to load DebugKit in development mode // Debug Kit should not be installed on a production system if (Configure::read('debug')) { Plugin::load('DebugKit', ['bootstrap' => true]); } /** * Connect middleware/dispatcher filters. */ DispatcherFactory::add('Asset'); DispatcherFactory::add('Routing'); DispatcherFactory::add('ControllerFactory'); /** * Enable default locale format parsing. * This is needed for matching the auto-localized string output of Time() class when parsing dates. */ Type::build('date')->useLocaleParser(); Type::build('datetime')->useLocaleParser(); Plugin::load('BoxManager', ['bootstrap' => false, 'routes' => true]); Plugin::load('SocialManager', ['bootstrap' => false, 'routes' => true]);
/** * Merges `$data` into `$entity` and recursively does the same for each one of * the association names passed in `$options`. When merging associations, if an * entity is not present in the parent entity for a given association, a new one * will be created. * * When merging HasMany or BelongsToMany associations, all the entities in the * `$data` array will appear, those that can be matched by primary key will get * the data merged, but those that cannot, will be discarded. `ids` option can be used * to determine whether the association must use the `_ids` format. * * ### Options: * * - associated: Associations listed here will be marshalled as well. * - validate: Whether or not to validate data before hydrating the entities. Can * also be set to a string to use a specific validator. Defaults to true/default. * - fieldList: A whitelist of fields to be assigned to the entity. If not present * the accessible fields list in the entity will be used. * - accessibleFields: A list of fields to allow or deny in entity accessible fields. * * The above options can be used in each nested `associated` array. In addition to the above * options you can also use the `onlyIds` option for HasMany and BelongsToMany associations. * When true this option restricts the request data to only be read from `_ids`. * * ``` * $result = $marshaller->merge($entity, $data, [ * 'associated' => ['Tags' => ['onlyIds' => true]] * ]); * ``` * * @param \Cake\Datasource\EntityInterface $entity the entity that will get the * data merged in * @param array $data key value list of fields to be merged into the entity * @param array $options List of options. * @return \Cake\Datasource\EntityInterface */ public function merge(EntityInterface $entity, array $data, array $options = []) { list($data, $options) = $this->_prepareDataAndOptions($data, $options); $propertyMap = $this->_buildPropertyMap($options); $isNew = $entity->isNew(); $keys = []; if (!$isNew) { $keys = $entity->extract((array) $this->_table->primaryKey()); } if (isset($options['accessibleFields'])) { foreach ((array) $options['accessibleFields'] as $key => $value) { $entity->accessible($key, $value); } } $errors = $this->_validate($data + $keys, $options, $isNew); $schema = $this->_table->schema(); $properties = $marshalledAssocs = []; foreach ($data as $key => $value) { if (!empty($errors[$key])) { if ($entity instanceof InvalidPropertyInterface) { $entity->invalid($key, $value); } continue; } $columnType = $schema->columnType($key); $original = $entity->get($key); if (isset($propertyMap[$key])) { $assoc = $propertyMap[$key]['association']; $value = $this->_mergeAssociation($original, $assoc, $value, $propertyMap[$key]); $marshalledAssocs[$key] = true; } elseif ($columnType) { $converter = Type::build($columnType); $value = $converter->marshal($value); $isObject = is_object($value); if (!$isObject && $original === $value || $isObject && $original == $value) { continue; } } $properties[$key] = $value; } if (!isset($options['fieldList'])) { $entity->set($properties); $entity->errors($errors); foreach (array_keys($marshalledAssocs) as $field) { if ($properties[$field] instanceof EntityInterface) { $entity->dirty($field, $properties[$field]->dirty()); } } return $entity; } foreach ((array) $options['fieldList'] as $field) { if (array_key_exists($field, $properties)) { $entity->set($field, $properties[$field]); if ($properties[$field] instanceof EntityInterface && isset($marshalledAssocs[$field])) { $entity->dirty($field, $properties[$field]->dirty()); } } } $entity->errors($errors); return $entity; }
/** * Test setting instances into the factory/registry. * * @return void */ public function testSet() { $instance = $this->getMock('Cake\\Database\\Type'); Type::set('random', $instance); $this->assertSame($instance, Type::build('random')); }
/** * Setup * * @return void */ public function setUp() { parent::setUp(); $this->type = Type::build('date'); $this->driver = $this->getMock('Cake\\Database\\Driver'); }
/** * Marshalls flat data into PHP objects. * * @param mixed $value The value to convert * @param string $type Type identifier, `integer`, `float`, etc * @return mixed Converted value */ public function marshal($value, $type) { return Type::build($type)->marshal($value); }
/** * Setup * * @return void */ public function setUp() { parent::setUp(); $this->type = Type::build('string'); $this->driver = $this->getMockBuilder('Cake\\Database\\Driver')->getMock(); }
/** * Generate a primary key value for a new record. * * By default, this uses the type system to generate a new primary key * value if possible. You can override this method if you have specific requirements * for id generation. * * @param array $primary The primary key columns to get a new ID for. * @return mixed Either null or the new primary key value. */ protected function _newId($primary) { if (!$primary || count((array) $primary) > 1) { return null; } $typeName = $this->schema()->columnType($primary[0]); $type = Type::build($typeName); return $type->newId(); }
* Uncomment one of the lines below, as you need. make sure you read the documentation on Plugin to use more * advanced ways of loading plugins * * Plugin::loadAll(); // Loads all plugins at once * Plugin::load('Migrations'); //Loads a single plugin named Migrations * */ Plugin::load('Migrations'); // Only try to load DebugKit in development mode // Debug Kit should not be installed on a production system if (Configure::read('debug')) { Plugin::load('DebugKit', ['bootstrap' => true]); } /** * Connect middleware/dispatcher filters. */ DispatcherFactory::add('Asset'); DispatcherFactory::add('Routing'); DispatcherFactory::add('ControllerFactory'); /** * Enable immutable time objects in the ORM. * * You can enable default locale format parsing by adding calls * to `useLocaleParser()`. This enables the automatic conversion of * locale specific date formats. For details see * @link http://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#parsing-localized-datetime-data */ Type::build('time')->useImmutable(); Type::build('date')->useImmutable(); Type::build('datetime')->useImmutable(); Plugin::load('AkkaFacebook', ['bootstrap' => false, 'routes' => true]);
public function mentionToDB() { $this->autoRender = false; $this->Markers = TableRegistry::get('Markers'); // first get the latest twitID from DB $getLatestTwitID = $this->Markers->find()->select(['twitID'])->where(['active' => true, 'twitID IS NOT' => null])->order(['twitID' => 'DESC'])->first(); if ($getLatestTwitID['twitID'] > 0) { $latestTwitID = $getLatestTwitID['twitID']; } else { //$latestTwitID = 642008117992001536;//first test twit mentioning @macetsurabaya $latestTwitID = 1; } // second grab twit $dataStream = $this->getMention($latestTwitID, 800); $countDataStream = count($dataStream); $dataToDisplay = []; // @todo better to return no data message after if ($countDataStream > 0) { foreach ($dataStream as $data) { if ($data['place'] !== null) { $isTwitExists = $this->Markers->exists(['twitID' => $data['id'], 'active' => 1]); if (!$isTwitExists) { //$dataToDisplay[] = $data; //if geo located, insert to DB //first get respondent_id $respondent_id = $this->findToSaveRespondent($data['user']['id'], $data['user']['name'], $data['user']['screen_name']); $info = trim(str_replace('@dimanamacetid', '', $data['text'])); $created_at = date("Y-m-d H:i:s", strtotime($data['created_at'])); Type::build('datetime')->useLocaleParser(); //cakephp need this to save datetime field $dataToSave = ['category_id' => 1, 'user_id' => 4, 'respondent_id' => $respondent_id, 'weather_id' => 1, 'twitID' => $data['id'], 'twitTime' => new Time($created_at), 'twitURL' => null, 'twitPlaceID' => $data['place']['id'], 'twitPlaceName' => $data['place']['name'], 'isTwitPlacePrecise' => 0, 'twitImage' => null, 'pinned' => 0, 'cleared' => 0, 'active' => 1]; // if image do exists if (array_key_exists('extended_entities', $data) && array_key_exists('media', $data['extended_entities']) && $data['extended_entities']['media'][0]['type'] == 'photo') { $dataToSave['twitImage'] = $data['extended_entities']['media'][0]['media_url_https']; } // if url do exists $twitURL = $this->findURLonText($info); if ($twitURL !== null) { $dataToSave['twitURL'] = $twitURL; $info = str_ireplace($twitURL, "", $info); $info = trim($info); } $dataToSave['info'] = $info; // category_id and weather_id based on twit $twitHashtagCategoryWeather = $this->findHashtagonText($info); $dataToSave['category_id'] = $twitHashtagCategoryWeather[0]; $dataToSave['weather_id'] = $twitHashtagCategoryWeather[1]; //$dataToSave['info'] = $twitHashtagCategoryWeather[2]; // if get precise location if ($data['geo'] !== null) { $dataToSave['lat'] = $data['geo']['coordinates'][0]; $dataToSave['lng'] = $data['geo']['coordinates'][1]; $dataToSave['isTwitPlacePrecise'] = 1; } else { $dataToSave['lat'] = $data['place']['bounding_box']['coordinates'][0][0][1]; $dataToSave['lng'] = $data['place']['bounding_box']['coordinates'][0][0][0]; } //$dataToDisplay[] = $dataToSave; //save marker $marker = $this->Markers->newEntity($dataToSave); $this->Markers->save($marker); } } } } /*$this->set([ 'latestTwitID' => $getLatestTwitID, 'data' => $dataToDisplay, 'meta' => $countDataStream, '_serialize' => ['latestTwitID', 'data', 'meta'] ]);*/ }
/** * Plugins need to be loaded manually, you can either load them one by one or all of them in a single call * Uncomment one of the lines below, as you need. make sure you read the documentation on Plugin to use more * advanced ways of loading plugins * * Plugin::loadAll(); // Loads all plugins at once * Plugin::load('Migrations'); //Loads a single plugin named Migrations * */ Plugin::load('Migrations'); // Only try to load DebugKit in development mode // Debug Kit should not be installed on a production system if (Configure::read('debug')) { Plugin::load('DebugKit', ['bootstrap' => true]); } /** * Connect middleware/dispatcher filters. */ DispatcherFactory::add('Asset'); DispatcherFactory::add('Routing'); DispatcherFactory::add('ControllerFactory'); /** * Enable default locale format parsing. * This is needed for matching the auto-localized string output of Time() class when parsing dates. * * Also enable immutable time objects in the ORM. */ Type::build('time')->useImmutable()->useLocaleParser(); Type::build('date')->useImmutable()->useLocaleParser(); Type::build('datetime')->useImmutable()->useLocaleParser();