示例#1
0
 public static function load($path)
 {
     if (!is_readable($path)) {
         return [];
     }
     $json = file_get_contents($path);
     return Json::decode($json);
 }
示例#2
0
 /**
  * 显示登录页(默认Action)
  */
 function doDefault()
 {
     $data = array('a', 'b' => 'roast');
     $json = new Json();
     $str_encoded = $json->encode($data);
     var_dump($str_encoded);
     var_dump($json->decode($str_encoded));
 }
 /**
  * Loads the message translation for the specified language and category.
  * @param string $messageFile string The path to message file.
  * @return string[] The message array, or an empty array if the file is not found or invalid.
  */
 protected function loadMessagesFromFile($messageFile) : array
 {
     if (!is_file($messageFile)) {
         return [];
     }
     $messages = Json::decode(@file_get_contents($messageFile));
     return is_array($messages) ? $messages : [];
 }
示例#4
0
 /**
  * Tests the <code>decode()</code> method with an exception.
  *
  * @covers Braincrafted\Json\Json::decode()
  * @covers Braincrafted\Json\Json::getError()
  */
 public function testDecode_WithError()
 {
     try {
         Json::decode('{"var1":"foo","var2":42');
         $this->assertTrue(false);
     } catch (JsonDecodeException $e) {
         $this->assertTrue(true);
     }
 }
 /**
  *
  * @return CompanyEntity
  */
 public function getCampaigns()
 {
     $request = Request::get("{$this->getCompanyId()}/campaigns");
     $response = $this->getConnector()->sendRequest($request);
     $data = Json::decode($response->getContent());
     $json = new stdClass();
     $json->campaigns = $data;
     return new CampaignsEntity($json);
 }
 /**
  * 
  * @param string $email
  * @return UnsubscribersEntity
  */
 public function getUnsubscribersByEmail($email)
 {
     $request = Request::get("{$this->getCompanyId()}/unsubscribers/{$email}");
     $response = $this->getConnector()->sendRequest($request);
     $data = Json::decode($response->getContent());
     $json = new stdClass();
     $json->unsubscribers = $data;
     return new UnsubscribersEntity($json);
 }
 /**
  * Parses custom function calls for geting function name and parameters.
  *
  * @param string $function
  *
  * @return array
  */
 private function parseFunction($function)
 {
     if (!Str::contains($function, ':')) {
         return [$function, []];
     }
     list($function, $params) = explode(':', $function, 2);
     $params = (array) Json::decode($params, true);
     return [$function, $params];
 }
示例#8
0
文件: JsonTest.php 项目: jivoo/core
 public function testEncodeAndDecode()
 {
     $value = 1;
     $this->assertEquals($value, Json::decode(Json::encode($value)));
     $value = 'foo';
     $this->assertEquals($value, Json::decode(Json::encode($value)));
     $value = ['foo' => 'bar'];
     $this->assertEquals($value, Json::decode(Json::encode($value)));
     $value = ['foo', 'bar'];
     $this->assertEquals($value, Json::decode(Json::encode($value)));
 }
示例#9
0
 public function update()
 {
     $data = Json::decode(Request::post('data'));
     $id = Request::post('id', true, Validator::INT);
     if (!$data) {
         throw new ValidatorException('Некорректный параметр data');
     }
     //проверка данных
     $this->validateDataForSave($data);
     echo $this->_update($data, $id);
 }
示例#10
0
 /**
  * Parses the arguments of a parametrized helper.
  * Arguments can be specified as a single value, or as a string in JSON format.
  * @param string $text The section content specifying the helper arguments.
  * @param string $defaultArgument The name of the default argument. This is used when the section content provides a plain string instead of a JSON object.
  * @param array $defaultValues The default values of arguments. These are used when the section content does not specify all arguments.
  * @return array The parsed arguments as an associative array.
  */
 protected function parseArguments(string $text, string $defaultArgument, array $defaultValues = []) : array
 {
     try {
         if (is_array($json = Json::decode($text))) {
             return ArrayHelper::merge($defaultValues, $json);
         }
         throw new InvalidParamException();
     } catch (InvalidParamException $e) {
         $defaultValues[$defaultArgument] = $text;
         return $defaultValues;
     }
 }
 /**
  * ControllerStyleTemplate::index()
  * 
  * @see Load
  * @see Document
  * @see Language
  * @see getList
  * @return void
  */
 public function index()
 {
     $this->load->auto('json');
     $response = Json::decode($this->fetchUrl('http://www.necotienda.org/api/index.php?r=style/template/get'));
     if ($response['response_code'] === 200) {
         $this->data['templates'] = $response['data']['data'];
     }
     $this->template = 'style/template_list.tpl';
     $this->children[] = 'common/header';
     $this->children[] = 'common/nav';
     $this->children[] = 'common/footer';
     $this->response->setOutput($this->render(true), $this->config->get('config_compression'));
 }
示例#12
0
 public function add()
 {
     $data = Json::decode(Request::post('data'));
     if (empty($data['type'])) {
         throw new ValidatorException('Параметр "type" не передан или пустой');
     }
     $real_url = eval($this->db->getOne('SELECT `url_maker` FROM ##items_types WHERE `id`=?i LIMIT 1', [$data['type']])) . '.html';
     $data['params'] = Json::encode($data['item_params']);
     unset($data['item_params']);
     $id = parent::_add($data);
     $this->db->query("INSERT INTO ##url_redirects (`old_url`,`new_url`,`type`,`system`,`comment`) VALUES (?s,?s,'I',1,?i)", [$data['item_url'], $real_url, $id]);
     echo $id;
 }
示例#13
0
 /**
  * @param string $json
  *
  * @throws Exception\JsonParseException
  *
  * @return Request|Request[]
  */
 public function parse($json)
 {
     // decode the string
     $request = Json::decode($json, $this->jsonDecodeDepthLimit);
     // create a new collection
     if (is_array($request) && count($request) > 0) {
         // non-empty arrays are attempts at batch requests
         $collection = array();
         foreach ($request as $singleRequest) {
             $collection[] = $this->createFrom($singleRequest);
         }
         return $collection;
     } else {
         // all other valid json is treated as a single request
         return $this->createFrom($request);
     }
 }
示例#14
0
 /**
  * @param mixed $value
  * @param bool $throwException
  * @throws SerializeException
  * @return mixed
  */
 public static function unserialize($value, $throwException = true)
 {
     if ($throwException === false) {
         if (!is_string($value)) {
             return $value;
         }
     }
     if (static::is($value)) {
         return unserialize($value);
     } elseif (Json::is($value)) {
         return Json::decode($value);
     }
     if ($throwException == true) {
         throw new SerializeException(SerializeException::NOT_SERIALIZE);
     }
     return $value;
 }
示例#15
0
 static function geocode($place, $country = '')
 {
     $text = $country ? $place . ',' . $country : $place;
     $temp = TempStore::getInstance();
     $key = 'YahooQueryClient/geocode//' . $text;
     $data = $temp->get($key);
     if ($data) {
         return unserialize($data);
     }
     $q = urlencode('select * from geo.places where text="' . $text . '"');
     $url = 'http://query.yahooapis.com/v1/public/yql?q=' . $q . '&format=json';
     $x = Json::decode($url);
     //XXX: instead return all results as array of YahooGeocodeResult objects?
     if ($x->query->count > 1) {
         $item = $x->query->results->place[0];
     } else {
         $item = $x->query->results->place;
     }
     $res = new YahooGeocodeResult();
     $res->name = $item->name;
     $res->country = $item->country->code;
     /* XXX TODO: parse admin1, admin2:
     
     admin1: {
         * code: ""
         * type: "County"
         * content: "Jamtland"
     }
     admin2: {
         * code: ""
         * type: "Municipality"
         * content: "Härjedalen"
     }
     */
     $res->woeid = $item->woeid;
     $res->area = new \StdClass();
     $res->area->center = new YahooQueryCoordinate($item->centroid->latitude, $item->centroid->longitude);
     $res->area->sw = new YahooQueryCoordinate($item->boundingBox->southWest->latitude, $item->boundingBox->southWest->longitude);
     $res->area->ne = new YahooQueryCoordinate($item->boundingBox->northEast->latitude, $item->boundingBox->northEast->longitude);
     //XXX this is a ugly hack until yahoo returns timezone with their response
     $geoname = GeonamesClient::reverse($item->centroid->latitude, $item->centroid->longitude);
     $res->timezone = $geoname->timezone;
     $temp->set($key, serialize($res));
     return $res;
 }
 static function shorten($input_url)
 {
     /*
             $login = '******';
             $key = 'R_0da49e0a9118ff35f52f629d2d71bf07';
     */
     $login = '******';
     $key = 'R_f37747e06a18173096b714827c76b567';
     $url = 'http://api.bit.ly/v3/shorten?format=json&login='******'&apiKey=' . $key . '&longUrl=' . urlencode($input_url);
     $http = new HttpClient($url);
     $http->setCacheTime(86400);
     //24 hours
     $res = Json::decode($http->getBody());
     if ($res->status_code != 200) {
         throw new \Exception('Error code ' . $res->status_code . ': ' . $res->status_txt);
     }
     return $res->data->url;
 }
 static function shorten($input_url)
 {
     $temp = TempStore::getInstance();
     $res = $temp->get('goo.gl/' . $input_url);
     if ($res) {
         return $res;
     }
     $api_key = '';
     $http = new HttpClient('https://www.googleapis.com/urlshortener/v1/url');
     $http->setContentType('application/json');
     $res = $http->post(Json::encode(array('longUrl' => $input_url, 'key' => $api_key)));
     $res = Json::decode($res);
     if (isset($res->error)) {
         d($res->error->errors);
         throw new \Exception('Error code ' . $res->error->code . ': ' . $res->error->message);
     }
     $temp->set('goo.gl/' . $input_url, $res->id);
     return $res->id;
 }
示例#18
0
 public static function start()
 {
     //если сайт отключен
     if (SConfig::SITE_DISABLED) {
         FileSys::includeFile(SITE_ROOT . '/client/pages/site_disabled.php');
         exit;
     }
     //в переменную $request_url заносим url без GET-параметров
     $request_url = explode('?', $_SERVER['REQUEST_URI'])[0];
     //проверяем url
     if (!preg_match('/^\\/(([-a-z0-9_]+\\/)*[-a-z0-9_]+\\.html)?(\\?.*)?$/', $request_url)) {
         Router::set404();
     }
     Request::setOriginalUrl($request_url);
     $db = (new Db())->setTable('url_redirects');
     //если у страницы есть новый адрес - перенаправляем, чтобы избежать дублей страниц
     if ($ou = $db->getOne('SELECT `old_url` FROM # WHERE new_url=?s AND type="I"', $request_url)) {
         Router::redirect($ou);
     }
     //проверяем, есть ли редиректы
     $r = $db->getRow('SELECT `new_url`,`type`,`comment` FROM # WHERE old_url=?s', $request_url);
     if ($r) {
         //если редирект внутренний
         if ($r[1] === 'I') {
             $request_url = $r[0];
         } elseif ($r[1] === 'E') {
             Router::redirect($r[0]);
         }
     }
     //получаем параметры пункта меню (если есть)
     $item = $db->getRow('SELECT * FROM ##menu_items WHERE `item_url`=?s', [Request::getOriginalUrl()], MYSQLI_ASSOC);
     if ($item) {
         if ($item['params']) {
             $item['params'] = Json::decode($item['params']);
         }
         Request::setItemParams($item);
     }
     Request::setRealUrl($request_url);
     Request::setUrlSegments(explode('/', substr($request_url, 1, -5)));
     //запускаем вывод страницы
     Document::generate();
 }
示例#19
0
 public function actionIndex()
 {
     $query = Article::find();
     $channelId = $this->getQuery('channel');
     $where = ['isDeleted' => false, 'channel' => new \MongoId($channelId)];
     $orderBy = $this->getQuery('orderBy');
     if (!empty($orderBy)) {
         $orderBy = Json::decode($orderBy, true);
         foreach ($orderBy as $key => $value) {
             if ('asc' === strtolower($value)) {
                 $orderBy[$key] = SORT_ASC;
             } else {
                 $orderBy[$key] = SORT_DESC;
             }
         }
     } else {
         $orderBy = ['createdAt' => SORT_DESC];
     }
     return new ActiveDataProvider(['query' => $query->where($where)->orderBy($orderBy)]);
 }
示例#20
0
 public static function switchTheme()
 {
     if (isset($_COOKIE["theme"])) {
         $theme = $_COOKIE["theme"];
         Typecho_Widget::widget("Widget_Options")->to($options);
         $themeDir = rtrim($options->themeFile($theme), '/') . '/';
         if (@is_dir($themeDir)) {
             $options->theme = $theme;
             $file = dirname(__FILE__) . "/themecfg.json";
             if (file_exists($file)) {
                 $opt = @Json::decode(@file_get_contents($file), true);
                 if (!empty($opt) && isset($opt[$theme])) {
                     foreach ($opt[$theme] as $key => $value) {
                         $options->{$key} = $value;
                     }
                 }
             }
         }
     }
 }
示例#21
0
 /**
  * @param $json
  *
  * @throws Exception\JsonParseException
  * @throws Exception\InvalidResponseException
  *
  * @return BatchResponse|Response|ResponseError|null
  */
 public function parse($json)
 {
     // if there's no data- return null
     if ($json === '') {
         return null;
     }
     // decode the string
     $response = Json::decode($json, $this->jsonDecodeDepthLimit);
     // create a new collection
     if (is_array($response) && count($response) > 0) {
         // non-empty arrays are attempts at batch requests
         $collection = array();
         foreach ($response as $singleResponse) {
             $collection[] = $this->createFrom($singleResponse);
         }
         return new BatchResponse($collection);
     } else {
         // all other valid json is treated as a single request
         return $this->createFrom($response);
     }
 }
示例#22
0
function setInvite($TML)
{
    if (!isset($_REQUEST['autoinviteid'])) {
        return;
    }
    $invite = MapperFactory::getMapper("AutoInvite")->getById($_REQUEST['autoinviteid']);
    if ($invite === null) {
        header("Location: " . AdminURL::getInstance()->getURL("auto_invites"));
        exit;
    }
    $TML->assign("text", $invite['text']);
    $json = new Json(SERVICES_JSON_LOOSE_TYPE);
    $conditions = $json->decode($invite['conditions']);
    if (isset($conditions['came_from'])) {
        $TML->assign("came_from", $conditions['came_from']);
    }
    if (isset($conditions['number_of_pages'])) {
        $TML->assign("number_of_pages", $conditions['number_of_pages']);
    }
    if (isset($conditions['time_on_site'])) {
        $TML->assign("time_on_site", $conditions['time_on_site']);
    }
    if (isset($conditions['order_matters'])) {
        $TML->assign("order_matters", 1);
    }
    if (isset($conditions['visited_pages']) && is_array($conditions['visited_pages'])) {
        $visted_page = array();
        $visted_page_time = array();
        foreach ($conditions['visited_pages'] as $v) {
            if (isset($v['url']) && isset($v['time'])) {
                $visited_page[] = "/" . trim($v['url'], "/");
                $visited_page_time[] = $v['time'];
            }
        }
        $TML->assign("visited_page", $visited_page);
        $TML->assign("visited_page_time", $visited_page_time);
    }
}
示例#23
0
 /**
  * {@inheritdoc}
  */
 public function decode(DataType $type, $value)
 {
     if (!isset($value)) {
         return null;
     }
     switch ($type->type) {
         case DataType::BOOLEAN:
             return $value != 0;
         case DataType::INTEGER:
         case DataType::DATE:
         case DataType::DATETIME:
             return intval($value);
         case DataType::FLOAT:
             return floatval($value);
         case DataType::TEXT:
         case DataType::BINARY:
         case DataType::STRING:
         case DataType::ENUM:
             return strval($value);
         case DataType::OBJECT:
             return Json::decode($value);
     }
 }
示例#24
0
 public static function reverse($latitude, $longitude, $api_key = '')
 {
     $temp = TempStore::getInstance();
     $key = 'googlemaps/reverse//' . $latitude . '/' . $longitude;
     $data = $temp->get($key);
     if ($data) {
         return unserialize($data);
     }
     $url = 'http://maps.googleapis.com/maps/api/geocode/json' . '?sensor=false' . ($api_key ? '&key=' . $api_key : '') . '&latlng=' . $latitude . ',' . $longitude;
     $json = Json::decode($url);
     if ($json->status != "OK") {
         return false;
     }
     $item = $json->results[0];
     //d($item);
     $res = new GeoLookupResult();
     //$res->accuracy     = $item->AddressDetails->Accuracy;
     $res->description = $item->formatted_address;
     //$res->country_code = $item->AddressDetails->Country->CountryNameCode;
     //$res->country_name = $item->AddressDetails->Country->CountryName;
     $temp->set($key, serialize($res));
     return $res;
 }
示例#25
0
 /**
  * use coupon before create order
  * @author cangzhou.wu(wucangzhou@gmail.com)
  * @param $event
  */
 public function useCoupon($event)
 {
     /** @var  $order Order */
     $order = $event->sender;
     /** @var  $couponModel  Coupon */
     $couponModel = Coupon::findOne(Yii::$app->getSession()->get(self::SESSION_COUPON_MODEL_KEY));
     if ($couponModel) {
         $couponRuleModel = $couponModel->couponRule;
         $result = Json::decode($couponRuleModel->result);
         if ($result['type']) {
             $order->total_price = $order->total_price * $result['number'];
         } else {
             $order->total_price = $order->total_price - $result['number'];
         }
         switch ($result['shipping']) {
             case 1:
                 $order->shipping_fee = $order->shipping_fee - $result['shippingFee'];
                 break;
             case 2:
                 $order->shipping_fee = 0;
         }
         Event::on(Order::className(), Order::EVENT_AFTER_INSERT, [ShoppingCoupon::className(), 'updateCouponStatus'], ['couponModel' => $couponModel]);
     }
 }
示例#26
0
 /**
  * Save item
  * @return boolean
  */
 public function save()
 {
     if (!$this->validate()) {
         return false;
     }
     //$this->beforeSave();
     $authManager = Yii::$app->authManager;
     // Create new item
     if ($this->getType() == Item::TYPE_ROLE) {
         $item = $authManager->createRole($this->name);
     } else {
         $item = $authManager->createPermission($this->name);
     }
     // Set item data
     $item->description = $this->description;
     $item->ruleName = $this->ruleName;
     $item->data = $this->data === null || $this->data === '' ? null : Json::decode($this->data);
     // save
     if ($this->item == null && !$authManager->add($item)) {
         return false;
     } else {
         if ($this->item !== null && !$authManager->update($this->item->name, $item)) {
             return false;
         }
     }
     $isNewRecord = $this->item == null ? true : false;
     $this->isNewRecord = !$isNewRecord;
     $this->item = $item;
     //$this->afterSave($isNewRecord,$this->attributes);
     if ($this->getType() == Item::TYPE_ROLE) {
         $role = $authManager->getRole($this->item->name);
         if (!$isNewRecord) {
             $authManager->removeChildren($role);
         }
         if ($this->permissions != null && is_array($this->permissions)) {
             foreach ($this->permissions as $permissionName) {
                 $permistion = $authManager->getPermission($permissionName);
                 $authManager->addChild($role, $permistion);
             }
         }
     }
     return true;
 }
示例#27
0
function load_psets_json($exclude_overrides)
{
    $datamap = psets_json_data($exclude_overrides);
    if (!count($datamap)) {
        Multiconference::fail_message("\$Opt[\"psetsConfig\"] is not set correctly.");
    }
    $json = (object) array("_defaults" => (object) array());
    foreach ($datamap as $fname => $data) {
        if ($data === false) {
            Multiconference::fail_message("{$fname}: Required configuration file cannot be read.");
        }
        $x = json_decode($data);
        if (!$x) {
            Json::decode($data);
            // our JSON decoder provides error positions
            Multiconference::fail_message("{$fname}: Invalid JSON. " . Json::last_error_msg());
        } else {
            if (!is_object($x)) {
                Multiconference::fail_message("{$fname}: Not a JSON object.");
            }
        }
        object_replace_recursive($json, $x);
    }
    return $json;
}
 private static function add_json($jlist, $fixed, $landmark)
 {
     if (is_string($jlist)) {
         if (($jlistx = json_decode($jlist)) !== false) {
             $jlist = $jlistx;
         } else {
             if (json_last_error()) {
                 Json::decode($jlist);
                 error_log("{$landmark}: Invalid JSON. " . Json::last_error_msg());
                 return;
             }
         }
         if (is_object($jlist)) {
             $jlist = [$jlist];
         }
     }
     foreach ($jlist as $oj) {
         if (is_object($oj) && isset($oj->id) && isset($oj->name)) {
             if (is_string($oj->id) && is_numeric($oj->id)) {
                 $oj->id = intval($oj->id);
             }
             if (is_int($oj->id) && !isset(self::$jlist[$oj->id]) && $oj->id >= self::MINFIXEDID === $fixed && is_string($oj->name)) {
                 if (!isset($oj->abbr) || $oj->abbr == "") {
                     $oj->abbr = self::abbreviate($oj->name, $oj->id);
                 }
                 self::$jlist[$oj->id] = $oj;
                 continue;
             }
         }
         error_log("{$landmark}: bad option " . json_encode($oj));
     }
 }
示例#29
0
 function json_decode($x, $assoc = false, $depth = 512, $options = 0)
 {
     return Json::decode($x, $assoc, $depth, $options);
 }
示例#30
0
         $attributes = '';
     }
     Extend::create(array('type' => $input['type'], 'pagetype' => $input['pagetype'], 'field' => $input['field'], 'key' => $input['key'], 'label' => $input['label'], 'attributes' => $attributes));
     Notify::success(__('extend.field_created'));
     return Response::redirect('admin/extend/fields');
 });
 /*
     Edit Field
 */
 Route::get('admin/extend/fields/edit/(:num)', function ($id) {
     $vars['token'] = Csrf::token();
     $vars['types'] = Extend::$types;
     $vars['fields'] = Extend::$field_types;
     $extend = Extend::find($id);
     if ($extend->attributes) {
         $extend->attributes = Json::decode($extend->attributes);
     }
     $vars['field'] = $extend;
     $vars['pagetypes'] = Query::table(Base::table('pagetypes'))->sort('key')->get();
     return View::create('extend/fields/edit', $vars)->partial('header', 'partials/header')->partial('footer', 'partials/footer');
 });
 Route::post('admin/extend/fields/edit/(:num)', function ($id) {
     $input = Input::get(array('type', 'field', 'key', 'label', 'attributes', 'pagetype'));
     if (empty($input['key'])) {
         $input['key'] = $input['label'];
     }
     $input['key'] = slug($input['key'], '_');
     array_walk_recursive($input, function (&$value) {
         $value = eq($value);
     });
     $validator = new Validator($input);