コード例 #1
0
ファイル: UserUidResolver.php プロジェクト: Tanklong/openvj
 protected function preprocessValue(&$uid)
 {
     if (!Validator::int($uid)) {
         throw new InvalidArgumentException('uid', 'type_invalid');
     }
     $uid = (int) $uid;
 }
コード例 #2
0
 /**
  * Display a selected resource.
  *
  * @return Response
  */
 public function getProductById($categoryId, $productId)
 {
     if (Validator::int()->min(0)->validate($categoryId) && Validator::int()->min(0)->validate($productId)) {
         $category = null;
         for ($i = 0; $i < count($this->json_content->collections) && $category == null; $i++) {
             if ($this->json_content->collections[$i]->id == $categoryId) {
                 $category = $this->json_content->collections[$i];
             }
         }
         if ($category != null) {
             $product = null;
             for ($i = 0; $i < count($category->skus) && $product == null; $i++) {
                 if ($category->skus[$i]->id == $productId) {
                     $product = $category->skus[$i];
                 }
             }
             if ($product != null) {
                 return response()->json(new SuccessResponse(array('category' => $category, 'product' => $product), 'Category and Product found'), 200);
             } else {
                 return response()->json(new DangerResponse(array('category' => $category, 'product' => $product), 'Product not found'), 200);
             }
         } else {
             return response()->json(new DangerResponse(array('category' => $category, 'product' => $product), 'Category and Product not found'), 200);
         }
     } else {
         return response()->json(new DangerResponse(array('category' => array()), 'Failed to get category and product'), 200);
     }
 }
コード例 #3
0
ファイル: Home.php プロジェクト: anchetaWern/naughtyfire
 public function createHolidayAction()
 {
     $title = $this->app->request->post('title');
     $date = $this->app->request->post('date');
     $days = $this->app->request->post('days');
     $is_enabled = !empty($this->app->request->post('is_enabled')) ? true : false;
     $is_recurring = !empty($this->app->request->post('is_recurring')) ? true : false;
     $date = c::parse($date)->toDateString();
     $rules = array('title' => v::string()->notEmpty()->setName('title'), 'date' => v::date()->notEmpty()->setName('date'), 'days' => v::int()->notEmpty()->setName('days'), 'is_enabled' => v::bool()->setName('is_enabled'), 'is_recurring' => v::bool()->setName('is_recurring'));
     $data = $this->app->request->post();
     $data['date'] = $date;
     $data['is_enabled'] = $is_enabled;
     $data['is_recurring'] = $is_recurring;
     $message = array('type' => 'success', 'text' => 'Successfully added event');
     foreach ($data as $key => $value) {
         try {
             $rules[$key]->check($value);
         } catch (\InvalidArgumentException $e) {
             $message = array('type' => 'error', 'text' => $e->getMainMessage());
             break;
         }
     }
     $event = R::dispense('events');
     $event->title = $title;
     $event->date = $date;
     $event->days = $days;
     $event->is_enabled = $is_enabled;
     $event->is_recurring = $is_recurring;
     R::store($event);
     $this->app->flash('message', $message);
     $this->app->redirect('/');
 }
コード例 #4
0
ファイル: RoleManager.php プロジェクト: Tanklong/openvj
 /**
  * 创建一个角色
  *
  * @param string $name
  * @param bool $internal
  * @param \MongoId $domain
  * @param int $owner
  * @return bool
  * @throws InvalidArgumentException
  * @throws MissingArgumentException
  */
 public static function createRole($name, $internal = false, \MongoId $domain = null, $owner = null)
 {
     if (!is_string($name)) {
         throw new InvalidArgumentException('name', 'type_invalid');
     }
     if (!mb_check_encoding($name, 'UTF-8')) {
         throw new InvalidArgumentException('name', 'encoding_invalid');
     }
     if (!preg_match('/^\\$[0-9a-zA-Z_]{1,20}$/', $name)) {
         throw new InvalidArgumentException('name', 'format_invalid');
     }
     if (!$internal) {
         if ($domain === null) {
             throw new MissingArgumentException('domain');
         }
         if ($owner === null) {
             throw new MissingArgumentException('owner');
         }
         if (!Validator::int()->validate($owner)) {
             throw new InvalidArgumentException('owner', 'type_invalid');
         }
     }
     $name = strtoupper($name);
     if (!$internal) {
         $result = Application::coll('Role')->update(['domain' => $domain, 'name' => $name], ['$setOnInsert' => ['owner' => (int) $owner, 'at' => new \MongoDate()]], ['upsert' => true]);
     } else {
         $result = Application::coll('Role')->update(['internal' => true, 'name' => $name], [], ['upsert' => true]);
     }
     return $result['n'] === 1;
 }
コード例 #5
0
ファイル: TokenManager.php プロジェクト: Tanklong/openvj
 /**
  * 创建并返回一个 token
  *
  * @param string $purpose
  * @param string|null $identifier 唯一标识,为空则不需要
  * @param int $expireAt
  * @param mixed $data
  * @param int $length
  * @return array
  * @throws InvalidArgumentException
  * @throws \Exception
  * @throws \MongoException
  */
 public function generate($purpose, $identifier, $expireAt, $data = null, $length = 30)
 {
     if (!is_string($purpose)) {
         throw new InvalidArgumentException('purpose', 'type_invalid');
     }
     if (!mb_check_encoding($purpose, 'UTF-8')) {
         throw new InvalidArgumentException('purpose', 'encoding_invalid');
     }
     if (!Validator::int()->validate($expireAt)) {
         throw new InvalidArgumentException('expireAt', 'type_invalid');
     }
     $token = Application::get('random')->generateString($length, VJ::RANDOM_CHARS);
     try {
         if ($identifier !== null) {
             if (!is_string($identifier)) {
                 throw new InvalidArgumentException('identifier', 'type_invalid');
             }
             if (!mb_check_encoding($identifier, 'UTF-8')) {
                 throw new InvalidArgumentException('identifier', 'encoding_invalid');
             }
             $result = Application::coll('Token')->update(['purpose' => $purpose, 'identifier' => $identifier], ['$set' => ['token' => $token, 'expireat' => new \MongoDate($expireAt), 'data' => $data]], ['upsert' => true]);
             return ['token' => $token, 'update' => $result['updatedExisting']];
         } else {
             $result = Application::coll('Token')->insert(['purpose' => $purpose, 'identifier' => null, 'token' => $token, 'expireat' => new \MongoDate($expireAt), 'data' => $data]);
             return ['token' => $token];
         }
     } catch (\MongoException $ex) {
         if ($ex->getCode() === 12) {
             throw new InvalidArgumentException('data', 'encoding_invalid');
         } else {
             throw $ex;
         }
     }
 }
コード例 #6
0
ファイル: DiscussionUtil.php プロジェクト: Tanklong/openvj
 /**
  * 创建主题
  *
  * @param \MongoId $topicId
  * @param int $owner
  * @param string title
  * @param string $markdown
  * @return array|null
  * @throws InvalidArgumentException
  * @throws UserException
  */
 public static function createDiscussion(\MongoId $topicId, $owner, $title, $markdown)
 {
     if (!Validator::int()->validate($owner)) {
         throw new InvalidArgumentException('owner', 'type_invalid');
     }
     if (!is_string($title)) {
         throw new InvalidArgumentException('markdown', 'type_invalid');
     }
     if (!mb_check_encoding($title, 'UTF-8')) {
         throw new InvalidArgumentException('markdown', 'encoding_invalid');
     }
     if (!is_string($markdown)) {
         throw new InvalidArgumentException('markdown', 'type_invalid');
     }
     if (!mb_check_encoding($markdown, 'UTF-8')) {
         throw new InvalidArgumentException('markdown', 'encoding_invalid');
     }
     if (!Validator::length(VJ::COMMENT_MIN, VJ::COMMENT_MAX)) {
         throw new UserException('DiscussionUtil.content_invalid_length');
     }
     self::initParser();
     $discussionId = new \MongoId();
     $html = self::$parser->parse($markdown);
     $keyword = KeywordFilter::isContainGeneric(strip_tags($html));
     if ($keyword !== false) {
         throw new UserException('DiscussionUtil.content_forbid', ['keyword' => $keyword]);
     }
     $doc = ['_id' => $discussionId, 'owner' => (int) $owner, 'topicId' => $topicId, 'at' => new \MongoDate(), 'title' => $title, 'raw' => $markdown, 'html' => $html];
     Application::coll('Discussion')->insert($doc);
     Application::emit('discussion.create.succeeded', [$topicId, $discussionId]);
     return ['_id' => $discussionId, 'html' => $html];
 }
コード例 #7
0
ファイル: DomainManager.php プロジェクト: Tanklong/openvj
 /**
  * 加入域
  *
  * @param int $uid
  * @param \MongoId $domainId
  * @return bool
  * @throws InvalidArgumentException
  * @throws UserException
  */
 public function joinDomainById($uid, \MongoId $domainId)
 {
     if (!Validator::int()->validate($uid)) {
         throw new InvalidArgumentException('uid', 'type_invalid');
     }
     $uid = (int) $uid;
     if (!DomainUtil::isGlobalDomainId($domainId)) {
         // 检查域是否存在
         $d = Application::coll('Domain')->findOne(['_id' => $domainId]);
         if (!DomainUtil::isDomainObjectValid($d)) {
             throw new UserException('DomainManager.joinDomain.invalid_domain');
         }
     }
     // 检查用户是否存在
     $user = UserUtil::getUserObjectByUid($uid);
     if (!UserUtil::isUserObjectValid($user)) {
         throw new UserException('DomainManager.joinDomain.invalid_user');
     }
     // 添加 MEMBER 角色
     Application::coll('UserRole')->update(['uid' => $uid], ['$addToSet' => ['d.' . (string) $domainId => 'DOMAIN_MEMBER']], ['upsert' => true]);
     // 创建空资料
     $document = ['pref' => new \stdClass(), 'rp' => 0.0, 'rp_s' => 0.0, 'rank' => -1, 'level' => 0];
     if (DomainUtil::isGlobalDomainId($domainId)) {
         $document += ['sig' => '', 'sigraw' => '', 'contacts' => []];
     }
     Application::coll('UserInfo')->update(['uid' => $uid, 'domain' => new \MongoId(VJ::DOMAIN_GLOBAL)], ['$setOnInsert' => $document], ['upsert' => true]);
     // 操作非全局域则插入操作记录
     if (!DomainUtil::isGlobalDomainId($domainId)) {
         $doc = ['uid' => $this->session->getCurrentToken(), 'at' => new \MongoDate(), 'type' => 'join', 'ua' => $this->request->getUserAgent(), 'ip' => $this->request->getClientIp(), 'target_uid' => $uid, 'target_domain' => $domainId];
         Application::coll('DomainLog')->insert($doc);
     }
     return true;
 }
コード例 #8
0
ファイル: UserUtil.php プロジェクト: Tanklong/openvj
 /**
  * @param int $uid
  * @return array|null
  */
 public static function getUserObjectByUid($uid)
 {
     if (!Validator::int()->validate($uid)) {
         return null;
     }
     $user = Application::coll('User')->findOne(['uid' => (int) $uid]);
     return $user;
 }
 protected function assertIntBetween($fieldName, $start, $end, $parameter)
 {
     if (!v::int()->between($start, $end, true)->validate($parameter)) {
         $this->setValidationResponse(s::VALIDATION_ERROR, $fieldName, "is invalid");
         return false;
     }
     return true;
 }
コード例 #10
0
ファイル: Blog.php プロジェクト: vijo/movim
 function load()
 {
     if ($this->_view == 'node') {
         $this->_from = $this->get('s');
         $this->_node = $this->get('n');
         if (!$this->validateServerNode($this->_from, $this->_node)) {
             return;
         }
         $pd = new \Modl\ItemDAO();
         $this->_item = $pd->getItem($this->_from, $this->_node);
         $this->_mode = 'group';
         $this->url = Route::urlize('node', array($this->_from, $this->_node));
     } else {
         $this->_from = $this->get('f');
         $cd = new \modl\ContactDAO();
         $this->_contact = $cd->get($this->_from, true);
         if (filter_var($this->_from, FILTER_VALIDATE_EMAIL)) {
             $this->_node = 'urn:xmpp:microblog:0';
         } else {
             return;
         }
         $this->_mode = 'blog';
         $this->url = Route::urlize('blog', $this->_from);
     }
     $pd = new \modl\PostnDAO();
     if ($this->_id = $this->get('i')) {
         if (Validator::int()->between(0, 100)->validate($this->_id)) {
             $this->_messages = $pd->getNodeUnfiltered($this->_from, $this->_node, $this->_id * $this->_paging, $this->_paging + 1);
             $this->_page = $this->_id + 1;
         } elseif (Validator::string()->length(5, 100)->validate($this->_id)) {
             $this->_messages = $pd->getPublicItem($this->_from, $this->_node, $this->_id);
             if (is_object($this->_messages[0])) {
                 $this->title = $this->_messages[0]->title;
                 $description = stripTags($this->_messages[0]->contentcleaned);
                 if (!empty($description)) {
                     $this->description = $description;
                 }
                 $attachements = $this->_messages[0]->getAttachements();
                 if ($attachements && array_key_exists('pictures', $attachements)) {
                     $this->image = urldecode($attachements['pictures'][0]['href']);
                 }
             }
             if ($this->_view == 'node') {
                 $this->url = Route::urlize('node', array($this->_from, $this->_node, $this->_id));
             } else {
                 $this->url = Route::urlize('blog', array($this->_from, $this->_id));
             }
         }
     } else {
         $this->_page = 1;
         $this->_messages = $pd->getNodeUnfiltered($this->_from, $this->_node, 0, $this->_paging + 1);
     }
     if (count($this->_messages) == $this->_paging + 1) {
         array_pop($this->_messages);
     }
 }
コード例 #11
0
ファイル: UserSession.php プロジェクト: Tanklong/openvj
 /**
  * 在函数调用期间使用指定的 uid 作为权限控制主体的标识符
  *
  * @param int $uid
  * @param callable $callback
  * @throws InvalidArgumentException
  */
 public function overWriteToken($uid, callable $callback)
 {
     if (!Validator::int()->validate($uid)) {
         throw new InvalidArgumentException('uid', 'type_invalid');
     }
     $lastOverWrite = $this->{$overWriteUid};
     $this->{$overWriteUid} = $uid;
     $callback();
     $this->{$overWriteUid} = $lastOverWrite;
 }
コード例 #12
0
ファイル: BuyerCreationValidator.php プロジェクト: HOFB/HOFB
 public function validate($data)
 {
     $validator = V::key('retailer_id', V::int()->length(0, 100), true);
     try {
         $validator->assert($data);
     } catch (AbstractNestedException $e) {
         $errors = $e->findMessages(['retailer_id']);
         throw new ValidationException('Could not create user.', $errors);
     }
     return true;
 }
コード例 #13
0
ファイル: Role.php プロジェクト: Tanklong/openvj
 /**
  * @param int|null $uid
  */
 public function __construct($uid = null)
 {
     if ($uid === null || !Validator::int()->validate($uid)) {
         $this->roles = [];
         return;
     }
     $data = Application::coll('UserRole')->findOne(['uid' => (int) $uid]);
     if ($data === null) {
         $this->roles = [];
         return;
     }
     $this->roles = $data['d'];
 }
コード例 #14
0
 public function validateId($id, $name = 'ID')
 {
     $rules = v::int()->notEmpty()->setName($name);
     if ($rules->validate($id)) {
         return true;
     }
     try {
         $rules->check($id);
     } catch (ValidationExceptionInterface $exception) {
         $this->error = $exception->getMainMessage();
     }
     return false;
 }
コード例 #15
0
ファイル: FormTest.php プロジェクト: ddelor/gallery-wp-theme
 public function __construct($data)
 {
     parent::__construct();
     $this->data = $data;
     $this->fields = array('firstname' => array('value' => $this->data['firstname'], 'validators' => array('notEmpty'), 'errors' => array('Firstname is empty')), 'email' => array('value' => $this->data['email'], 'validators' => array('email', 'notEmpty'), 'errors' => array('Email is not valid', 'Email is empty')), 'url' => array('value' => $this->data['url'], 'validators' => array('notEmpty', 'url'), 'errors' => array('Url is empty', 'Url is not valid')), 'cv' => array('value' => $_FILES['cv'], 'validators' => function () {
         return v::exists()->validate($_FILES['cv']["tmp_name"]);
     }, 'errors' => array('File is empty')), 'content' => array('value' => $this->data['content'], 'validators' => function ($value) {
         return v::when(v::int(), v::positive(), v::notEmpty())->validate($value);
     }, 'errors' => array('content is not valid')), 'int' => array('value' => $this->data['int'], 'validators' => function ($value) {
         return v::allOf(v::int(), v::positive(), v::notEmpty())->validate($value);
     }, 'errors' => array('int is not valid')), 'uppercase' => array('value' => '', 'validators' => function ($value) {
         return v::string()->uppercase()->validate($value);
     }, 'errors' => array('uppercase is not valid')));
 }
コード例 #16
0
ファイル: DomainUtil.php プロジェクト: Tanklong/openvj
 /**
  * 获取用户所在域
  *
  * @param $uid
  * @return \MongoId[]|null
  * @throws InvalidArgumentException
  */
 public static function getUserDomains($uid)
 {
     if (!Validator::int()->validate($uid)) {
         throw new InvalidArgumentException('uid', 'type_invalid');
     }
     $record = Application::coll('UserRole')->findOne(['uid' => (int) $uid]);
     // user not found
     if ($record === null) {
         return null;
     }
     $domainIds = array_keys($record['d']);
     return array_map(function ($id) {
         return new \MongoId($id);
     }, $domainIds);
 }
 private function validateExpYear($parameters)
 {
     $fieldName = "exp_year";
     if (!v::int()->validate($parameters[$fieldName])) {
         $this->validationResponse->status = s::VALIDATION_ERROR;
         $this->validationResponse->errors[$fieldName] = "is not a valid year";
         return false;
     }
     $now = new \DateTime();
     $year = substr($parameters[$fieldName], -2);
     if (!v::int()->min($now->format("y"), true)->validate($year)) {
         $this->validationResponse->status = s::VALIDATION_ERROR;
         $this->validationResponse->errors[$fieldName] = "is invalid";
         return false;
     }
     return true;
 }
コード例 #18
0
ファイル: VoteUtil.php プロジェクト: Tanklong/openvj
 /**
  * 若投票成功,返回投票后的投票值,若失败,返回 null
  *
  * @param \MongoCollection $collection
  * @param array $query
  * @param int $uid
  * @param int $value
  * @return int|null
  * @throws InvalidArgumentException
  */
 public static function vote(\MongoCollection $collection, array $query, $uid, $value)
 {
     if ($value !== 1 && $value !== -1) {
         throw new InvalidArgumentException('value', 'value_invalid');
     }
     if (!Validator::int()->validate($uid)) {
         throw new InvalidArgumentException('uid', 'type_invalid');
     }
     $value = (int) $value;
     $result = $collection->findAndModify(array_merge($query, ['votes.' . strval(intval($uid)) => ['$exists' => false]]), ['$set' => ['votes' . strval(intval($uid)) => $value], '$inc' => ['voting' => $value]], ['voting' => 1], ['new' => true]);
     if ($result === null) {
         // vote failed
         return null;
     } else {
         // vote succeeded
         return $result['voting'];
     }
 }
コード例 #19
0
 public function __construct()
 {
     $this->properties = ['userAgent' => new Property(['default' => sprintf('%s/%s (+%s)', Client::NAME, Client::VERSION, Client::URL), 'validator' => function ($val) {
         try {
             Validator::string()->length(6)->notEmpty()->assert($val);
         } catch (NestedValidationExceptionInterface $e) {
             throw new ValidationException($e);
         }
     }]), 'connectionTimeout' => new Property(['default' => 10, 'validator' => function ($val) {
         try {
             Validator::int()->min(2, true)->max(600)->assert($val);
         } catch (NestedValidationExceptionInterface $e) {
             throw new ValidationException($e);
         }
     }]), 'baseUrl' => new Property(['validator' => function ($val) {
         try {
             Validator::string()->notEmpty()->assert($val);
         } catch (NestedValidationExceptionInterface $e) {
             throw new ValidationException($e);
         }
     }])];
 }
コード例 #20
0
ファイル: ContestTag.php プロジェクト: Tanklong/openvj
 /**
  * @param string $name
  * @param int|null $year
  * @throws InvalidArgumentException
  * @throws UserException
  */
 public function __construct($name, $year = null)
 {
     if (!is_string($name)) {
         throw new InvalidArgumentException('name', 'type_invalid');
     }
     if (!mb_check_encoding($name, 'UTF-8')) {
         throw new InvalidArgumentException('name', 'encoding_invalid');
     }
     $keyword = KeywordFilter::isContainGeneric($name);
     if ($keyword !== false) {
         throw new UserException('Problem.Tag.name_forbid', ['keyword' => $keyword]);
     }
     if (!Validator::length(VJ::TAG_MIN, VJ::TAG_MAX)->validate($name)) {
         throw new UserException('Problem.Tag.invalid_length');
     }
     if ($year !== null) {
         if (!Validator::int()->validate($year)) {
             throw new InvalidArgumentException('year', 'type_invalid');
         }
         $year = (int) $year;
     }
     $this->name = $name;
     $this->year = $year;
 }
コード例 #21
0
ファイル: product.php プロジェクト: beyondkeysystem/sushi-web
function validateProduct(&$product)
{
    $invalids = array();
    if (empty($product['name']) || !Validation::string()->length(1, 255)->validate($product['name'])) {
        array_push($invalids, 'name');
    }
    if (empty($product['price']) || !Validation::float()->min(0, true)->validate($product['price'])) {
        array_push($invalids, 'price');
    }
    if (empty($product['amount']) || !Validation::int()->min(1, true)->validate($product['amount'])) {
        array_push($invalids, 'amount');
    }
    if (empty($product['categoryId']) || !Validation::int()->max(10, true)->validate($product['categoryId'])) {
        array_push($invalids, 'categoryId');
    }
    return $invalids;
}
コード例 #22
0
ファイル: Valid.php プロジェクト: tourze/base
 /**
  * 检测数值是否在范围内
  *
  * @param  string $value
  * @param  int    $min 最小值
  * @param  int    $max 最大值
  * @return bool
  */
 public static function range($value, $min, $max)
 {
     return Validator::int()->between($min, $max)->validate($value);
 }
コード例 #23
0
use Respect\Validation\Validator as Valid;
Route::get('/carbon', function () {
    var_dump(Carbon::now());
    echo 'asdf';
    //return 'test';
});
Route::get('/paths', function () {
    // See: http://laravel.com/docs/5.1/helpers#paths
    echo 'url() => ' . url('/heheh') . '<br>';
    echo 'app_path() => ' . app_path('asdfasd') . '<br>';
    echo 'base_path() => ' . base_path() . '<br>';
    //App\Helpers::load('app_helpers.php');
    echo ENV_PREFIX . 'LOCAL_DB_HOST' . '<br>';
    echo env(ENV_PREFIX . 'DB_HOST') . '<br>';
    echo config('database.connections.mysql.host') . '<br>';
    var_dump(Valid::int()->notEmpty()->validate('1'));
    //xplog('hello');
});
Route::get('/get/hostname', function () {
    $hostname = strtolower(trim(gethostname()));
    //echo $hostname;
    echo bcrypt('abc123456');
});
Route::get('/sessions', function () {
    _pr(session()->all());
});
Route::get('/email', function () {
    die('turned off');
    var_dump(Mail::send('emails.signup_confirmation', ['user' => 'test'], function ($m) {
        $m->to('*****@*****.**', 'Raffy')->subject('CLEVERBONS TEST EMAIL');
        $m->from('*****@*****.**', 'Laravel');
コード例 #24
0
ファイル: Contact.php プロジェクト: Trim/movim
 function ajaxPublic($page = 0)
 {
     $validate_page = Validator::int();
     if (!$validate_page->validate($page)) {
         return;
     }
     RPC::call('MovimTpl.fill', '#public_list', $this->preparePublic($page));
 }
コード例 #25
0
ファイル: Settings.php プロジェクト: natedrake/fast-forward
 public function __construct(Client $client)
 {
     $this->client = $client;
     $sortColumns = array_keys(Bookmark::select()->toAssoc());
     $this->supportedSettings = array('ff.limit' => array('desc' => 'Limit amount of results (> 0 or 0 for no limit)', 'validation' => array(v::int()->min(0, true)), 'default' => '0'), 'ff.sort' => array('desc' => 'Sort order of results (' . implode($sortColumns, ', ') . ')', 'validation' => array(v::in($sortColumns)->notEmpty()), 'default' => 'hit_count'), 'ff.interactive' => array('desc' => 'Ask for missing input interactively (0 never, 1 always)', 'validation' => array(v::in(array('0', '1'))), 'default' => '1'), 'ff.color' => array('desc' => 'Enable color output on supported systems (0/1)', 'validation' => array(v::in(array('0', '1'))), 'default' => '1'));
 }
コード例 #26
0
ファイル: formclass.php プロジェクト: tohir/formgenerator
 public static function max($details, $value)
 {
     return RespectValidator::oneOf(RespectValidator::int()->max((int) $details), RespectValidator::int()->equals((int) $details))->validate($value);
 }
コード例 #27
0
ファイル: order.php プロジェクト: beyondkeysystem/sushi-web
     array_push($invalids, 'timeTo');
 }
 if (!isset($params['paid']) || !Validation::int()->min(0, true)->max(1, true)->validate($params['paid'])) {
     array_push($invalids, 'paid');
 }
 if (!isset($params['items']) || !Validation::arr()->length(1, null)->validate($params['items'])) {
     array_push($invalids, 'items');
 }
 foreach ($params['items'] as $index => $product) {
     if (!isset($product['productId']) || !Validation::int()->min(0, true)->validate($product['productId'])) {
         array_push($invalids, 'productId-' . $index);
     }
     if (!isset($product['plu']) || !Validation::int()->max(999999)->validate($product['plu'])) {
         array_push($invalids, 'plu-' . $index);
     }
     if (!isset($product['amount']) || !Validation::int()->validate($product['amount'])) {
         array_push($invalids, 'amount-' . $index);
     }
 }
 if (empty($invalids)) {
     $queryValues = array('userId' => $params['userId'], 'name' => $params['name'], 'phone' => $params['phone'], 'address' => $params['address'], 'dateFrom' => date('Y-m-d'), 'timeFrom' => $params['timeFrom'], 'dateTo' => date('Y-m-d'), 'timeTo' => $params['timeTo'], 'paid' => $params['paid'], 'deliver' => $params['deliver'], 'src' => 'orders/' . date('Y-m-d-H-i-U') . '.txt');
     $dbquery = $db->prepare('INSERT INTO orders(userId, name, phone, address, dateFrom, timeFrom, dateTo, timeTo, paid, deliver, src) VALUES (:userId, :name, :phone, :address, :dateFrom, :timeFrom, :dateTo, :timeTo, :paid, :deliver, :src)');
     $success = $dbquery->execute($queryValues);
     $orderId = $db->lastInsertId();
     foreach ($params['items'] as $index => $product) {
         $subQueryValues = array('orderId' => $orderId, 'productId' => $product['productId'], 'amount' => $product['amount']);
         $dbquery = $db->prepare('INSERT INTO `order-item`(orderId, productId, amount) VALUES (:orderId, :productId, :amount)');
         $success = $dbquery->execute($subQueryValues);
         /*
         $message = $queryValues['phone'].'|'.$queryValues['address'].'|'.$queryValues['name'].'|';
         $message .= $queryValues['deliver'] ? 'S|' : 'N|';
コード例 #28
0
/**
 * Validates input type
 *
 * @param string           $hook       "validate:type"
 * @param string           $type       "prototyper"
 * @param ValidationStatus $validation Current validation status
 * @param array            $params     Hook params
 * @return ValidationStatus
 */
function prototyper_validate_type($hook, $type, $validation, $params)
{
    if (!$validation instanceof ValidationStatus) {
        $validation = new ValidationStatus();
    }
    $field = elgg_extract('field', $params);
    if (!$field instanceof Field) {
        return $validation;
    }
    $rule = elgg_extract('rule', $params);
    if ($rule != "type") {
        return $validation;
    }
    $value = elgg_extract('value', $params);
    $expectation = elgg_extract('expectation', $params);
    switch ($expectation) {
        case 'text':
        case 'string':
            if (!v::string()->validate($value)) {
                $validation->setFail(elgg_echo('prototyper:validate:error:type:string', array($field->getLabel())));
            }
            break;
        case 'alnum':
        case 'alphanum':
            if (!v::alnum()->validate($value)) {
                $validation->setFail(elgg_echo('prototyper:validate:error:type:alnum', array($field->getLabel())));
            }
            break;
        case 'alpha':
            if (!v::alpha()->validate($value)) {
                $validation->setFail(elgg_echo('prototyper:validate:error:type:alpha', array($field->getLabel())));
            }
            break;
        case 'number':
        case 'numeric':
            if (!v::numeric()->validate($value)) {
                $validation->setFail(elgg_echo('prototyper:validate:error:type:numeric', array($field->getLabel())));
            }
            break;
        case 'integer':
        case 'int':
            if (!v::int()->validate($value)) {
                $validation->setFail(elgg_echo('prototyper:validate:error:type:int', array($field->getLabel())));
            }
            break;
        case 'date':
            if (!v::date()->validate($value)) {
                $validation->setFail(elgg_echo('prototyper:validate:error:type:date', array($field->getLabel())));
            }
            break;
        case 'url':
            if (!v::filterVar(FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)->validate($value)) {
                $validation->setFail(elgg_echo('prototyper:validate:error:type:url', array($field->getLabel())));
            }
            break;
        case 'email':
            if (!v::filterVar(FILTER_VALIDATE_EMAIL)->validate($value)) {
                $validation->setFail(elgg_echo('prototyper:validate:error:type:email', array($field->getLabel())));
            }
            break;
        case 'guid':
        case 'entity':
            if (!elgg_entity_exists($value)) {
                $validation->setFail(elgg_echo('prototyper:validate:error:type:guid', array($field->getLabel())));
            }
            break;
        case 'image':
            $type = elgg_extract('type', $value);
            if (!$type || substr_count($type, 'image/') == 0) {
                $validation->setFail(elgg_echo('prototyper:validate:error:type:image', array($field->getLabel())));
            }
            break;
    }
    return $validation;
}
コード例 #29
0
 public function addProperty(Request $request)
 {
     if (!Auth::check()) {
         return redirect(route('logout'));
     }
     if (!$request->session()->has('current_user')) {
         return redirect(route('logout'));
     }
     $current_user = $request->session()->get('current_user');
     $data = [];
     view()->share(['title' => 'Add Property', 'CB_PAGE_JS' => [url('/js/mods/Cb.Notify.js')]]);
     $p = ['property_street' => '', 'property_state' => 'ACT', 'property_city' => '', 'property_postcode' => '', 'property_phone' => '', 'property_short_desc' => '', 'property_description' => '', 'property_type' => '', 'property_bedrooms' => '0', 'property_bathrooms' => '0', 'property_landarea' => '', 'property_floorarea' => '', 'property_garage' => '0', 'property_lat' => '00000', 'property_lng' => '00000', 'property_terms' => '1'];
     $data['aus_states'] = config('cleverbons.aus_states');
     $data['property_types'] = App\Cb\Properties::getTypes();
     if ($request->isMethod('post') && $request->has('submit')) {
         $p = $request->all();
         // See: https://github.com/Respect/Validation/blob/master/docs/VALIDATORS.md
         $checks = [];
         $checks['property_street'] = Valid::string()->notEmpty()->validate($p['property_street']);
         $checks['property_state'] = Valid::string()->notEmpty()->validate($p['property_state']);
         $checks['property_city'] = Valid::string()->notEmpty()->validate($p['property_city']);
         $checks['property_postcode'] = Valid::string()->notEmpty()->validate($p['property_postcode']);
         $checks['property_phone'] = Valid::string()->notEmpty()->validate($p['property_phone']);
         $checks['property_short_desc'] = Valid::string()->notEmpty()->validate($p['property_short_desc']);
         $checks['property_description'] = Valid::string()->notEmpty()->validate($p['property_description']);
         $checks['property_type'] = Valid::string()->notEmpty()->validate($p['property_type']);
         $checks['property_bedrooms'] = Valid::int()->notEmpty()->validate($p['property_bedrooms']);
         $checks['property_bathrooms'] = Valid::int()->notEmpty()->validate($p['property_bathrooms']);
         $checks['property_landarea'] = Valid::string()->notEmpty()->validate($p['property_landarea']);
         $checks['property_floorarea'] = Valid::string()->notEmpty()->validate($p['property_floorarea']);
         $checks['property_garage'] = Valid::int()->notEmpty()->validate($p['property_garage']);
         $checks['property_lat'] = Valid::string()->notEmpty()->validate($p['property_lat']);
         $checks['property_lng'] = Valid::string()->notEmpty()->validate($p['property_lng']);
         $checks['property_terms'] = isset($p['property_terms']);
         try {
             if (in_array(false, $checks)) {
                 throw new Exception('Some required field(s) have invalid values.');
             }
             // Floorplan Files //
             if (isset($_FILES['property_floorplan_files']['name'])) {
                 $floorplan_file_arr = App\Upload::reArrayFiles($_FILES['property_floorplan_files']);
                 if (!App\Cb\Properties\Docs::isAllowed($floorplan_file_arr)) {
                     throw new Exception('One or more of the floor plan files are supported');
                 }
             }
             // Property Images //
             if (isset($_FILES['property_images']['name'])) {
                 $images_file_arr = App\Upload::reArrayFiles($_FILES['property_images']);
                 if (!App\Cb\Properties\Images::isAllowed($images_file_arr)) {
                     throw new Exception('One or more of the images is not supported');
                 }
             }
             $property_id = App\Cb\Properties::add($current_user->id, ['short_desc' => $p['property_short_desc'], 'description' => $p['property_description'], 'street' => $p['property_street'], 'city' => $p['property_city'], 'state' => $p['property_state'], 'postcode' => $p['property_postcode'], 'lat' => $p['property_lat'], 'lng' => $p['property_lng'], 'num_bedrooms' => $p['property_bedrooms'], 'num_bathrooms' => $p['property_bathrooms'], 'num_garage' => $p['property_garage'], 'landarea' => $p['property_landarea'], 'floorarea' => $p['property_floorarea'], 'type' => $p['property_type']]);
             if (!$property_id) {
                 throw new Exception('Unable to add property. Please check your connection and try again.');
             }
             // Save the floorplan docs //
             if (isset($floorplan_file_arr) && !App\Cb\Properties\Docs::save($property_id, $floorplan_file_arr)) {
                 xplog('Unable to save some floor plan files for property "' . $property_id . '"', __METHOD__);
             }
             // Save the images //
             if (isset($images_file_arr) && !App\Cb\Properties\Images::save($property_id, $images_file_arr)) {
                 xplog('Unable to save some images for property "' . $property_id . '"', __METHOD__);
             }
             cb_set_message('Successfully added property to your account', 1);
             return redirect(route('my_properties'));
         } catch (Exception $err) {
             cb_set_message($err->getMessage(), 0);
         }
     }
     $data['post'] = $p;
     return View::make('add_property', $data)->render();
 }
コード例 #30
0
ファイル: NotTest.php プロジェクト: 00F100/Validation
 public function providerForInvalidNot()
 {
     return array(array(new Int(), ''), array(new Int(), 123), array(new AllOf(new OneOf(new Numeric(), new Int())), 13.37), array(new OneOf(new Numeric(), new Int()), 13.37), array(Validator::oneOf(Validator::numeric(), Validator::int()), 13.37));
 }