/** * return geojson representation of test points given either * * - neighborhood name and region name */ public function showAction() { $neighborhood_name = $this->getRequestParameter('neighborhood'); $region_name = $this->getRequestParameter('region'); $grid_resolution = $this->getRequestParameter('grid-res'); if (empty($neighborhood_name) or empty($region_name) or empty($grid_resolution)) { die("neighborhood_name,region_name and grid_res must all be defined"); } $neighborhood = $this->m()->neighborhoodMapper()->byName($neighborhood_name, $region_name); if (empty($neighborhood)) { die("no neighborhood found"); } $user_polygons = $this->m()->userPolygonMapper()->byNeighborhood($neighborhood); if (empty($user_polygons)) { die("no user polygons found for neighborhood"); } $timer = \Whathood\Timer::start('api'); $points = $this->m()->testPointMapper()->createByUserPolygons($user_polygons, $grid_resolution); $test_point_ms = $timer->elapsed_milliseconds(); $test_point_count = count($points); $this->logger()->info(sprintf("generated %s test points in %sms; %sms per 1000 points", $test_point_count, $test_point_ms, round($test_point_ms / $test_point_count * 1000, 1))); if (empty($points)) { die("no points returned with grid_resolution {$grid_resolution}"); } $timer = \Whathood\Timer::start('election'); $consensus_col = $this->m()->electionMapper()->buildElectionPointCollection($points); $consensus_seconds = $timer->elapsed_seconds(); $this->logger()->info(sprintf("got consensus in %s seconds; %sms per point", $consensus_seconds, round($consensus_seconds / count($points) * 1000, 2))); $timer = \Whathood\Timer::start('election'); $consensus_col = $this->m()->electionMapper()->buildElectionPointCollection($points); $points = $consensus_col->pointsByNeighborhoodId($neighborhood->getId()); \Zend\Debug\Debug::dump(get_class($points[0])); print Json::encode(\Whathood\Spatial\Util::multiPointToGeoJsonArray(new WhMultiPoint($points))); }
/** * Converts an associative array to a string of tag attributes. * * @access public * * @param array $attribs From this array, each key-value pair is * converted to an attribute name and value. * * @return string The XHTML for the attributes. */ protected function htmlAttribs($attribs) { $xhtml = ''; $escaper = $this->getView()->plugin('escapehtml'); foreach ((array) $attribs as $key => $val) { $key = $escaper($key); if ('on' == substr($key, 0, 2) || 'constraints' == $key) { // Don't escape event attributes; _do_ substitute double quotes with singles if (!is_scalar($val)) { // non-scalar data should be cast to JSON first $val = \Zend\Json\Json::encode($val); } // Escape single quotes inside event attribute values. // This will create html, where the attribute value has // single quotes around it, and escaped single quotes or // non-escaped double quotes inside of it $val = str_replace('\'', ''', $val); } else { if (is_array($val)) { $val = implode(' ', $val); } $val = $escaper($val); } if ('id' == $key) { $val = $this->normalizeId($val); } if (strpos($val, '"') !== false) { $xhtml .= " {$key}='{$val}'"; } else { $xhtml .= " {$key}=\"{$val}\""; } } return $xhtml; }
/** * Render the view into a string and return for output * * @param mixed $input * @return string */ public function render($input = null) { $output = (object) $this->template; if (isset($input["status"])) { $output->status = $input["status"]; } else { unset($output->status); } if (isset($input["errors"])) { $output->errors = $input["errors"]; } else { unset($output->errors); } if (isset($input["data"])) { $output->data = $input["data"]; } else { unset($output->data); } if (isset($input["messages"])) { $output->messages = $input["messages"]; } else { unset($output->messages); } return Json::encode($input); }
protected function callGa(array $params) { $jsArray = Json::encode($params); $jsArrayAsParams = substr($jsArray, 1, -1); $output = sprintf("\n" . '%s(%s);', $this->getFunctionName(), $jsArrayAsParams); return $output; }
/** * Encode data as JSON, disable layouts, and set response header * * If $keepLayouts is true, does not disable layouts. * * @param mixed $data * @param bool $keepLayouts * NOTE: if boolean, establish $keepLayouts to true|false * if array, admit params for Zend_Json::encode as enableJsonExprFinder=>true|false * this array can contains a 'keepLayout'=>true|false * that will not be passed to Zend_Json::encode method but will be used here * @return string|void */ public function direct($data = null, $keepLayouts = false) { if ($data == null) { throw new \InvalidArgumentException('JSON: missing argument. $data is required in json($data, $keepLayouts = false)'); } $options = array(); if (is_array($keepLayouts)) { $options = $keepLayouts; $keepLayouts = (array_key_exists('keepLayouts', $keepLayouts)) ? $keepLayouts['keepLayouts'] : false; unset($options['keepLayouts']); } $data = \Zend\Json\Json::encode($data, null, $options); if (!$keepLayouts) { $layout = LayoutManager::getMvcInstance(); if ($layout instanceof LayoutManager) { $layout->disableLayout(); } } $response = \Zend\Controller\Front::getInstance()->getResponse(); $response->setHeader('Content-Type', 'application/json'); return $data; }
/** * Validate a field and return validation messages on failure * * @throws \InvalidArgumentException * @return \Zend\Stdlib\ResponseInterface */ public function validateAction() { /** @var $request \Zend\Http\PhpEnvironment\Request */ $request = $this->getRequest(); $response = $this->getResponse(); $data = $request->getPost()->toArray(); if (count($data) > 1) { throw new \InvalidArgumentException('Validating multiple fields is not allowed'); } if (empty($data)) { throw new \InvalidArgumentException('No input data received'); } $formAlias = $this->getEvent()->getRouteMatch()->getParam('form'); /** @var $form \Zend\Form\FormInterface */ $form = $this->getFormManager()->get($formAlias); $filter = $form->getInputFilter(); $filter->setData($data); $filter->setValidationGroup($this->convertDataArrayToValidationGroup($data)); $valid = $filter->isValid(); if (!$valid) { $messages = $filter->getMessages(); $result = false; array_walk_recursive($messages, function ($item) use(&$result) { if (is_string($item)) { $result = $item; } }); } else { $result = true; } $response->setContent(\Zend\Json\Json::encode($result)); return $response; }
/** * Defined by Zend\ProgressBar\Adapter\AbstractAdapter * * @param float $current Current progress value * @param float $max Max progress value * @param float $percent Current percent value * @param int $timeTaken Taken time in seconds * @param int $timeRemaining Remaining time in seconds * @param string $text Status text * @return void */ public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text) { $arguments = array('current' => $current, 'max' => $max, 'percent' => $percent * 100, 'timeTaken' => $timeTaken, 'timeRemaining' => $timeRemaining, 'text' => $text); $data = 'parent.' . $this->updateMethodName . '(' . Json::encode($arguments) . ');'; // Output the data $this->_outputData($data); }
public static function arrayToJsonString($aDane) { ob_start(); echo \Zend\Json\Json::encode($aDane); $sOut = ob_get_clean(); return $sOut; }
public function validatepostajaxAction() { $form = $this->getForm(); $request = $this->getRequest(); $response = $this->getResponse(); $messages = array(); if ($request->isPost()) { $form->setData($request->getPost()); $formValidador = new ValidaFormulario(); $form->setInputFilter($formValidador->getInputFilter()); echo "es valido2: " . "<pre>" . print_r($form->isValid(), true) . "</pre>"; if (!$form->isValid()) { $errors = $form->getMessages(); foreach ($errors as $key => $row) { if (!empty($row) && $key != 'enviar') { foreach ($row as $keyer => $rower) { //save error(s) per-element that //needed by Javascript $messages[$key][] = $rower; } } } } if (!empty($messages)) { $response->setContent(\Zend\Json\Json::encode($messages)); } else { //save to db <span class="wp-smiley wp-emoji wp-emoji-wink" title=";)">;)</span> echo "son válidos los datos"; //$this->savetodb($form->getData()); $response->setContent(\Zend\Json\Json::encode(array('success' => 1))); } } return $response; }
/** * Defined by Zend\ProgressBar\Adapter\AbstractAdapter * * @param float $current Current progress value * @param float $max Max progress value * @param float $percent Current percent value * @param int $timeTaken Taken time in seconds * @param int $timeRemaining Remaining time in seconds * @param string $text Status text * @return void */ public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text) { $arguments = ['current' => $current, 'max' => $max, 'percent' => $percent * 100, 'timeTaken' => $timeTaken, 'timeRemaining' => $timeRemaining, 'text' => $text]; $data = '<script type="text/javascript">' . 'parent.' . $this->updateMethodName . '(' . Json::encode($arguments) . ');' . '</script>'; // Output the data $this->_outputData($data); }
public function dataAction() { $response = $this->getResponse(); $grid = $this->grid('Application\\Index\\Index', array('-', 'id', 'title', 'category', 'username', 'created_at', '-')); if (isset($this->getSessionContainer()->parent_id)) { $grid['parent_id'] = $this->getSessionContainer()->parent_id; } $result = $this->getResourceTable()->fetchDataGrid($grid); $adapter = new ArrayAdapter($result); $paginator = new Paginator($adapter); $page = ceil(intval($grid['start']) / intval($grid['length'])) + 1; $paginator->setCurrentPageNumber($page); $paginator->setItemCountPerPage(intval($grid['length'])); $data = array(); $data['data'] = array(); foreach ($paginator as $row) { $category = array_key_exists('category', $row) ? $row['category'] : '-'; $title = $row['node_type'] == \Application\Model\Resource::NODE_TYPE_CATEGORY ? '<a href="/admin/resource/parent_id/' . $row['id'] . '" title="' . strip_tags($row['description']) . '">' . strip_tags($row['title']) . '</a>' : '<i>' . strip_tags($row['title']) . '</i>'; $actions = ''; if ($row['url']) { $actions .= '<a class="btn btn-xs btn-outline blue-steel btn-view" href="' . $row['url'] . '" data-id="' . $row['id'] . '" target="_blank">View</a> '; } $actions .= '<a class="btn btn-xs btn-outline red" href="/admin/resource/delete/id/' . $row['id'] . '" onclick="return confirm("Are you sure you wish to delete selected resources?");">Delete</a>'; $data['data'][] = array('<input type="checkbox" name="id[' . $row['id'] . ']" value="' . $row['id'] . '" />', '<a class="btn btn-xs btn-outline blue-steel btn-view" href="/admin/resource/edit/id/' . $row['id'] . '/parent_id/' . $row['parent_id'] . '" title="' . $row['id'] . '">Edit: ' . $row['id'] . '</a>', $title, $category, $row['username'], date('F jS Y', strtotime($row['created_at'])), $actions); } $data['page'] = $page; $data['grid'] = $grid; $data['draw'] = intval($grid['draw']); $data['recordsTotal'] = $paginator->getTotalItemCount(); $data['recordsFiltered'] = $paginator->getTotalItemCount(); $response->setStatusCode(200); $response->setContent(Json::encode($data)); return $response; }
public function convertToDatabaseValue($value, AbstractPlatform $platform) { if (null === $value) { return null; } return Json::encode($value); }
/** * Override serialize() * * Tests for the special top-level variable "payload", set by ZF\Rest\RestController. * * If discovered, the value is pulled and used as the variables to serialize. * * A further check is done to see if we have a ZF\Hal\Entity or * ZF\Hal\Collection, and, if so, we pull the top-level entity or * collection and serialize that. * * @return string */ public function serialize() { $variables = $this->getVariables(); // 'payload' == payload for HAL representations if (isset($variables['payload'])) { $variables = $variables['payload']; } // Use ZF\Hal\Entity's composed entity if ($variables instanceof HalEntity) { $variables = method_exists($variables, 'getEntity') ? $variables->getEntity() : $variables->entity; // v1.0-1.1.* } // Use ZF\Hal\Collection's composed collection if ($variables instanceof HalCollection) { $variables = $variables->getCollection(); } if (null !== $this->jsonpCallback) { return $this->jsonpCallback . '(' . Json::encode($variables) . ');'; } $serialized = Json::encode($variables); if (false === $serialized) { $this->raiseError(json_last_error()); } return $serialized; }
public function testCanSerializeWithJsonpCallback() { $array = array('foo' => 'bar'); $model = new JsonModel($array); $model->setJsonpCallback('callback'); $this->assertEquals('callback(' . Json::encode($array) . ');', $model->serialize()); }
/** * 更新安全密码 * * @author young * @name 更新安全密码 * @version 2014.01.02 young * @return JsonModel */ public function updateAction() { $oldPassword = trim($this->params()->fromPost('oldPassword', '')); $password = trim($this->params()->fromPost('password', '')); $repeatPassword = trim($this->params()->fromPost('repeatPassword', '')); $active = filter_var($this->params()->fromPost('active', ''), FILTER_VALIDATE_BOOLEAN); $criteria = array('project_id' => $this->_project_id, 'collection_id' => $this->_collection_id); $lockInfo = $this->_lock->findOne($criteria); if ($lockInfo != null) { if (empty($oldPassword)) { return $this->msg(true, '请输入原密码'); } if (sha1($oldPassword) !== $lockInfo['password']) { return $this->msg(true, '身份验证未通过'); } } if (empty($password) || empty($repeatPassword)) { return $this->msg(true, '请输入新密码或者确认密码'); } if ($password !== $repeatPassword) { return $this->msg(true, '两次密码输入不一致'); } $datas = array('password' => sha1($password), 'active' => $active); if ($active) { $rst = $this->_lock->update($criteria, array('$set' => $datas), array('upsert' => true)); if ($rst['ok']) { return $this->msg(true, '设定集合访问密钥成功'); } else { return $this->msg(false, Json::encode($rst)); } } else { $this->_lock->remove($criteria); return $this->msg(true, '清除安全密钥成功'); } }
/** * Converts an associative array to a string of tag attributes. * * @access public * * @param array $attribs From this array, each key-value pair is * converted to an attribute name and value. * * @return string The XHTML for the attributes. */ protected function htmlAttribs($attribs) { $xhtml = ''; $escaper = $this->getView()->plugin('escapehtml'); $escapeHtmlAttr = $this->getView()->plugin('escapehtmlattr'); foreach ((array) $attribs as $key => $val) { $key = $escaper($key); if ('on' == substr($key, 0, 2) || 'constraints' == $key) { // Don't escape event attributes; _do_ substitute double quotes with singles if (!is_scalar($val)) { // non-scalar data should be cast to JSON first $val = \Zend\Json\Json::encode($val); } } else { if (is_array($val)) { $val = implode(' ', $val); } } $val = $escapeHtmlAttr($val); if ('id' == $key) { $val = $this->normalizeId($val); } if (strpos($val, '"') !== false) { $xhtml .= " {$key}='{$val}'"; } else { $xhtml .= " {$key}=\"{$val}\""; } } return $xhtml; }
/** * Render a Zend_Config into a JSON config string. * * @since 1.10 * @return string */ public function render() { $data = $this->_config->toArray(); $sectionName = $this->_config->getSectionName(); $extends = $this->_config->getExtends(); if (is_string($sectionName)) { $data = array($sectionName => $data); } foreach ($extends as $section => $parentSection) { $data[$section][JsonConfig::EXTENDS_NAME] = $parentSection; } // Ensure that each "extends" section actually exists foreach ($data as $section => $sectionData) { if (is_array($sectionData) && isset($sectionData[JsonConfig::EXTENDS_NAME])) { $sectionExtends = $sectionData[JsonConfig::EXTENDS_NAME]; if (!isset($data[$sectionExtends])) { // Remove "extends" declaration if section does not exist unset($data[$section][JsonConfig::EXTENDS_NAME]); } } } $out = JsonUtil::encode($data); if ($this->prettyPrint()) { $out = JsonUtil::prettyPrint($out); } return $out; }
public function validatepostajaxAction() { $form = $this->getForm(); $request = $this->getRequest(); $response = $this->getResponse(); $messages = array(); if ($request->isPost()) { $form->setData($request->getPost()); if (!$form->isValid()) { $errors = $form->getMessages(); foreach ($errors as $key => $row) { if (!empty($row) && $key != 'submit') { foreach ($row as $keyer => $rower) { $messages[$key][] = $rower; } } } } if (!empty($messages)) { $response->setContent(\Zend\Json\Json::encode($messages)); } else { //save to db ;) $this->savetodb($form->getData()); $response->setContent(\Zend\Json\Json::encode(array('success' => 1))); } } return $response; }
public function indexAction() { // 获取到请求的JSON字符串 $content = $this->request->getContent(); $this->writeConfig(); $this->errorService = $this->getServiceLocator()->get("error_service"); $this->_log = $this->getServiceLocator()->get('DhErrorLogging\\Logger'); if (empty($content)) { // 判断请求数据是否为空,直接返回给客户端,不做进一步的处理 $this->_log->err('接收到的指令为空!'); $returnMsg = $this->_processEmptyMsg(); $this->response->setContent($returnMsg); return $this->response; } try { Json::$useBuiltinEncoderDecoder = true; $ac = Json::decode($content, Json::TYPE_ARRAY); $this->_log->debug('action is: ' . var_export($ac, true)); } catch (\Exception $e) { $this->_log->err('Json解码失败!'); $codeMsg = $this->_errorCodeMeg('00000003'); $returnMsg = urldecode(Json::encode($codeMsg)); $this->response->setContent($returnMsg); return $this->response; } // 接口指令处理 if (array_key_exists($ac['action'], $this->_actionToService)) { $service = $this->getServiceLocator()->get($this->_actionToService[$ac['action']]); // 获取可用的openstack节点组 $osGroup = $this->getOSGroup(); // 对调用具体指令时捕获异常 try { $checkAuth = $service->checkSignature(json_decode($content, true)); if (!$checkAuth) { echo json_encode(array("code" => -1, "msg" => "authentication failed")); exit; } $service->setReader(); $service->getToken(); $result = $service->{$ac}['action']($ac['data']); $returnData = urldecode($result); $this->_log->debug($this->_actionToService[$ac['action']] . ' :' . $returnData . PHP_EOL); $this->response->setContent($returnData); return $this->response; } catch (\Exception $e) { file_put_contents('error_index.log', $e->getMessage() . $e->getCode() . PHP_EOL, FILE_APPEND); $this->_log->err('调用服务出错:' . $e->getMessage() . $e->getCode() . PHP_EOL); $codeMsg = $this->_errorCodeMeg('00000004'); $returnMsg = urldecode(Json::encode($codeMsg)); $this->response->setContent($returnMsg); return $this->response; } } else { $codeMsg = $this->_errorCodeMeg('00000002'); $returnMsg = urldecode(Json::encode($codeMsg)); $this->response->setContent($returnMsg); return $this->response; } }
public function testGetClientById() { $jsonData = \Zend\Json\Json::encode(array('clients' => array(array('id' => 'test-client', 'type' => 'public', 'redirect_uri' => 'http://uri', 'authentication' => array('type' => 'secret', 'options' => array('secret' => 'xxx')))))); file_put_contents($this->_jsonFile, $jsonData); $client = $this->_storage->getClientById('test-client'); $this->assertInstanceOf('\\InoOicServer\\Client\\Client', $client); $this->assertEquals('test-client', $client->getId()); }
/** * Serialize to JSON * * @return string */ public function serialize() { if (!isset($this->errCode) || $this->errCode == 0) { $this->errCode = 1001; } $ret = array('status' => $this->errCode, 'message' => $this->errMessage, 'content' => null); return Json::encode($ret); }
/** * @return string */ public function __toString() { $data = []; foreach ($this->options as $key => $value) { $data[$key] = $this->getValue($value); } return Json::encode($data, false, ['enableJsonExprFinder' => true]); }
/** * Trims and validates password against regex * * @param string $password * @return string * @throws Exception */ public static function validatePassword($password) { $validator = new Regex(['pattern' => '/((?=.*\\d)(?=.*[a-zA-Z]).{8,20})/U']); if (!$validator->isValid((new StringTrim())->filter($password))) { throw new Exception(Json::encode($validator->getMessages())); } return $password; }
public function response() { $resultJson = Json::encode($this->returnEntity); $response = new \Zend\Http\Response(); $response->getHeaders()->addHeaderLine('Content-Type', 'text/html; charset=utf-8'); $response->setContent($resultJson); return $response; }
public function write($contents) { parent::write($contents); //check if $contents is array if (is_array($contents) && !empty($contents)) { $this->getSessionManager()->getSaveHandler()->write($this->getSessionId(), \Zend\Json\Json::encode($contents)); } }
public function validateformajaxAction() { if ($this->getRequest()->isPost()) { $oResponse = $this->getResponse(); $aPostData = $this->getRequest()->getPost(); $aClassName = explode('_', $aPostData['form_name']); if (is_array($aClassName) && count($aClassName)) { $sClassName = ''; foreach ($aClassName as $nKey => $sValue) { $sClassName .= ucfirst($sValue); } } else { $sClassName = ucfirst($aPostData['form_name']); } $aValidationGroup = $aPostData['validation_group']; $sFormServiceName = $sClassName . 'FormService'; $sInputFilterServiceName = $sClassName . 'InputFilterService'; $aValidElements = array(); $aResponse = array(); if ($this->getServiceLocator()->has($sFormServiceName) && $this->getServiceLocator()->has($sInputFilterServiceName) && is_array($aPostData['valid'])) { $oFormInstance = $this->getServiceLocator()->get($sFormServiceName); $oInputFilterInstance = $this->getServiceLocator()->get($sInputFilterServiceName); if (isset($aPostData['valid'])) { foreach ($aPostData['valid'] as $aValue) { if ($aValue['tag_name'] === 'select' && strpos($aValue['name'], '[]')) { $sNewElementName = str_replace('[]', '', $aValue['name']); if (!isset($aValidElements[$sNewElementName])) { $aValidElements[$sNewElementName] = array(); } if ($aValue['value']) { foreach ($aValue['value'] as $nKey => $mValue) { array_push($aValidElements[$sNewElementName], $mValue); } } } else { $aValidElements[$aValue['name']] = $aValue['value']; } } } if (is_array($aValidationGroup) && count($aValidationGroup)) { $oFormInstance->setValidationGroup($aValidationGroup); } $oFormInstance->setInputFilter($oInputFilterInstance->getInputFilter())->setData($aValidElements); if (isset($aPostData['fake_required'])) { foreach ($aPostData['fake_required'] as $aValue) { if (isset($aValue['depend_element'])) { $oFormInstance->getInputFilter()->get($aValue['name'])->setRequired(true); } } } if (!$oFormInstance->isValid()) { $aResponse = $oFormInstance->getMessages(); } } $oResponse->setContent(\Zend\Json\Json::encode(array('response' => $aResponse))); return $oResponse; } }
public function toJson() { $jsonData = array(); foreach ($this->points as $r) { $arr = array('lat' => $r['y'], 'lon' => $r['x'], 'value' => $r['value']); array_push($jsonData, $arr); } return \Zend\Json\Json::encode($jsonData); }
/** * Encode data as JSON and set response header * * @param mixed $data * @param array $jsonOptions Options to pass to JsonFormatter::encode() * @return string|void */ public function __invoke($data, array $jsonOptions = array()) { $data = JsonFormatter::encode($data, null, $jsonOptions); if ($this->response instanceof Response) { $headers = $this->response->getHeaders(); $headers->addHeaderLine('Content-Type', 'application/json'); } return $data; }
public function argsAction() { $job = $this->api()->read('jobs', $this->params('id'))->getContent(); $args = Json::prettyPrint(Json::encode($job->args()), ['indent' => ' ']); $response = $this->getResponse(); $response->getHeaders()->addHeaderLine('Content-Type', 'text/plain; charset=utf-8'); $response->setContent($args); return $response; }
/** * Serialize PHP value to JSON * * @param mixed $value * @param array $opts * @return string * @throws \Zend\Serializer\Exception on JSON encoding exception */ public function serialize($value, array $opts = array()) { $opts = $opts + $this->_options; try { return ZendJson::encode($value, $opts['cycleCheck'], $opts); } catch (\Exception $e) { throw new SerializationException('Serialization failed', 0, $e); } }