/** * @todo . */ public function messageHandler() { if (!isset($_POST['serviceKey']) || !nodejs_is_valid_service_key($_POST['serviceKey'])) { return new JsonResponse(array('error' => 'Invalid service key.')); } if (!isset($_POST['messageJson'])) { return new JsonResponse(array('error' => 'No message.')); } $message = Json::decode($_POST['messageJson']); $response = array(); switch ($message['messageType']) { case 'authenticate': $response = nodejs_auth_check($message); break; case 'userOffline': nodejs_user_set_offline($message['uid']); break; default: $handlers = array(); foreach (module_implements('nodejs_message_callback') as $module) { $function = $module . '_nodejs_message_callback'; $handlers += $function($message['messageType']); } foreach ($handlers as $callback) { $callback($message, $response); } } \Drupal::moduleHandler()->alter('nodejs_message_response', $response, $message); return new JsonResponse($response ? $response : array('error' => 'Not implemented')); }
/** * Attempts to decode the incoming request's content as JSON. * * @param \Symfony\Component\HttpFoundation\Request $request * * @return mixed * * @throws \Drupal\panels_ipe\Exception\EmptyRequestContentException */ protected static function decodeRequest(Request $request) { if (empty($request->getContent())) { throw new EmptyRequestContentException(); } return Json::decode($request->getContent()); }
/** * Tests an ajax view. */ public function testAjaxView() { $this->drupalGet('test_ajax_view'); $drupal_settings = $this->getDrupalSettings(); $this->assertTrue(isset($drupal_settings['views']['ajax_path']), 'The Ajax callback path is set in drupalSettings.'); $this->assertEqual(count($drupal_settings['views']['ajaxViews']), 1); $view_entry = array_keys($drupal_settings['views']['ajaxViews'])[0]; $this->assertEqual($drupal_settings['views']['ajaxViews'][$view_entry]['view_name'], 'test_ajax_view', 'The view\'s ajaxViews array entry has the correct \'view_name\' key.'); $this->assertEqual($drupal_settings['views']['ajaxViews'][$view_entry]['view_display_id'], 'page_1', 'The view\'s ajaxViews array entry has the correct \'view_display_id\' key.'); $data = array(); $data['view_name'] = 'test_ajax_view'; $data['view_display_id'] = 'test_ajax_view'; $post = array('view_name' => 'test_ajax_view', 'view_display_id' => 'page_1'); $post += $this->getAjaxPageStatePostData(); $response = $this->drupalPost('views/ajax', 'application/vnd.drupal-ajax', $post); $data = Json::decode($response); $this->assertTrue(isset($data[0]['settings']['views']['ajaxViews'])); $this->assertEqual($data[1]['command'], 'add_css'); // Ensure that the view insert command is part of the result. $this->assertEqual($data[2]['command'], 'insert'); $this->assertTrue(strpos($data[2]['selector'], '.js-view-dom-id-') === 0); $this->setRawContent($data[2]['data']); $result = $this->xpath('//div[contains(@class, "views-row")]'); $this->assertEqual(count($result), 2, 'Ensure that two items are rendered in the HTML.'); }
/** * Test base logic for the Juicebox field formatter. */ public function testFieldFormatter() { $node = $this->node; $xml_path = 'juicebox/xml/field/node/' . $node->id() . '/' . $this->instFieldName . '/full'; $xml_url = \Drupal::url('juicebox.xml_field', array('entityType' => 'node', 'entityId' => $node->id(), 'fieldName' => $this->instFieldName, 'displayName' => 'full')); // Get the urls to the test image and thumb derivative used by default. $uri = \Drupal\file\Entity\File::load($node->{$this->instFieldName}[0]->target_id)->getFileUri(); $test_image_url = entity_load('image_style', 'juicebox_medium')->buildUrl($uri); $test_thumb_url = entity_load('image_style', 'juicebox_square_thumb')->buildUrl($uri); // Check for correct embed markup. $this->drupalGet('node/' . $node->id()); $this->assertRaw(trim(json_encode(array('configUrl' => $xml_url)), '{}"'), 'Gallery setting found in Drupal.settings.'); $this->assertRaw('id="node--' . $node->id() . '--' . str_replace('_', '-', $this->instFieldName) . '--full"', 'Embed code wrapper found.'); $this->assertRaw(Html::escape(file_url_transform_relative($test_image_url)), 'Test image found in embed code'); // Check for correct XML. $this->drupalGet($xml_path); $this->assertRaw('<?xml version="1.0" encoding="UTF-8"?>', 'Valid XML detected.'); $this->assertRaw('imageURL="' . Html::escape($test_image_url), 'Test image found in XML.'); $this->assertRaw('thumbURL="' . Html::escape($test_thumb_url), 'Test thumbnail found in XML.'); // Check for contextual links in embed code. It might we worth checking if // there is a more programmatic way to build the related id at some point. $this->drupalLogin($this->webUser); // Need access to contextual links. $this->drupalGet('node/' . $node->id()); $id = 'juicebox_xml_field:entityType=node&entityId=' . $node->id() . '&fieldName=' . $this->instFieldName . '&displayName=full:langcode=en|juicebox_conf_field_node:view_mode_name=default&node_type=' . $this->instBundle . ':langcode=en|juicebox_conf_global::langcode=en'; $this->assertRaw('<div data-contextual-id="' . Html::escape($id) . '"></div>', 'Correct contextual link placeholders found.'); $json = Json::decode($this->renderContextualLinks(array($id), 'node/' . $node->id())); $this->assertResponse(200); $this->assertTrue(preg_match('|/juicebox/xml/field/node/' . $node->id() . '/' . $this->instFieldName . '/full.*/admin/structure/types/manage/' . $this->instBundle . '/display/default.*/admin/config/media/juicebox|', $json[$id]), 'Correct contextual links found.'); }
/** * Sets up all of our services with mock methods so buildForm() is possible. * * @param string $catalog_id * Catalog id. * @param string $application_id * Application id. * @param [] $filters * An optional list of filters for the client to receive. */ protected function baseMockBuild($catalog_id, $application_id, $filters = []) { // Field manager mocking. $field_settings = ['max_filesize' => '2 MB', 'file_extensions' => self::MOCK_FIELD_SETTINGS_FILE_EXTENSIONS, 'catalog_id' => $catalog_id]; $this->fieldConfig->expects($this->once())->method('getName')->willReturn('field_test'); $this->fieldConfig->expects($this->once())->method('getSettings')->willReturn($field_settings); // Search filter always starts with the extensions OR filter. $extension_filter_value = str_replace(',', '|', self::MOCK_FIELD_SETTINGS_FILE_EXTENSIONS); $extension_filter = ['field' => 'fileformat', 'operator' => 'matches', 'value' => $extension_filter_value]; array_unshift($filters, $extension_filter); // Client mocking. $search_response = $this->json->decode(file_get_contents('expected/search-expected-small-response.json', TRUE)); $per_page = 8; $page = 1; $this->client->expects($this->once())->method('search')->with($page, $per_page, $filters)->willReturn($search_response); // Entity type storage mocking. $mock_catalog = $this->getMockBuilder('\\Drupal\\embridge\\EmbridgeCatalogInterface')->disableOriginalConstructor()->getMock(); $mock_catalog->expects($this->once())->method('getApplicationId')->willReturn($application_id); $mock_catalog_storage = $this->getMock(EntityStorageInterface::class); $mock_catalog_storage->expects($this->once())->method('load')->with($catalog_id)->willReturn($mock_catalog); $this->entityTypeManager->expects($this->once())->method('getStorage')->with('embridge_catalog')->willReturn($mock_catalog_storage); // Create mock assets. foreach ($search_response['results'] as $i => $result) { $mock_asset = $this->getMockBuilder('\\Drupal\\embridge\\EmbridgeAssetEntityInterface')->disableOriginalConstructor()->getMock(); $mock_asset->expects($this->once())->method('id')->willReturn($i); $this->mockAssets[$i]['asset'] = $mock_asset; $this->mockAssets[$i]['result'] = $result; } // Mock up the asset helper. $return_map = []; foreach ($this->mockAssets as $id => $asset_result) { $return_map[] = [$asset_result['result'], $catalog_id, $asset_result['asset']]; } $this->assetHelper->expects($this->exactly(count($this->mockAssets)))->method('searchResultToAsset')->will($this->returnValueMap($return_map)); }
protected function getRequestParams(Request $request) { $params = array_merge(['where' => [], 'limit' => null], $request->query->all()); $params['where'] = Json::decode($params['where']); ksort($params['where']); return $params; }
/** * Tests several valid and invalid read requests on all entity types. */ public function testRead() { // @todo Expand this at least to users. // Define the entity types we want to test. $entity_types = array('entity_test', 'node'); foreach ($entity_types as $entity_type) { $this->enableService('entity:' . $entity_type, 'GET'); // Create a user account that has the required permissions to read // resources via the REST API. $permissions = $this->entityPermissions($entity_type, 'view'); $permissions[] = 'restful get entity:' . $entity_type; $account = $this->drupalCreateUser($permissions); $this->drupalLogin($account); // Create an entity programmatically. $entity = $this->entityCreate($entity_type); $entity->save(); // Read it over the REST API. $response = $this->httpRequest($entity->getSystemPath(), 'GET', NULL, $this->defaultMimeType); $this->assertResponse('200', 'HTTP response code is correct.'); $this->assertHeader('content-type', $this->defaultMimeType); $data = Json::decode($response); // Only assert one example property here, other properties should be // checked in serialization tests. $this->assertEqual($data['uuid'][0]['value'], $entity->uuid(), 'Entity UUID is correct'); // Try to read the entity with an unsupported mime format. $response = $this->httpRequest($entity->getSystemPath(), 'GET', NULL, 'application/wrongformat'); $this->assertResponse(200); $this->assertHeader('Content-type', 'text/html; charset=UTF-8'); // Try to read an entity that does not exist. $response = $this->httpRequest($entity_type . '/9999', 'GET', NULL, $this->defaultMimeType); $this->assertResponse(404); $path = $entity_type == 'node' ? '/node/{node}' : '/entity_test/{entity_test}'; $expected_message = Json::encode(['error' => 'A fatal error occurred: The "' . $entity_type . '" parameter was not converted for the path "' . $path . '" (route name: "rest.entity.' . $entity_type . '.GET.hal_json")']); $this->assertIdentical($expected_message, $response, 'Response message is correct.'); // Make sure that field level access works and that the according field is // not available in the response. Only applies to entity_test. // @see entity_test_entity_field_access() if ($entity_type == 'entity_test') { $entity->field_test_text->value = 'no access value'; $entity->save(); $response = $this->httpRequest($entity->getSystemPath(), 'GET', NULL, $this->defaultMimeType); $this->assertResponse(200); $this->assertHeader('content-type', $this->defaultMimeType); $data = Json::decode($response); $this->assertFalse(isset($data['field_test_text']), 'Field access protected field is not visible in the response.'); } // Try to read an entity without proper permissions. $this->drupalLogout(); $response = $this->httpRequest($entity->getSystemPath(), 'GET', NULL, $this->defaultMimeType); $this->assertResponse(403); $this->assertIdentical('{}', $response); } // Try to read a resource which is not REST API enabled. $account = $this->drupalCreateUser(); $this->drupalLogin($account); $response = $this->httpRequest($account->getSystemPath(), 'GET', NULL, $this->defaultMimeType); $this->assertResponse(404); $expected_message = Json::encode(['error' => 'A fatal error occurred: Unable to find the controller for path "/user/4". Maybe you forgot to add the matching route in your routing configuration?']); $this->assertIdentical($expected_message, $response); }
/** * Writes a log messages and retrieves it via the REST API. */ public function testWatchdog() { // Write a log message to the DB. $this->container->get('logger.channel.rest')->notice('Test message'); // Get the ID of the written message. $id = db_query_range("SELECT wid FROM {watchdog} WHERE type = :type ORDER BY wid DESC", 0, 1, array(':type' => 'rest'))->fetchField(); // Create a user account that has the required permissions to read // the watchdog resource via the REST API. $account = $this->drupalCreateUser(array('restful get dblog')); $this->drupalLogin($account); $response = $this->httpRequest(Url::fromRoute('rest.dblog.GET.' . $this->defaultFormat, ['id' => $id, '_format' => $this->defaultFormat]), 'GET'); $this->assertResponse(200); $this->assertHeader('content-type', $this->defaultMimeType); $log = Json::decode($response); $this->assertEqual($log['wid'], $id, 'Log ID is correct.'); $this->assertEqual($log['type'], 'rest', 'Type of log message is correct.'); $this->assertEqual($log['message'], 'Test message', 'Log message text is correct.'); // Request an unknown log entry. $response = $this->httpRequest(Url::fromRoute('rest.dblog.GET.' . $this->defaultFormat, ['id' => 9999, '_format' => $this->defaultFormat]), 'GET'); $this->assertResponse(404); $decoded = Json::decode($response); $this->assertEqual($decoded['message'], 'Log entry with ID 9999 was not found', 'Response message is correct.'); // Make a bad request (a true malformed request would never be a route match). $response = $this->httpRequest(Url::fromRoute('rest.dblog.GET.' . $this->defaultFormat, ['id' => 0, '_format' => $this->defaultFormat]), 'GET'); $this->assertResponse(400); $decoded = Json::decode($response); $this->assertEqual($decoded['message'], 'No log entry ID was provided', 'Response message is correct.'); }
/** * Sets the raw content (e.g. HTML). * * @param string $content * The raw content to set. */ protected function setRawContent($content) { $this->content = $content; $this->plainTextContent = NULL; $this->elements = NULL; $this->drupalSettings = array(); if (preg_match('@<script type="application/json" data-drupal-selector="drupal-settings-json">([^<]*)</script>@', $content, $matches)) { $this->drupalSettings = Json::decode($matches[1]); } }
public static function genRandomExpoFront($nodenums = 1, $stickymax = 78, $storymax = 10) { $ns = 'public318'; $fetchurl = _expo_coll_fetchurl($ns); $json_fn = $ns . '-all'; $cache_fn_all = _expo_get_json_fn($json_fn); $json = WG::fetch_url($fetchurl, $cache_fn_all); $ret = Json::decode($json); $datas0 = $ret['results']; $public318_ids = [10478, 11857, 11861, 11897, 11902, 11914, 11933, 11940, 11941, 11956, 11960, 11962, 12377, 12378, 12382, 12395, 12578, 12663, 12669, 12681, 12684, 13035, 13049, 13050, 13051, 13064, 13065, 13066, 13067, 13070, 13076, 13077, 13078, 13100, 13121, 13122, 13130, 13135, 13136, 13138, 13140, 13142, 13144, 13145, 13149, 13173, 13182, 13202, 13225, 13253, 13255, 13258, 13259, 13260, 13264, 13265, 13266, 13267, 13292, 13305, 13313, 13325, 13328, 13329, 13343, 13348, 13349, 13350, 13351, 13352, 13353, 13354, 13356, 13377, 13391, 13394, 13395, 13396, 13413, 13416, 13428, 14944, 14945, 14946, 14948, 14951, 14952, 14953, 14954, 14955, 14956, 14957, 14959, 14960, 14961, 14962, 14963, 14967, 14968, 14969, 14970, 14971, 14972]; $datas = []; foreach ($datas0 as $data0) { $id = $data0['identifier']; if (in_array($id, $public318_ids)) { //echo $id.' '; $datas[$id] = $data0; } } for ($i = 1; $i <= $nodenums; $i++) { $d = []; $d['title'] = 'expo-autofront-' . date('ymdhi'); $d['public'] = 0; $d['showinfront'] = 1; $items = self::_getRandomItems2($storymax - 1, $stickymax - 1, $public318_ids); $easteregg_index = rand(0, $stickymax - 1); $el = ['itemtype' => 'story', 'id' => WG::config_get('expo.settings', 'easter_egg.nid')]; $items = DT::array_insert_element($items, $easteregg_index, $el); //print_r($items); //die(); $pos = 0; foreach ($items as $item) { $collitem = []; $collitem['weight'] = $pos; $pos++; DT::dnotice($pos . '-' . $item['itemtype'] . ':' . $item['id']); switch ($item['itemtype']) { case 'story': $collitem['target'] = 'storynode://' . $item['id']; $collitem['annotation'] = []; break; case 'public318': $id = $item['id']; //echo $id.' '; $entity = $datas[$id]; self::_fetch_public318($entity); $collitem['target'] = 'public318://' . $entity['identifier']; $text = $entity['text']; $text = str_replace(';;;', "\n", $text); $collitem['annotation'] = ['format' => 'rich_html_base', 'value' => $text]; break; } $d['collitems'][] = $collitem; } \Drupal\expo\ExpoCrud::saveExpo($d); } }
/** * Sets the raw content (e.g. HTML). * * @param string $content * The raw content to set. */ protected function setRawContent($content) { $this->content = $content; $this->plainTextContent = NULL; $this->elements = NULL; $this->drupalSettings = array(); if (preg_match('/var drupalSettings = (.*?);$/m', $content, $matches)) { $this->drupalSettings = Json::decode($matches[1]); } }
/** * @param \Symfony\Component\HttpKernel\Profiler\Profile $profile * @param \Symfony\Component\HttpFoundation\Request $request * * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function savePerformanceTimingAction(Profile $profile, Request $request) { $this->profiler->disable(); $data = Json::decode($request->getContent()); /** @var $collector */ $collector = $profile->getCollector('performance_timing'); $collector->setData($data); $this->profiler->updateProfile($profile); return new JsonResponse(['success' => TRUE]); }
/** * Tests contextual links with different permissions. * * Ensures that contextual link placeholders always exist, even if the user is * not allowed to use contextual links. */ function testDifferentPermissions() { $this->drupalLogin($this->editor_user); // Create three nodes in the following order: // - An article, which should be user-editable. // - A page, which should not be user-editable. // - A second article, which should also be user-editable. $node1 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1)); $node2 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 1)); $node3 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1)); // Now, on the front page, all article nodes should have contextual links // placeholders, as should the view that contains them. $ids = array('node:node=' . $node1->id() . ':changed=' . $node1->getChangedTime(), 'node:node=' . $node2->id() . ':changed=' . $node2->getChangedTime(), 'node:node=' . $node3->id() . ':changed=' . $node3->getChangedTime(), 'entity.view.edit_form:view=frontpage:location=page&name=frontpage&display_id=page_1'); // Editor user: can access contextual links and can edit articles. $this->drupalGet('node'); for ($i = 0; $i < count($ids); $i++) { $this->assertContextualLinkPlaceHolder($ids[$i]); } $this->renderContextualLinks(array(), 'node'); $this->assertResponse(400); $this->assertRaw('No contextual ids specified.'); $response = $this->renderContextualLinks($ids, 'node'); $this->assertResponse(200); $json = Json::decode($response); $this->assertIdentical($json[$ids[0]], '<ul class="contextual-links"><li class="entitynodeedit-form"><a href="' . base_path() . 'node/1/edit">Edit</a></li></ul>'); $this->assertIdentical($json[$ids[1]], ''); $this->assertIdentical($json[$ids[2]], '<ul class="contextual-links"><li class="entitynodeedit-form"><a href="' . base_path() . 'node/3/edit">Edit</a></li></ul>'); $this->assertIdentical($json[$ids[3]], ''); // Authenticated user: can access contextual links, cannot edit articles. $this->drupalLogin($this->authenticated_user); $this->drupalGet('node'); for ($i = 0; $i < count($ids); $i++) { $this->assertContextualLinkPlaceHolder($ids[$i]); } $this->renderContextualLinks(array(), 'node'); $this->assertResponse(400); $this->assertRaw('No contextual ids specified.'); $response = $this->renderContextualLinks($ids, 'node'); $this->assertResponse(200); $json = Json::decode($response); $this->assertIdentical($json[$ids[0]], ''); $this->assertIdentical($json[$ids[1]], ''); $this->assertIdentical($json[$ids[2]], ''); $this->assertIdentical($json[$ids[3]], ''); // Anonymous user: cannot access contextual links. $this->drupalLogin($this->anonymous_user); $this->drupalGet('node'); for ($i = 0; $i < count($ids); $i++) { $this->assertContextualLinkPlaceHolder($ids[$i]); } $this->renderContextualLinks(array(), 'node'); $this->assertResponse(403); $this->renderContextualLinks($ids, 'node'); $this->assertResponse(403); }
/** * Test comment row. */ public function testCommentRestExport() { $this->drupalGet(sprintf('node/%d/comments', $this->nodeUserCommented->id()), [], ['Accept' => 'application/hal+json']); $this->assertResponse(200); $contents = Json::decode($this->getRawContent()); $this->assertEqual($contents[0]['subject'], 'How much wood would a woodchuck chuck'); $this->assertEqual($contents[1]['subject'], 'A lot, apparently'); $this->assertEqual(count($contents), 2); // Ensure field-level access is respected - user shouldn't be able to see // mail or hostname fields. $this->assertNoText('*****@*****.**'); $this->assertNoText('public.example.com'); }
/** * Tests the UI of field handlers. */ public function testFieldUI() { // Ensure the field is not marked as hidden on the first run. $this->drupalGet('admin/structure/views/view/test_view/edit'); $this->assertText('Views test: Name'); $this->assertNoText('Views test: Name [' . t('hidden') . ']'); // Hides the field and check whether the hidden label is appended. $edit_handler_url = 'admin/structure/views/nojs/handler/test_view/default/field/name'; $this->drupalPostForm($edit_handler_url, array('options[exclude]' => TRUE), t('Apply')); $this->assertText('Views test: Name [' . t('hidden') . ']'); // Ensure that the expected tokens appear in the UI. $edit_handler_url = 'admin/structure/views/nojs/handler/test_view/default/field/age'; $this->drupalGet($edit_handler_url); $result = $this->xpath('//details[@id="edit-options-alter-help"]/div[@class="details-wrapper"]/div[@class="item-list"]/ul/li'); $this->assertEqual((string) $result[0], '{{ age }} == Age'); $edit_handler_url = 'admin/structure/views/nojs/handler/test_view/default/field/id'; $this->drupalGet($edit_handler_url); $result = $this->xpath('//details[@id="edit-options-alter-help"]/div[@class="details-wrapper"]/div[@class="item-list"]/ul/li'); $this->assertEqual((string) $result[0], '{{ age }} == Age'); $this->assertEqual((string) $result[1], '{{ id }} == ID'); $edit_handler_url = 'admin/structure/views/nojs/handler/test_view/default/field/name'; $this->drupalGet($edit_handler_url); $result = $this->xpath('//details[@id="edit-options-alter-help"]/div[@class="details-wrapper"]/div[@class="item-list"]/ul/li'); $this->assertEqual((string) $result[0], '{{ age }} == Age'); $this->assertEqual((string) $result[1], '{{ id }} == ID'); $this->assertEqual((string) $result[2], '{{ name }} == Name'); $result = $this->xpath('//details[@id="edit-options-more"]'); $this->assertEqual(empty($result), TRUE, "Container 'more' is empty and should not be displayed."); // Ensure that dialog titles are not escaped. $edit_groupby_url = 'admin/structure/views/nojs/handler/test_view/default/field/name'; $this->assertNoLinkByHref($edit_groupby_url, 0, 'No aggregation link found.'); // Enable aggregation on the view. $edit = array( 'group_by' => TRUE, ); $this->drupalPostForm('/admin/structure/views/nojs/display/test_view/default/group_by', $edit, t('Apply')); $this->assertLinkByHref($edit_groupby_url, 0, 'Aggregation link found.'); $edit_handler_url = '/admin/structure/views/ajax/handler-group/test_view/default/field/name'; $this->drupalGet($edit_handler_url); $data = Json::decode($this->getRawContent()); $this->assertEqual($data[3]['dialogOptions']['title'], 'Configure aggregation settings for field Views test: Name'); }
/** * Test loading of untransformed text when a user does have access to it. */ public function testUserWithPermission() { $user = $this->drupalCreateUser(array_merge(static::$basicPermissions, array('edit any article content', 'access in-place editing'))); $this->drupalLogin($user); $this->drupalGet('node/1'); // Ensure the text is transformed. $this->assertRaw('<p>Do you also love Drupal?</p><figure role="group" class="caption caption-img"><img src="druplicon.png" /><figcaption>Druplicon</figcaption></figure>'); $response = $this->drupalPost('editor/' . 'node/1/body/en/full', 'application/vnd.drupal-ajax', array()); $this->assertResponse(200); $ajax_commands = Json::decode($response); $this->assertIdentical(1, count($ajax_commands), 'The untransformed text POST request results in one AJAX command.'); $this->assertIdentical('editorGetUntransformedText', $ajax_commands[0]['command'], 'The first AJAX command is an editorGetUntransformedText command.'); $this->assertIdentical('<p>Do you also love Drupal?</p><img src="druplicon.png" data-caption="Druplicon" />', $ajax_commands[0]['data'], 'The editorGetUntransformedText command contains the expected data.'); }
/** * Asserts the cache context for the wrapper format is always present. */ function testWrapperFormatCacheContext() { $this->drupalGet('common-test/type-link-active-class'); $this->assertIdentical(0, strpos($this->getRawContent(), "<!DOCTYPE html>\n<html")); $this->assertIdentical('text/html; charset=UTF-8', $this->drupalGetHeader('Content-Type')); $this->assertTitle('Test active link class | Drupal'); $this->assertCacheContext('url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT); $this->drupalGet('common-test/type-link-active-class', ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'json']]); $this->assertIdentical('application/json', $this->drupalGetHeader('Content-Type')); $json = Json::decode($this->getRawContent()); $this->assertEqual(['content', 'title'], array_keys($json)); $this->assertIdentical('Test active link class', $json['title']); $this->assertCacheContext('url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT); }
/** * Page callback to output a token tree as an empty page. */ function outputTree(Request $request) { $build['#title'] = $this->t('Available tokens'); $options = $request->query->has('options') ? Json::decode($request->query->get('options')) : array(); // Force the dialog option to be false so we're not creating a dialog within // a dialog. $options['dialog'] = FALSE; // Build a render array with the options. foreach ($options as $key => $value) { $build['tree']['#' . $key] = $value; } $build['tree']['#theme'] = 'token_tree'; return $build; }
/** * Test using pre-packaged base Juicebox view. */ public function testViews() { $node = $this->node; $xml_path = 'juicebox/xml/viewsstyle/juicebox_views_test/page_1'; $xml_url = \Drupal::url('juicebox.xml_viewsstyle', array('viewName' => 'juicebox_views_test', 'displayName' => 'page_1')); // Get the urls to the test image and thumb derivative used by default. $uri = \Drupal\file\Entity\File::load($node->{$this->instFieldName}[0]->target_id)->getFileUri(); $test_image_url = entity_load('image_style', 'juicebox_medium')->buildUrl($uri); $test_thumb_url = entity_load('image_style', 'juicebox_square_thumb')->buildUrl($uri); // Check for correct embed markup. $this->drupalGet('juicebox-views-test'); $this->assertRaw(trim(json_encode(array('configUrl' => $xml_url)), '{}"'), 'Gallery setting found in Drupal.settings.'); $this->assertRaw('juicebox-views-test--page-1', 'Embed code wrapper found.'); $this->assertRaw(Html::escape($test_image_url), 'Test image found in embed code'); // Check for correct XML. $this->drupalGet($xml_path); $this->assertRaw('<?xml version="1.0" encoding="UTF-8"?>', 'Valid XML detected.'); $this->assertRaw('imageURL="' . Html::escape($test_image_url), 'Test image found in XML.'); $this->assertRaw('thumbURL="' . Html::escape($test_thumb_url), 'Test thumbnail found in XML.'); // A test leveraging fields with formattiong options also allows us to test // as additional global justboc configuration - the markup filter. The // node's title and body are mapped to the image title and caption. Most // formatting should be maintained in the caption because it's based on // a body field (with default settings to use "basic_html" text format). // However that our Juicebox markup filter should have stripped the // block-level p tags that were *added* by default by the text format. $this->assertRaw('<title><![CDATA[' . $this->node->getTitle() . ']]></title>', 'Image title text found in XML.'); $this->assertRaw('<caption><![CDATA[Some body content on node ' . $this->node->id() . ' <strong>with formatting</strong>]]></caption>', 'Image caption text found in XML.'); // Check for contextual links in embed code. It might we worth checking if // there is a more programmatic way to build the related id at some point. $this->drupalLogin($this->webUser); // Need access to contextual links. $this->drupalGet('juicebox-views-test'); $id = 'juicebox_xml_viewsstyle:viewName=juicebox_views_test&displayName=page_1:langcode=en|juicebox_conf_global::langcode=en'; $this->assertRaw('<div data-contextual-id="' . Html::escape($id) . '"></div>', 'Correct contextual link placeholders found.'); $json = Json::decode($this->renderContextualLinks(array($id), 'juicebox-views-test')); $this->assertResponse(200); $this->assertTrue(preg_match('|/' . $xml_path . '.*/admin/config/media/juicebox|', $json[$id]), 'Correct contextual links found.'); // Also test the toggle for the Juicebox markup filter. $edit = array('apply_markup_filter' => FALSE); $this->drupalPostForm('admin/config/media/juicebox', $edit, t('Save configuration')); $this->assertText(t('The Juicebox configuration options have been saved'), 'Custom global options saved.'); // Logout and test the formatting changge. $this->drupalLogout(); $this->drupalGet($xml_path); // With the filter off, the p tags in our example caption should come // through. $this->assertRaw('<caption><![CDATA[<p>Some body content on node ' . $this->node->id() . ' <strong>with formatting</strong></p>', 'Image caption text found in XML.'); }
/** * Tests contextual links. */ public function testNodeContextualLinks() { $this->drupalCreateNode(array('promote' => 1)); $this->drupalGet('node'); $user = $this->drupalCreateUser(array('administer nodes', 'access contextual links')); $this->drupalLogin($user); $response = $this->renderContextualLinks(array('node:node=1:'), 'node'); $this->assertResponse(200); $json = Json::decode($response); $this->drupalSetContent($json['node:node=1:']); // @todo Add these back when the functionality for making Views displays // appear in contextual links is working again. // $this->assertLinkByHref('node/1/contextual-links', 0, 'The contextual link to the view was found.'); // $this->assertLink('Test contextual link', 0, 'The contextual link to the view was found.'); }
/** * Page callback to output a token tree as an empty page. */ function outputTree(Request $request) { $options = $request->query->has('options') ? Json::decode($request->query->get('options')) : []; // The option token_types may only be an array OR 'all'. If it is not set, // we assume that only global token types are requested. $token_types = !empty($options['token_types']) ? $options['token_types'] : []; if ($token_types == 'all') { $build = $this->treeBuilder->buildAllRenderable($options); } else { $build = $this->treeBuilder->buildRenderable($token_types, $options); } $build['#cache']['contexts'][] = 'url.query_args:options'; $build['#title'] = $this->t('Available tokens'); return $build; }
/** * Tests that enforced responses propagate through subscribers and middleware. */ public function testFormResponse() { $edit = ['content' => $this->randomString(), 'status' => 200]; $content = Json::decode($this->drupalPostForm('form-test/response', $edit, 'Submit')); $this->assertResponse(200); $this->assertIdentical($edit['content'], $content, 'Response content matches'); $this->assertIdentical('invoked', $this->drupalGetHeader('X-Form-Test-Response-Event'), 'Response handled by kernel response subscriber'); $this->assertIdentical('invoked', $this->drupalGetHeader('X-Form-Test-Stack-Middleware'), 'Response handled by kernel middleware'); $edit = ['content' => $this->randomString(), 'status' => 418]; $content = Json::decode($this->drupalPostForm('form-test/response', $edit, 'Submit')); $this->assertResponse(418); $this->assertIdentical($edit['content'], $content, 'Response content matches'); $this->assertIdentical('invoked', $this->drupalGetHeader('X-Form-Test-Response-Event'), 'Response handled by kernel response subscriber'); $this->assertIdentical('invoked', $this->drupalGetHeader('X-Form-Test-Stack-Middleware'), 'Response handled by kernel middleware'); }
/** * Tests an ajax view. */ public function testAjaxView() { $this->drupalGet('test_ajax_view'); $data = array(); $data['view_name'] = 'test_ajax_view'; $data['view_display_id'] = 'test_ajax_view'; $post = array('view_name' => 'test_ajax_view', 'view_display_id' => 'page_1'); $response = $this->drupalPost('views/ajax', 'application/json', $post); $data = Json::decode($response); // Ensure that the view insert command is part of the result. $this->assertEqual($data[1]['command'], 'insert'); $this->assertTrue(strpos($data[1]['selector'], '.view-dom-id-') === 0); $this->drupalSetContent($data[1]['data']); $result = $this->xpath('//div[contains(@class, "views-row")]'); $this->assertEqual(count($result), 2, 'Ensure that two items are renderd in the HTML.'); }
public function decode($url) { // Clients will only throw exceptions that are a subclass of GuzzleHttp\Exception\RequestException. try { // Create a HTTP client. $response = \Drupal::httpClient()->get($url)->getBody(TRUE); } catch (RequestException $e) { // Do some stuff in case of the error. } // If successful HTTP query. if ($response) { $data = $response->getContents(); return Json::decode($data); } else { return NULL; } }
/** * Tests that a contextual link is available for translating a node. */ public function testContentTranslationContextualLinks() { // Create a node. $title = $this->randomString(); $this->drupalCreateNode(array('type' => $this->bundle, 'title' => $title)); $node = $this->drupalGetNodeByTitle($title); // Check that the translate link appears on the node page. $this->drupalLogin($this->translator); $translate_link = 'node/' . $node->id() . '/translations'; $response = $this->renderContextualLinks(array('node:node=1:'), 'node/' . $node->id()); $this->assertResponse(200); $json = Json::decode($response); $this->drupalSetContent($json['node:node=1:']); $this->assertLinkByHref($translate_link, 0, 'The contextual link to translate the node is shown.'); // Check that the link leads to the translate page. $this->drupalGet($translate_link); $this->assertRaw(t('Translations of %label', array('%label' => $node->label())), 'The contextual link leads to the translate page.'); }
/** * Tests HEAD support when a REST resource supports GET. */ public function testHeadSupport() { user_role_grant_permissions('anonymous', ['view test entity', 'restful get entity:entity_test']); // Create an entity programatically. $this->entityCreate('entity_test')->save(); $url = Url::fromUri('internal:/entity_test/1?_format=' . $this->defaultFormat); $this->enableService('entity:entity_test', 'GET'); $this->httpRequest($url, 'HEAD', NULL, $this->defaultMimeType); $this->assertResponse(200, 'HTTP response code is correct.'); $this->assertHeader('X-Drupal-Cache', 'MISS'); $this->assertResponseBody(''); $response = $this->httpRequest($url, 'GET', NULL, $this->defaultMimeType); $this->assertResponse(200, 'HTTP response code is correct.'); $this->assertHeader('X-Drupal-Cache', 'HIT'); $this->assertCacheTag('config:rest.settings'); $this->assertCacheTag('entity_test:1'); $data = Json::decode($response); $this->assertEqual($data['type'][0]['value'], 'entity_test'); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $route_name = NULL, $parameters = NULL) { $parameters = Json::decode($parameters); if (empty($route_name)) { // @todo Throw error } $form['label'] = array( '#type' => 'textfield', '#title' => $this->t('Label'), '#maxlength' => 255, '#description' => $this->t("Label for the Block Visibility Group."), '#required' => TRUE, ); $form['id'] = array( '#type' => 'machine_name', '#machine_name' => array( 'exists' => '\Drupal\block_visibility_groups\Entity\BlockVisibilityGroup::load', ), ); $form['conditions'] = [ '#type' => 'fieldset', '#title' => $this->t('Conditions'), '#description' => $this->t('Select at least one condition that applies to the current page.'), ]; $form['conditions'] += $this->conditionOptions($route_name, $parameters); $form['submit'] = [ '#type' => 'submit', '#value' => $this->t('Create new Group'), ]; $form['route_name'] = [ '#type' => 'value', '#value' => $route_name, ]; $form['parameters'] = [ '#type' => 'value', '#value' => $parameters, ]; return $form; }
/** * Tests that #type 'email' fields are properly validated. */ function testFormEmail() { $edit = array(); $edit['email'] = 'invalid'; $edit['email_required'] = ' '; $this->drupalPostForm('form-test/email', $edit, 'Submit'); $this->assertRaw(t('The email address %mail is not valid.', array('%mail' => 'invalid'))); $this->assertRaw(t('!name field is required.', array('!name' => 'Address'))); $edit = array(); $edit['email_required'] = ' foo.bar@example.com '; $values = Json::decode($this->drupalPostForm('form-test/email', $edit, 'Submit')); $this->assertIdentical($values['email'], ''); $this->assertEqual($values['email_required'], '*****@*****.**'); $edit = array(); $edit['email'] = '*****@*****.**'; $edit['email_required'] = '*****@*****.**'; $values = Json::decode($this->drupalPostForm('form-test/email', $edit, 'Submit')); $this->assertEqual($values['email'], '*****@*****.**'); $this->assertEqual($values['email_required'], '*****@*****.**'); }
/** * Tests \Drupal\Core\Form\FormState::cleanValues(). */ function testFormStateValuesClean() { $values = Json::decode($this->drupalPostForm('form_test/form-state-values-clean', array(), t('Submit'))); // Setup the expected result. $result = array('beer' => 1000, 'baz' => array('beer' => 2000)); // Verify that all internal Form API elements were removed. $this->assertFalse(isset($values['form_id']), format_string('%element was removed.', array('%element' => 'form_id'))); $this->assertFalse(isset($values['form_token']), format_string('%element was removed.', array('%element' => 'form_token'))); $this->assertFalse(isset($values['form_build_id']), format_string('%element was removed.', array('%element' => 'form_build_id'))); $this->assertFalse(isset($values['op']), format_string('%element was removed.', array('%element' => 'op'))); // Verify that all buttons were removed. $this->assertFalse(isset($values['foo']), format_string('%element was removed.', array('%element' => 'foo'))); $this->assertFalse(isset($values['bar']), format_string('%element was removed.', array('%element' => 'bar'))); $this->assertFalse(isset($values['baz']['foo']), format_string('%element was removed.', array('%element' => 'foo'))); $this->assertFalse(isset($values['baz']['baz']), format_string('%element was removed.', array('%element' => 'baz'))); // Verify that nested form value still exists. $this->assertTrue(isset($values['baz']['beer']), 'Nested form value still exists.'); // Verify that actual form values equal resulting form values. $this->assertEqual($values, $result, 'Expected form values equal actual form values.'); }
/** * Tests that #type 'url' fields are properly validated and trimmed. */ function testFormUrl() { $edit = array(); $edit['url'] = 'http://'; $edit['url_required'] = ' '; $this->drupalPostForm('form-test/url', $edit, 'Submit'); $this->assertRaw(t('The URL %url is not valid.', array('%url' => 'http://'))); $this->assertRaw(t('!name field is required.', array('!name' => 'Required URL'))); $edit = array(); $edit['url'] = "\n"; $edit['url_required'] = 'http://example.com/ '; $values = Json::decode($this->drupalPostForm('form-test/url', $edit, 'Submit')); $this->assertIdentical($values['url'], ''); $this->assertEqual($values['url_required'], 'http://example.com/'); $edit = array(); $edit['url'] = 'http://foo.bar.example.com/'; $edit['url_required'] = 'https://www.drupal.org/node/1174630?page=0&foo=bar#new'; $values = Json::decode($this->drupalPostForm('form-test/url', $edit, 'Submit')); $this->assertEqual($values['url'], $edit['url']); $this->assertEqual($values['url_required'], $edit['url_required']); }