public function testIfTwoInstancesOfManganHaveProperConnections() { // Default $mangan = new Mangan(); $this->assertSame($mangan->dbName, ManganFirstDbName); $this->assertInstanceOf(MongoDB::class, $mangan->getDbInstance(), 'That first connection is active'); // Second $second = new Mangan('second'); $this->assertSame($second->dbName, ManganSecondDbName); $this->assertInstanceOf(MongoDB::class, $second->getDbInstance(), 'That second connection is active'); }
public function __construct($scenario = 'insert', $lang = '') { parent::__construct($scenario, $lang); $this->_id = new MongoId(); $mangan = Mangan::fromModel($this); $this->_db = $mangan->getDbInstance(); }
/** * Finds all documents satisfying the specified condition. * See {@link find()} for detailed explanation about $condition and $params. * * @param array|CriteriaInterface $criteria query criteria. * @return AnnotatedInterface[]|Cursor */ public function findAll($criteria = null) { if ($this->_beforeFind()) { $criteria = $this->sm->apply($criteria); $criteria->decorateWith($this->model); $cursor = $this->em->getCollection()->find($criteria->getConditions()); if ($criteria->getSort() !== null) { $cursor->sort($criteria->getSort()); } if ($criteria->getLimit() !== null) { $cursor->limit($criteria->getLimit()); } if ($criteria->getOffset() !== null) { $cursor->skip($criteria->getOffset()); } if ($criteria->getSelect()) { $cursor->fields($criteria->getSelect()); } $this->mn->getProfiler()->cursor($cursor); if ($this->_useCursor) { return new Cursor($cursor, $this->model); } else { return $this->populateRecords($cursor); } } return []; }
public static function create(DocumentPropertyMeta $meta, DocumentTypeMeta $modelMeta, $transformatorClass) { $sanitizerClass = self::_resolve($meta, $modelMeta); // Remap sanitizer if needed $mapConfig = []; $map = Mangan::fly($modelMeta->connectionId)->sanitizersMap; if (isset($map[$transformatorClass]) && isset($map[$transformatorClass][$sanitizerClass])) { $mapConfig = $map[$transformatorClass][$sanitizerClass]; if (is_string($mapConfig)) { $mapClass = $mapConfig; $mapConfig = ['class' => $mapClass]; } } if (is_array($meta->sanitizer)) { $sanitizerConfig = $meta->sanitizer; $sanitizerConfig['class'] = $sanitizerClass; } else { $sanitizerConfig = []; $sanitizerConfig['class'] = $sanitizerClass; } if (!empty($mapConfig)) { $sanitizerConfig = array_merge($sanitizerConfig, $mapConfig); } // Sanitize as array if ($meta->sanitizeArray) { $sanitizerConfig = ['class' => ArraySanitizer::class, 'sanitizer' => $sanitizerConfig]; } $config = [$transformatorClass => [$sanitizerConfig]]; $sanitizer = PluginFactory::fly($modelMeta->connectionId)->instance($config, $transformatorClass)[0]; return $sanitizer; }
/** * Create validator based on config. * @param AnnotatedInterface $model * @param ValidatorMeta $validatorMeta * @return ValidatorInterface Validator instance */ public static function create(AnnotatedInterface $model, ValidatorMeta $validatorMeta, $fieldName = null) { $mn = Mangan::fromModel($model); // Resolve validator class if ($validatorMeta->proxy && empty($validatorMeta->class)) { if (isset($mn->validators[$validatorMeta->proxy])) { $validatorMeta->class = $mn->validators[$validatorMeta->proxy]; } else { if (empty($fieldName)) { $fieldName = '<not provided>'; } $args = [get_class($model), $validatorMeta->proxy, $fieldName]; $msg = vsprintf("Could not resolve validator class from proxy. For model `%s`. Proxy class: `%s`. Model field: `%s`", $args); throw new InvalidArgumentException($msg); } } if (empty($validatorMeta->class)) { $args = [get_class($model)]; $msg = vsprintf("Empty validator class for model `%s`", $args); throw new InvalidArgumentException($msg); } $config = (array) $validatorMeta; unset($config['proxy']); $di = $mn->getDi(); return $di->apply($config); }
public function testIfManganHasProperlyConfiguredFilters() { $model = new ExplicitlyNonIndexableField(); // Check if mangan has properly configured filters $mangan = Mangan::fromModel($model); $filterConfig = $mangan->filters; $this->assertTrue(array_key_exists(SearchArray::class, $filterConfig), 'That SearchArray filters are configured'); $this->assertTrue(in_array(SearchFilter::class, $filterConfig[SearchArray::class]), 'That SearchFilter is configured'); }
public static function toModel($transformerClass, AnnotatedInterface $model) { $plugins = PluginFactory::fly()->instance(Mangan::fromModel($model)->finalizers, $transformerClass, ModelFinalizerInterface::class); foreach ($plugins as $finalizer) { /* @var $finalizer ArrayFinalizerInterface */ $finalizer->toModel($model); } return $model; }
public function call($command, $arguments = []) { $arg = $this->model ? CollectionNamer::nameCollection($this->model) : true; $cmd = [$command => $arg]; if (is_array($arguments) && count($arguments)) { $cmd = array_merge($cmd, $arguments); } $result = $this->mn->getDbInstance()->command($cmd); if (array_key_exists('errmsg', $result) && array_key_exists('ok', $result) && $result['ok'] == 0) { if (array_key_exists('bad cmd', $result)) { $badCmd = key($result['bad cmd']); if ($badCmd == $command) { throw new CommandNotFoundException(sprintf('Command `%s` not found', $command)); } } throw new CommandException(sprintf('Could not execute command `%s`, mongo returned: "%s"', $command, $result['errmsg'])); } return $result; }
public function __construct($model) { // This is to use get/set foreach ($this->_getOptionNames() as $name) { PropertyMaker::defineProperty($this, $name, $this->_defaults); } foreach (ManganMeta::create($model)->type()->clientFlags as $name => $value) { $this->_values[$name] = $value; } $this->_mangan = Mangan::fromModel($model); }
/** * Get filters for connection and transformator class * @param string $connectionId * @param string $transformatorClass * @return TransformatorFilterInterface[] */ private static function getManganFilters($connectionId, $transformatorClass) { if (!isset(self::$_configs[$connectionId])) { self::$_configs[$connectionId] = []; } if (!isset(self::$_configs[$connectionId][$transformatorClass])) { self::$_configs[$connectionId] = []; self::$_configs[$connectionId][$transformatorClass] = []; $mangan = Mangan::fly($connectionId); $tranformator = new $transformatorClass(); foreach ($mangan->filters as $implementer => $filterClasses) { foreach ($filterClasses as $filterClass) { if ($tranformator instanceof $implementer) { self::$_configs[$connectionId][$transformatorClass][] = new $filterClass(); } } } } return self::$_configs[$connectionId][$transformatorClass]; }
public function index() { if (!$this->isIndexable) { return; } // NOTE: Transformer must ensure that _id is string, not MongoId $body = SearchArray::fromModel($this->model); if (array_key_exists('_id', $body)) { $config = Mangan::fromModel($this->model)->sanitizersMap; if (!array_key_exists(SearchArray::class, $config)) { throw new UnexpectedValueException(sprintf('Mangan is not properly configured for Manganel. Signals must be generated or add configuration manually from `%s::getDefault()`', ConfigManager::class)); } else { throw new UnexpectedValueException(sprintf('Cannot index `%s`, as it contains _id field. Either use MongoObjectId sanitizer on it, or rename.', get_class($this->model))); } } // In some cases $value *might* still be mongoId type, // see https://github.com/Maslosoft/Addendum/issues/43 $func = function ($value) { if ($value instanceof MongoId) { return (string) $value; } return $value; }; $filtered = filter_var($body, \FILTER_CALLBACK, ['options' => $func]); // Create proper elastic search request array $params = ['body' => $filtered]; try { $this->getClient()->index($this->getParams($params)); } catch (BadRequest400Exception $e) { // Throw previous exception, // as it holds more meaningfull information $previous = $e->getPrevious(); $message = sprintf('Exception while indexing `%s`@`%s`: %s', get_class($this->model), $this->manganel->indexId, $previous->getMessage()); throw new BadRequest400Exception($message); } }
use Maslosoft\Mangan\Transformers\YamlArray; use Maslosoft\Manganel\Manganel; use Maslosoft\Manganel\SearchArray; use Maslosoft\Signals\Signal; date_default_timezone_set('Europe/Paris'); define('VENDOR_DIR', __DIR__ . '/../../..'); define('YII_DIR', VENDOR_DIR . '/yiisoft/yii/framework/'); require VENDOR_DIR . '/autoload.php'; // Invoker stub for windows if (defined('PHP_WINDOWS_VERSION_MAJOR')) { require __DIR__ . '/../misc/Invoker.php'; } //require $yii = YII_DIR . 'yii.php'; //require_once YII_DIR . 'base/CComponent.php'; //require_once YII_DIR . 'base/CModel.php'; $config = (require __DIR__ . '/../config.php'); $signals = new Signal(); $sMap = [JsonArray::class => [MongoObjectId::class => MongoWriteStringId::class, DateSanitizer::class => DateWriteUnixSanitizer::class], SearchArray::class => [MongoObjectId::class => MongoWriteStringId::class, DateSanitizer::class => DateWriteUnixSanitizer::class], YamlArray::class => [MongoObjectId::class => MongoWriteStringId::class, DateSanitizer::class => DateWriteUnixSanitizer::class]]; $mangan = Mangan::fly(); $mangan->connectionString = 'mongodb://localhost:27017'; $mangan->dbName = 'ManganTest'; $mangan->sanitizersMap = $sMap; $mangan->init(); $mangan2 = Mangan::fly('second'); $mangan2->connectionString = 'mongodb://localhost:27017'; $mangan2->dbName = 'ManganTestSecond'; $mangan2->sanitizersMap = $sMap; $mangan2->init(); $manganel = Manganel::fly(); $manganel->index = strtolower($mangan->dbName); $manganel->hosts = ['localhost:9200'];
public function testIfWillDeleteEmbeddedImage() { $fileName = __DIR__ . '/logo-1024.png'; $md5 = md5_file($fileName); // NOTE: Must work fine even if _id is not set $model = new ModelWithEmbeddedImage(); $model->file = new Image(); $model->file->set($fileName); $em = new EntityManager($model); $em->save(); $finder = new Finder($model); $found = $finder->findByPk($model->_id); /* @var $found ModelWithEmbeddedImage */ $file = $found->file->get()->getBytes(); $this->assertSame($md5, md5($file)); // Resize image $params = new ImageParams(); $params->width = 100; $params->height = 100; $resized = $found->file->get($params)->getBytes(); // Check if was resized $this->assertTrue($file > $resized); $mangan = new Mangan(); $gfs = $mangan->getDbInstance()->getGridFS(); $tmp = $mangan->getDbInstance()->getGridFS(File::TmpPrefix); $criteria = ['parentId' => $found->file->_id]; $this->assertSame(1, $gfs->count($criteria)); $this->assertSame(1, $tmp->count($criteria)); $deleted = $found->delete(); $this->assertTrue($deleted); $this->assertSame(0, $gfs->count($criteria)); $this->assertSame(0, $tmp->count($criteria)); }
//exit; // Invoker stub for windows if (defined('PHP_WINDOWS_VERSION_MAJOR')) { require __DIR__ . '/../misc/Invoker.php'; } $config = (require __DIR__ . '/../config.php'); $addendum = new Addendum(); $addendum->namespaces[] = MetaOptionsHelper::Ns; $addendum->namespaces[] = ValidatorAnnotation::Ns; $addendum->init(); const ManganFirstDbName = 'ManganTest'; const ManganSecondDbName = 'ManganTestSecond'; const ManganThirdDbName = 'ManganTestThird'; const ManganCustomValidatorsDbName = 'ManganTestCustomValidators'; $mangan = new Mangan(); $mangan->connectionString = 'mongodb://localhost:27017'; $mangan->dbName = ManganFirstDbName; $mangan->init(); $mangan2 = new Mangan('second'); $mangan2->connectionString = 'mongodb://localhost:27017'; $mangan2->dbName = ManganSecondDbName; $mangan2->init(); $mangan3 = new Mangan('tokumx'); $mangan3->connectionString = 'mongodb://localhost:27017'; $mangan3->dbName = ManganThirdDbName; $mangan3->init(); $mangan4 = new Mangan('custom-validators'); $mangan4->connectionString = 'mongodb://localhost:27017'; $mangan4->dbName = ManganCustomValidatorsDbName; $mangan4->validators[RequiredProxy::class] = RequiredValidator::class; $mangan4->init();
/** * Profile cursor * @param MongoCursor $cursor */ public function cursor(MongoCursor $cursor) { $this->mangan->getLogger()->info(var_export($cursor->explain(), true)); }
public function __construct(AnnotatedInterface $model = null) { parent::__construct($model); $this->available = new CommandProxyStorage($this, Mangan::fromModel($model)->connectionId); }
/** * Create entity manager * @param AnnotatedInterface $model * @param Mangan $mangan * @throws ManganException */ public function __construct(AnnotatedInterface $model, Mangan $mangan = null) { $this->model = $model; $this->sm = new ScopeManager($model); $this->options = new EntityOptions($model); $this->collectionName = CollectionNamer::nameCollection($model); $this->meta = ManganMeta::create($model); $this->validator = new Validator($model); if (null === $mangan) { $mangan = Mangan::fromModel($model); } if (!$this->collectionName) { throw new ManganException(sprintf('Invalid collection name for model: `%s`', $this->meta->type()->name)); } $this->_collection = new MongoCollection($mangan->getDbInstance(), $this->collectionName); }