Esempio n. 1
0
 public function testErrors()
 {
     $form = Form::create()->add(Primitive::ternary('flag')->setFalseValue('0')->setTrueValue('1'))->add(Primitive::integer('old')->required())->addRule('someRule', Expression::between(FormField::create('old'), '18', '35'));
     //empty import
     $form->import(array())->checkRules();
     //checking
     $expectingErrors = array('old' => Form::MISSING, 'someRule' => Form::WRONG);
     $this->assertEquals($expectingErrors, $form->getErrors());
     $this->assertEquals(Form::MISSING, $form->getError('old'));
     $this->assertEquals(Form::WRONG, $form->getError('someRule'));
     $this->assertTrue($form->hasError('old'));
     $this->assertFalse($form->hasError('flag'));
     //drop errors
     $form->dropAllErrors();
     $this->assertEquals(array(), $form->getErrors());
     //import wrong data
     $form->clean()->importMore(array('flag' => '3', 'old' => '17'))->checkRules();
     //checking
     $expectingErrors = array('flag' => Form::WRONG, 'someRule' => Form::WRONG);
     $this->assertEquals($expectingErrors, $form->getErrors());
     $this->assertTrue($form->hasError('someRule'));
     //marking good and custom check errors
     $form->markGood('someRule')->markCustom('flag', 3);
     $this->assertEquals(array('flag' => 3), $form->getErrors());
     $this->assertFalse($form->hasError('someRule'));
     $this->assertNull($form->getError('someRule'));
     $this->assertEquals(3, $form->getError('flag'));
     //import right data
     $form->dropAllErrors()->clean()->importMore(array('flag' => '1', 'old' => '35'));
     //checking
     $this->assertEquals(array(), $form->getErrors());
 }
 /**
  * @group pi
  */
 public function testCustomImportExport()
 {
     $dbs = DBTestPool::me()->getPool();
     if (empty($dbs)) {
         $this->fail('For test required at least one DB in config');
     }
     DBPool::me()->setDefault(reset($dbs));
     $moscow = TestCity::create()->setCapital(true)->setName('Moscow');
     $moscow->dao()->add($moscow);
     $stalingrad = TestCity::create()->setCapital(false)->setName('Stalingrad');
     $stalingrad->dao()->add($stalingrad);
     $prms = array();
     $prms[] = Primitive::identifier('city')->setScalar(true)->of('TestCity')->setMethodName('PrimitiveIdentifierTest::getCityByName')->setExtractMethod('PrimitiveIdentifierTest::getCityName');
     $prms[] = Primitive::identifier('city')->setScalar(true)->of('TestCity')->setMethodName(array(get_class($this), 'getCityByName'))->setExtractMethod(function (TestCity $city) {
         return $city->getName();
     });
     foreach ($prms as $prm) {
         $prm->import(array('city' => 'Moscow'));
         $this->assertEquals($moscow, $prm->getValue());
         $this->assertEquals('Moscow', $prm->exportValue());
         $prm->importValue($stalingrad);
         $this->assertequals($stalingrad, $prm->getValue());
         $this->assertequals('Stalingrad', $prm->exportValue());
         $prm->import(array('city' => $moscow));
         $this->assertEquals($moscow, $prm->getValue());
         $this->assertEquals('Moscow', $prm->exportValue());
     }
 }
 public function testImport()
 {
     $prm = Primitive::string('name');
     $nullValues = array(null, '');
     foreach ($nullValues as $value) {
         $this->assertNull($prm->importValue($value));
     }
     $prm->clean();
     $falseValues = array(array(), true, false, $prm);
     foreach ($falseValues as $value) {
         $this->assertFalse($prm->importValue($value));
     }
     $prm->clean();
     $trueValues = array('some string', -100500, 2011.09);
     foreach ($trueValues as $value) {
         $this->assertTrue($prm->importValue($value));
     }
     $prm->setAllowedPattern(PrimitiveString::MAIL_PATTERN);
     $prm->clean();
     $trueValues = array('*****@*****.**', '*****@*****.**', '*****@*****.**');
     foreach ($trueValues as $value) {
         $this->assertTrue($prm->importValue($value));
     }
     $prm->clean();
     $falseValues = array('example.com', 100500, 2012.04);
     foreach ($falseValues as $value) {
         $this->assertFalse($prm->importValue($value));
     }
 }
 /**
  * @param scalar[] $data_
  * @param string $type_
  *
  * @return mixed
  */
 public function hydrateForType($type_, array $data_)
 {
     $object = new $type_();
     if ($object instanceof Object_Mappable) {
         $properties = $object->properties();
     } else {
         $properties = Object_Properties::forType($type_);
     }
     foreach ($properties->propertyNames() as $propertyName) {
         /* @var $property \Components\Object_Property */
         $property = $properties->{$propertyName};
         if (false === isset($data_[$property->nameMapped])) {
             continue;
         }
         $t = $property->type;
         if (Primitive::isNative($t)) {
             $object->{$property} = $data_[$property->nameMapped];
         } else {
             $o = new \ReflectionClass($t);
             if ($o->isSubclassOf('Components\\Value')) {
                 $object->{$property} = $t::valueOf($data_[$property->nameMapped]);
             }
         }
     }
     // TODO Recursive mapping ...
     return $object;
 }
 /**
  * Install hstore
  * /usr/share/postgresql/contrib # cat hstore.sql | psql -U pgsql -d onphp
  **/
 public function testHstore()
 {
     foreach (DBTestPool::me()->getPool() as $connector => $db) {
         DBPool::me()->setDefault($db);
         $properties = array('age' => '23', 'weight' => 80, 'comment' => null);
         $user = TestUser::create()->setCity($moscow = TestCity::create()->setName('Moscow'))->setCredentials(Credentials::create()->setNickname('fake')->setPassword(sha1('passwd')))->setLastLogin(Timestamp::create(time()))->setRegistered(Timestamp::create(time())->modify('-1 day'))->setProperties(Hstore::make($properties));
         $moscow = TestCity::dao()->add($moscow);
         $user = TestUser::dao()->add($user);
         Cache::me()->clean();
         TestUser::dao()->dropIdentityMap();
         $user = TestUser::dao()->getById('1');
         $this->assertInstanceOf('Hstore', $user->getProperties());
         $this->assertEquals($properties, $user->getProperties()->getList());
         $form = TestUser::proto()->makeForm();
         $form->get('properties')->setFormMapping(array(Primitive::string('age'), Primitive::integer('weight'), Primitive::string('comment')));
         $form->import(array('id' => $user->getId()));
         $this->assertNotNull($form->getValue('id'));
         $object = $user;
         FormUtils::object2form($object, $form);
         $this->assertInstanceOf('Hstore', $form->getValue('properties'));
         $this->assertEquals(array_filter($properties), $form->getValue('properties')->getList());
         $subform = $form->get('properties')->getInnerForm();
         $this->assertEquals($subform->getValue('age'), '23');
         $this->assertEquals($subform->getValue('weight'), 80);
         $this->assertNull($subform->getValue('comment'));
         $user = new TestUser();
         FormUtils::form2object($form, $user, false);
         $this->assertEquals($user->getProperties()->getList(), array_filter($properties));
     }
 }
 /**
  * @test
  */
 public function privilegedPortInvalid()
 {
     $form = Form::create()->add(Primitive::httpUrl("url")->setCheckPrivilegedPorts());
     $form->import(array('url' => $this->urlWithPrivilegedPort));
     $errors = $form->getErrors();
     $this->assertTrue(isset($errors["url"]));
     $this->assertEquals(Form::WRONG, $errors["url"]);
 }
Esempio n. 7
0
 /**
  * @param array $data Data.
  */
 public function __construct($data)
 {
     parent::__construct();
     $this->data = E()->Utils->convertFieldNames($data, 'site_');
     if (is_null(self::$isPropertiesTableExists)) {
         self::$isPropertiesTableExists = $this->dbh->tableExists('share_sites_properties');
     }
 }
 static function __static()
 {
     self::$STRING = new self('string');
     self::$INTEGER = self::$INT = new self('int');
     self::$DOUBLE = new self('double');
     self::$BOOLEAN = self::$BOOL = new self('bool');
     self::$ARRAY = new self('array');
 }
Esempio n. 9
0
 /**
  * @param bool|int $id User ID.
  */
 public function __construct($id = false)
 {
     parent::__construct();
     $this->id = $id;
     $this->userGroup = E()->UserGroup;
     //Если пользователь существует  - загружаем его информацию
     if ($this->id) {
         $this->loadInfo($this->id);
     }
 }
 public function testGetList()
 {
     $primitive = Primitive::enum('enum')->of('MimeType');
     $enum = MimeType::wrap(1);
     $this->assertEquals($primitive->getList(), MimeType::getObjectList());
     $primitive->setDefault($enum);
     $this->assertEquals($primitive->getList(), MimeType::getObjectList());
     $primitive->import(array('enum' => MimeType::getAnyId()));
     $this->assertEquals($primitive->getList(), MimeType::getObjectList());
 }
 public function testGetList()
 {
     $primitive = Primitive::enumeration('enum')->of('DataType');
     $enum = DataType::create(DataType::getAnyId());
     $this->assertEquals($primitive->getList(), $enum->getObjectList());
     $primitive->setDefault($enum);
     $this->assertEquals($primitive->getList(), $enum->getObjectList());
     $primitive->import(array('enum' => DataType::getAnyId()));
     $this->assertEquals($primitive->getList(), $enum->getObjectList());
 }
 public function testSingle()
 {
     $prm = Primitive::timestamp('test')->setSingle();
     $array = array('test' => '1234-01-02 17:38:59');
     $this->assertTrue($prm->import($array));
     $this->assertTrue($prm->getValue()->getYear() == 1234);
     $array = array('test' => '1975-01-02 17:38:59');
     $this->assertTrue($prm->import($array));
     $this->assertEquals($prm->getValue()->toDateTime(), '1975-01-02 17:38.59');
 }
Esempio n. 13
0
 public function __construct($_ = [])
 {
     if (is_array($_) != true) {
         throw new \Exception();
     }
     $_ = array_map(function ($_) {
         return primval($_);
     }, $_);
     parent::__construct($_);
 }
 public function testInet()
 {
     $prm = Primitive::inet('inet');
     $this->assertTrue($prm->importValue('127.0.0.1'));
     $this->assertTrue($prm->importValue('254.254.254.254'));
     $this->assertTrue($prm->importValue('0.0.0.0'));
     $this->assertFalse($prm->importValue('10.0.0'));
     $this->assertFalse($prm->importValue('42.42.42.360'));
     $this->assertFalse($prm->importValue('10.0.256'));
 }
 public function __construct($type_)
 {
     if (null === ($native = Primitive::asNative($type_))) {
         $this->m_type = $type_;
         $this->m_isPrimitive = false;
     } else {
         $this->m_type = $native;
         $this->m_isPrimitive = true;
     }
 }
Esempio n. 16
0
 public function __construct()
 {
     parent::__construct();
     /*
      * Загружаем инфомацию о группах пользователей в структуру вида:
      *     array(
      *         $group_id => array(group info)
      *     );
      */
     $this->groups = convertDBResult($this->dbh->select('user_groups'), 'group_id', true);
 }
 public function testImport()
 {
     $prm = Primitive::time('test')->setSingle(true)->setMax(Time::create('00:12:00'))->setMin(Time::create('00:10:00'));
     $array = array(0 => array('test' => '00:12:01'), 1 => array('test' => '00:14:00'), 2 => array('test' => '00:09:59'), 3 => array('test' => '00:11:00'), 4 => array('test' => '00:10:00'), 5 => array('test' => '00:12:00'));
     $this->assertFalse($prm->import($array[0]));
     $this->assertFalse($prm->import($array[1]));
     $this->assertFalse($prm->import($array[2]));
     $this->assertTrue($prm->import($array[3]));
     $this->assertTrue($prm->import($array[4]));
     $this->assertTrue($prm->import($array[5]));
 }
 public function chooseAction(HttpRequest $request)
 {
     $action = Primitive::choice('action')->setList($this->methodMap);
     if ($this->getDefaultAction()) {
         $action->setDefault($this->getDefaultAction());
     }
     Form::create()->add($action)->import($request->getGet())->importMore($request->getPost())->importMore($request->getAttached());
     if (!($command = $action->getValue())) {
         return $action->getDefault();
     }
     return $command;
 }
 public function __construct(Prototyped $subject)
 {
     $this->subject = $subject;
     $form = $this->subject->proto()->makeForm()->add(Primitive::choice('action')->setList($this->commandMap)->setDefault($this->defaultAction));
     if ($this->idFieldName) {
         $form->add(Primitive::alias($this->idFieldName, $form->get('id')));
     }
     $this->map = MappedForm::create($form)->addSource('id', RequestType::get())->addSource('action', RequestType::get())->setDefaultType(RequestType::post());
     if ($this->idFieldName) {
         $this->map->addSource($this->idFieldName, RequestType::get());
     }
 }
 public function testCustomError()
 {
     $realPrimitive = new PrimitiveCustomError('customError');
     $realPrimitive->setMax(1);
     $form = Form::create()->add($realPrimitive)->add(Primitive::alias('alias', $realPrimitive))->import(array('alias' => 'Toooo long'));
     $errors = $form->getErrors();
     $this->assertTrue(isset($errors['alias']));
     $this->assertEquals(PrimitiveCustomError::CUSTOM_MARK, $errors['alias']);
     $form->clean()->dropAllErrors()->import(array('customError' => 'Toooo long'));
     $errors = $form->getErrors();
     $this->assertTrue(isset($errors['customError']));
     $this->assertEquals(PrimitiveCustomError::CUSTOM_MARK, $errors['customError']);
 }
 public function testOf()
 {
     $prm = Primitive::clazz('name');
     try {
         $prm->of('InExIsNaNtClass');
         $this->fail();
     } catch (WrongArgumentException $e) {
         // pass
     }
     $this->assertFalse($prm->of('Enumeration')->importValue('IdentifiableObject'));
     $this->assertTrue($prm->of('Identifiable')->importValue('IdentifiableObject'));
     $this->assertTrue($prm->of('IdentifiableObject')->importValue('IdentifiableObject'));
 }
Esempio n. 22
0
 /**
  * @copydoc DBWorker::__construct
  *
  * @throws SystemException 'ERR_NO_LANG_INFO'
  */
 public function __construct()
 {
     parent::__construct();
     // получаем все языки, определённые в системе
     $res = $this->dbh->select('share_languages', true, null, array('lang_order_num' => QAL::ASC));
     if (!$res) {
         throw new SystemException('ERR_NO_LANG_INFO', SystemException::ERR_CRITICAL, $this->dbh->getLastRequest());
     }
     // формируем набор языков вида array(langID => langInfo)
     foreach ($res as $langInfo) {
         $this->languages[$langInfo['lang_id']] = $langInfo;
         unset($this->languages[$langInfo['lang_id']]['lang_id']);
     }
 }
Esempio n. 23
0
 /**
  * @param DataDescription $dataDescription Data description.
  * @param Data $data Data.
  * @param string $tableName Table name.
  */
 public function __construct(DataDescription $dataDescription, Data $data, $tableName)
 {
     parent::__construct();
     if ($this->isActive = $this->dbh->tableExists($this->tableName = $tableName . '_tags')) {
         $this->dataDescription = $dataDescription;
         $this->data = $data;
         foreach ($this->dataDescription as $fd) {
             if ($fd->getPropertyValue('key')) {
                 $this->pk = $fd;
                 break;
             }
         }
     }
 }
 public function testEmpty()
 {
     $prm = Primitive::identifier('name')->of('TestCity');
     $nullValues = array(null, '');
     foreach ($nullValues as $value) {
         $this->assertNull($prm->import(array('name' => $value)));
         $this->assertNull($prm->importValue($value));
     }
     $emptyValues = array(0, '0', false);
     foreach ($emptyValues as $value) {
         $this->assertFalse($prm->import(array('name' => $value)));
         $this->assertFalse($prm->importValue($value));
     }
 }
 public function testImport()
 {
     $prm = Primitive::string('name');
     $nullValues = array(null, '');
     foreach ($nullValues as $value) {
         $this->assertNull($prm->importValue($value));
     }
     $falseValues = array(array(), true, false, $prm);
     foreach ($falseValues as $value) {
         $this->assertFalse($prm->importValue($value));
     }
     $trueValues = array('some string', -100500, 2011.09);
     foreach ($trueValues as $value) {
         $this->assertTrue($prm->importValue($value));
     }
 }
 /**
  * @see \Components\Marshaller::unmarshal() \Components\Marshaller::unmarshal()
  */
 public function unmarshal($data_, $type_)
 {
     if (Primitive::isNative($type_)) {
         $type = Primitive::asBoxed($type_);
         return $type::cast($data_);
     }
     $type = new \ReflectionClass($type_);
     if ($type->isSubclassOf('Components\\Value')) {
         return $type_::valueOf($data_);
     }
     if ($type->isSubclassOf('Components\\Serializable_Json')) {
         $instance = new $type_();
         return $instance->unserializeJson($data_);
     }
     return $this->m_mapper->hydrateForType($type_, json_decode($data_, true));
 }
Esempio n. 27
0
 /**
  * @copydoc DBWorker::__construct
  *
  * @throws SystemException 'ERR_NO_SITE'
  * @throws SystemException 'ERR_403'
  */
 public function __construct()
 {
     parent::__construct();
     $uri = URI::create();
     $this->data = Site::load();
     if (!($this->getConfigValue('site.debug') && ($res = $this->getConfigValue('site.dev_domains')))) {
         $request = 'SELECT d . * , site_id as domain_site
                   FROM `share_domains` d
                   LEFT JOIN share_domain2site d2c
                   USING ( domain_id ) ';
         $res = $this->dbh->select($request);
     }
     if (!$res) {
         throw new SystemException('ERR_NO_SITE', SystemException::ERR_DEVELOPER);
     }
     foreach ($res as $domainData) {
         $domainData = E()->Utils->convertFieldNames($domainData, 'domain_');
         //Если не установлен уже домен - для сайта - дописываем
         //по сути первый домен будет дефолтным
         if (isset($domainData['site']) && is_null($this->data[$domainData['site']]->base)) {
             $tmp = $domainData;
             unset($tmp['id'], $tmp['site']);
             $this->data[$domainData['site']]->setDomain($tmp);
             unset($tmp);
         }
         if ($domainData['protocol'] == $uri->getScheme() && $domainData['host'] == $uri->getHost() && $domainData['port'] == $uri->getPort()) {
             $realPathSegments = array_values(array_filter(explode('/', $domainData['root'])));
             $pathSegments = array_slice($uri->getPath(false), 0, sizeof($realPathSegments));
             if ($realPathSegments == $pathSegments) {
                 $this->currentSiteID = $domainData['site'];
                 unset($domainData['id'], $domainData['site']);
                 $this->data[$this->currentSiteID]->setDomain($domainData);
             }
         }
     }
     if (is_null($this->currentSiteID)) {
         foreach ($this->data as $siteID => $site) {
             if ($site->isDefault == 1) {
                 $this->currentSiteID = $siteID;
             }
         }
     }
     //Если текущий сайт не активный
     if (!$this->data[$this->currentSiteID]->isActive) {
         throw new SystemException('ERR_403', SystemException::ERR_403);
     }
 }
 public function testBase()
 {
     $prm = Primitive::ipAddress('ip');
     $this->assertTrue($prm->importValue('127.0.0.1'));
     $this->assertTrue($prm->importValue('254.254.254.254'));
     $this->assertTrue($prm->importValue('0.0.0.0'));
     $this->assertFalse($prm->importValue('10.0.0'));
     $this->assertFalse($prm->importValue('42.42.42.360'));
     $this->assertFalse($prm->importValue('10.0.256'));
     $prmWithDefault = Primitive::ipAddress('ip')->setDefault(IpAddress::create('42.42.42.42'));
     $this->assertEquals($prmWithDefault->getActualValue()->toString(), '42.42.42.42');
     $prmWithDefault->import(array('ip' => '43.43.43.43'));
     $this->assertEquals($prmWithDefault->getActualValue()->toString(), '43.43.43.43');
     $prmWithDefault->importValue(IpAddress::create('8.8.8.8'));
     //google public dns ;)
     $this->assertEquals($prmWithDefault->getActualValue()->toString(), '8.8.8.8');
 }
 /**
  * Resolves (named) binding for given type.
  *
  * @param string $type_
  * @param string $name_
  *
  * @return \Components\Binding_Type_Abstract
  *
  * @throws \Components\Binding_Exception If failed to resolve binding.
  */
 public function getBinding($type_, $name_ = null)
 {
     $hashCode = Binding_Builder::createHashCode($type_, $name_);
     if (isset($this->m_bindings[$hashCode])) {
         return $this->m_bindings[$hashCode];
     }
     if ($native = Primitive::asNative($type_)) {
         $hashCode = Binding_Builder::createHashCode($native, $name_);
         if (isset($this->m_bindings[$hashCode])) {
             return $this->m_bindings[$hashCode];
         }
     }
     if (false === $this->m_initialized) {
         throw new Binding_Exception('inject/binding/module', 'Not initialized.');
     }
     return null;
 }
 public function handleRequest(HttpRequest $request)
 {
     $form = Form::create()->add(Primitive::string('username')->setMax(64)->required())->add(Primitive::string('password')->addImportFilter(Filter::hash())->required())->import($request->getPost());
     if (!$form->getErrors()) {
         try {
             $admin = Administrator::dao()->logIn($form->getValue('username'), $form->getValue('password'));
         } catch (ObjectNotFoundException $e) {
             // failed to log in
             return ModelAndView::create()->setView('error');
         }
         if (!Session::isStarted()) {
             Session::start();
         }
         Session::assign(Administrator::LABEL, $admin);
         return ModelAndView::create()->setView(new RedirectToView('main'));
     }
     return ModelAndView::create()->setView('login');
 }