public function testProcessTranslationsEnableKey() { $language = CMTest_TH::createLanguage('test'); $languageKey = CM_Model_LanguageKey::create('Hello World'); $this->assertSame(false, $languageKey->getJavascript()); $site = CM_Site_Abstract::factory(); $render = new CM_Frontend_Render(new CM_Frontend_Environment(null, null, $language)); // Check that key is *not* included in the JS translations list $versionJavascript = CM_Model_Language::getVersionJavascript(); $request = new CM_Http_Request_Get($render->getUrlResource('library-js', "translations/{$versionJavascript}.js")); $response = CM_Http_Response_Resource_Javascript_Library::createFromRequest($request, $site, $this->getServiceManager()); $response->process(); $this->assertNotContains('Hello World', $response->getContent()); // Request JS-enabling of language key via RPC call $body = CM_Params::jsonEncode(['method' => 'CM_Model_Language.requestTranslationJs', 'params' => ['Hello World']]); $request = new CM_Http_Request_Post('/rpc', null, null, $body); $response = CM_Http_Response_RPC::createFromRequest($request, $site, $this->getServiceManager()); $response->process(); CMTest_TH::reinstantiateModel($languageKey); $this->assertSame(true, $languageKey->getJavascript()); // Check that key *is* included in the JS translations list $versionJavascript = CM_Model_Language::getVersionJavascript(); $request = new CM_Http_Request_Get($render->getUrlResource('library-js', "translations/{$versionJavascript}.js")); $response = CM_Http_Response_Resource_Javascript_Library::createFromRequest($request, $site, $this->getServiceManager()); $response->process(); $this->assertContains('Hello World', $response->getContent()); }
public function getSuggestion($location, CM_Frontend_Render $render) { $names = array(); for ($level = $location->getLevel(); $level >= CM_Model_Location::LEVEL_COUNTRY; $level--) { $names[] = $location->getName($level); } return array('id' => CM_Params::jsonEncode($location->toArray()), 'name' => implode(', ', array_filter($names)), 'img' => $render->getUrlResource('layout', 'img/flags/' . strtolower($location->getAbbreviation(CM_Model_Location::LEVEL_COUNTRY)) . '.png')); }
public function testProcessingInvalidMethod() { $body = CM_Params::jsonEncode(['method' => 'foo']); $request = new CM_Http_Request_Post('/rpc/' . CM_Site_Abstract::factory()->getType(), null, null, $body); $response = new CM_Http_Response_RPC($request, $this->getServiceManager()); $response->process(); $responseData = CM_Params::jsonDecode($response->getContent()); $this->assertSame(['error' => ['type' => 'CM_Exception_InvalidParam', 'msg' => 'Internal server error', 'isPublic' => false]], $responseData); }
public function testProcessReturnDeployVersion() { $body = CM_Params::jsonEncode(['method' => 'CM_Http_Response_RPCTest.add', 'params' => [2, 3]]); $site = $this->getMockSite(); $request = new CM_Http_Request_Post('/rpc', null, null, $body); $response = CM_Http_Response_RPC::createFromRequest($request, $site, $this->getServiceManager()); $response->process(); $responseDecoded = CM_Params::jsonDecode($response->getContent()); $this->assertArrayHasKey('deployVersion', $responseDecoded); $this->assertSame(CM_App::getInstance()->getDeployVersion(), $responseDecoded['deployVersion']); }
protected function _save(array $data) { $values = \Functional\map($data, function (DateTime $dateTime) { return $dateTime->getTimestamp(); }); $content = CM_Params::jsonEncode($values, true); $file = $this->_getStorageFile(); if (!$file->exists()) { $file->ensureParentDirectory(); } $file->write($content); }
/** * @param string $key * @param mixed $value * @return mixed * @throws CM_Exception_Invalid * @throws CM_Model_Exception_Validation */ public function encodeField($key, $value) { $key = (string) $key; if ($this->hasField($key)) { $schemaField = $this->_schema[$key]; if (null !== $value) { $type = isset($schemaField['type']) ? $schemaField['type'] : null; if (null !== $type) { switch ($type) { case 'integer': case 'int': $value = (int) $value; break; case 'float': $value = (double) $value; break; case 'string': break; case 'boolean': case 'bool': $value = (bool) $value; break; case 'array': break; case 'DateTime': /** @var DateTime $value */ $value = $value->getTimestamp(); break; default: if (!(class_exists($type) && is_subclass_of($type, 'CM_Model_Abstract'))) { throw new CM_Model_Exception_Validation('Field `' . $key . '` is not a valid model'); } if (!$value instanceof $type) { throw new CM_Model_Exception_Validation('Value `' . CM_Util::var_line($value) . '` is not an instance of `' . $type . '`'); } /** @var CM_Model_Abstract $value */ $id = $value->getIdRaw(); if (count($id) == 1) { $value = $value->getId(); } else { $value = CM_Params::jsonEncode($id); } } } } } return $value; }
/** * @param string[]|null $variables * @throws CM_Exception_Invalid */ public function setVariables(array $variables = null) { $previousVariables = $this->getVariables(); $variables = (array) $variables; $variables = array_values($variables); sort($variables); if ($previousVariables !== $variables) { $variablesEncoded = CM_Params::jsonEncode($variables); $this->_set('variables', $variablesEncoded); $this->_increaseUpdateCount(); if ($this->_getUpdateCount() > self::MAX_UPDATE_COUNT) { $message = ['Variables for languageKey `' . $this->getName() . '` have been updated over ' . self::MAX_UPDATE_COUNT . ' times since release.', 'Previous variables: `' . CM_Util::var_line($previousVariables) . '`', 'Current variables: `' . CM_Util::var_line($variables) . '`']; throw new CM_Exception_Invalid(join(PHP_EOL, $message)); } } }
/** * @return string */ public function getJs() { $js = ''; foreach ($this->_pageViewList as $pageView) { $url = CM_Params::jsonEncode($pageView); $js .= "ADGN.track.view({$url});"; } foreach ($this->_eventList as $event) { $eventType = 'ADGN.eventTypes.' . $event['eventType']; if (isset($event['data'])) { $data = CM_Params::jsonEncode($event['data']); $js .= "ADGN.track.event({$eventType}, {$data});"; } else { $js .= "ADGN.track.event({$eventType});"; } } return $js; }
/** * @param string $namespace */ private function _dbToFileMongo($namespace) { $mongo = CM_Service_Manager::getInstance()->getMongoDb(); $collectionList = \Functional\select($mongo->listCollectionNames(), function ($collection) use($namespace) { return preg_match('/^' . strtolower($namespace) . '_/', $collection); }); sort($collectionList); $optionsValid = ['unique', 'name', 'dropDups', 'sparse', 'expireAfterSeconds']; $indexes = []; foreach ($collectionList as $collection) { $indexList = $mongo->getIndexInfo($collection); foreach ($indexList as $indexInfo) { $key = $indexInfo['key']; $options = array_intersect_key($indexInfo, array_flip($optionsValid)); $indexes[$collection][] = ['key' => $key, 'options' => $options]; } } $dump = CM_Params::jsonEncode($indexes, true); $dirPath = CM_Util::getModulePath($namespace) . '/resources/mongo/'; CM_File::getFilesystemDefault()->ensureDirectory($dirPath); CM_File::create($dirPath . 'collections.json', $dump); }
public function getHtml(CM_Frontend_Environment $environment) { $scriptName = 'analytics.js'; if ($environment->isDebug()) { $scriptName = 'analytics_debug.js'; } $html = '<script type="text/javascript">'; $html .= <<<EOF (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/{$scriptName}','ga'); EOF; $fieldList = ['cookieDomain' => $environment->getSite()->getHost()]; if ($user = $environment->getViewer()) { $fieldList['userId'] = (string) $user->getId(); } $html .= 'ga("create", ' . CM_Params::jsonEncode($this->_getCode()) . ', ' . CM_Params::jsonEncode(array_filter($fieldList)) . ');'; $html .= $this->getJs(); $html .= '</script>'; return $html; }
public function testLoadPageTrackingRedirect() { $page = new CM_Page_View_Ajax_Test_MockRedirectSelf(); $request = $this->createRequestAjax($page, 'loadPage', ['path' => $page::getPath() . '?count=3']); $response = new CM_Http_Response_View_Ajax($request, $this->_getServiceManagerWithGA('ga123')); $response->process(); $this->assertViewResponseSuccess($response); $responseContent = CM_Params::decode($response->getContent(), true); $jsTracking = $responseContent['success']['data']['jsTracking']; $this->assertSame(1, substr_count($jsTracking, 'ga("send", "pageview"')); $pageview = CM_Params::jsonEncode($page::getPath() . '?count=0'); $this->assertContains('ga("send", "pageview", ' . $pageview . ')', $jsTracking); }
/** * @expectedException Exception */ public function testJsonEncodeInvalid() { $resource = fopen(sys_get_temp_dir(), 'r'); CM_Params::jsonEncode(['foo' => $resource]); }
/** * @param string $collection * @param array|null $criteria * @param array|null $options * @return mixed * @throws CM_MongoDb_Exception */ public function remove($collection, array $criteria = null, array $options = null) { $criteria = $criteria ?: array(); $options = $options ?: array(); CM_Service_Manager::getInstance()->getDebug()->incStats('mongo', "Remove `{$collection}`: " . CM_Params::jsonEncode($criteria)); $result = $this->_getCollection($collection)->remove($criteria, $options); $this->_checkResultForErrors($result); return is_array($result) ? $result['n'] : $result; }
public function testLoadPageTrackingRedirect() { $site = CM_Site_Abstract::factory(); $page = new CM_Page_View_Ajax_Test_MockRedirectSelf(); $env = new CM_Frontend_Environment($site, CMTest_TH::createUser()); $params = ['path' => $page::getPath() . '?count=3', 'currentLayout' => $page->getLayout($env)]; $request = $this->createRequestAjax($page, 'loadPage', $params); $response = CM_Http_Response_View_Ajax::createFromRequest($request, $site, $this->_getServiceManagerWithGA('ga123')); $response->process(); $this->assertViewResponseSuccess($response); $responseContent = CM_Params::decode($response->getContent(), true); $jsTracking = $responseContent['success']['data']['jsTracking']; $this->assertSame(1, substr_count($jsTracking, 'ga("send", "pageview"')); $pageview = CM_Params::jsonEncode($page::getPath() . '?count=0'); $this->assertContains('ga("send", "pageview", ' . $pageview . ')', $jsTracking); }
/** * @param CM_Frontend_TreeNode $node * @return string */ private function _getTreeNodeInitJs(CM_Frontend_TreeNode $node) { $viewResponse = $node->getValue(); $reference = 'cm.views["' . $viewResponse->getAutoId() . '"]'; $view = $viewResponse->getView(); $code = $reference . ' = new ' . get_class($view) . '({'; $code .= 'el:$("#' . $viewResponse->getAutoId() . '").get(0),'; $code .= 'params:' . CM_Params::jsonEncode($view->getParams()->getParamsEncoded()); if (!$node->isRoot()) { $code .= ',parent: cm.views["' . $node->getParent()->getValue()->getAutoId() . '"]'; } $code .= '});'; return $code; }