Skip to content

Commit

Permalink
use WP Rest API
Browse files Browse the repository at this point in the history
  • Loading branch information
vz01d committed Dec 21, 2019
1 parent f9b9001 commit 003e906
Show file tree
Hide file tree
Showing 12 changed files with 369 additions and 225 deletions.
14 changes: 10 additions & 4 deletions classes/core/BlitzAssets.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,14 +212,20 @@ public function enqueueFrontendAssets(): void
true
);

$id = get_the_ID();
$pt = get_post_type($id);
wp_localize_script(
'blitz-frontend',
'BLITZ',
[
'nonce' => wp_create_nonce('wp_rest'),
'restBase' => esc_url_raw(rest_url()),
'restUrl' => esc_url_raw(rest_url().'blitz/' . \blitz\core\BlitzApi::API_VERSION),
'currentID' => get_the_ID()
'nonce' => wp_create_nonce('wp_rest'),
'restBase' => esc_url_raw(rest_url()),
'settingsUrl' => esc_url_raw(rest_url().'blitz/' . \blitz\core\BlitzApi::API_VERSION.'/settings'),
'contentUrl' => esc_url_raw(rest_url().'blitz/' . \blitz\core\BlitzApi::API_VERSION.'/content'),
'slidesUrl' => esc_url_raw(rest_url().'blitz/' . \blitz\core\BlitzApi::API_VERSION.'/slides'),
'currentID' => $id,
'pt' => $pt != false ? $pt.'s' : false,
'siteBase' => Blitz::$siteUrl
]
);

Expand Down
84 changes: 54 additions & 30 deletions classes/core/BlitzFrontend.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,46 +36,70 @@ public function __construct(BlitzAssets $assets)
show_admin_bar($showAdminBar);
add_action('wp_enqueue_scripts', [$assets, 'enqueueFrontendAssets']);
add_action('get_footer', [$assets, 'enqueueFooterCss']);
}

/**
* Get data for the specific chunk of the page for example the header, footer or content
* there maybe data available to all chunks

BlitzApi::registerEndpoint(
'content',
[$this, 'getContent']
);
}

/**
* Return the page content
*
* @param string $chunk - the chunk to load
* @param int $postId (optional) - the post or page id the content is to
* be fetched from
* @param \WP_REST_Request $request - the request object
*
* @return array - all required page data for the requested chunk
*/
public function getChunkdata(string $chunk, int $postId = 0): array
{
$possibleChunks = [
* @return \WP_REST_Response - the page content object which may
* includes navigation, slider images or post content rendered
*/
public function getContent(\WP_REST_Request $request): \WP_REST_Response
{
$parts = [
'header',
'footer',
'content'
'content',
'footer'
];

if (!in_array($chunk, $possibleChunks)) {
$chunk = 'header';
$postId = $request->get_header('B-PID');
$part = $request->get_param('load');
if (false === in_array($part, $parts)) {
$part = 'header';
}

$data = [];
if (is_callable([$this, $chunk])) {
if ('content' === $chunk){
$data = $this->$chunk($postId);
} else {
$data = $this->$chunk();
}
$returnCode = 200;

if ('header' === $part) {
$content['navigation'] = $this->_getNavigation(['main', 'top']);
$content['baseUrl'] = Blitz::$siteUrl;
}

// apply these to all requests
// colors
$data['textColor'] = get_field('frontend_text_color', 'option');
$response = new \WP_REST_Response($content, $returnCode);
return $response;
}

/**
* Get frontend settings (colors, hidden items etc.)
*
* @param int $postId (optional) - the post or page id the content is to
* be fetched for - posts and pages can have their header hidden, no navigation etc.
*
* @return array - all settings to built the page
*/
public function getSettings(int $postId): array
{
$data['textColor'] = get_field('frontend_text_color', 'option');
$data['backgroundColor'] = get_field('frontend_background_color', 'option');
$data['showHeader'] = get_field('show_header', 'option');
if (true === $data['showHeader']) {
$data['showNavigation'] = get_field('show_navigation', 'option');
}

// base Url
$data['baseUrl'] = Blitz::$siteUrl;
/*
we include the logo url here since we
do not want to have the logo in header
for some layouts
*/
$logo = get_field('logo', 'option');
$data['logoUrl'] = $logo['url'];

return $data;
}
Expand Down Expand Up @@ -111,7 +135,7 @@ public function header(): array
*
* @return array - the settings for the content
*/
public function content(int $postId): array
private function content(int $postId): array
{
/*
TODO: currentId is false when no static page is
Expand Down
5 changes: 5 additions & 0 deletions classes/core/BlitzObjects.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ public function __construct(array $objects)
$o->registerEndpoints();
}

// not all objects require this
if (true === is_callable([$o, 'loadRestFields'])) {
$o->loadRestFields();
}

$this->_objects[$this->_getName($o)] = $o;
}
}, $objects);
Expand Down
22 changes: 22 additions & 0 deletions classes/objects/Pages.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,26 @@ public function loadObjectMeta(): void
public function loadObject(): void
{
}

/**
* Load rest fields
*
* @return void
*/
public function loadRestFields(): void
{
add_action('rest_api_init', function() {
register_rest_field('page', 'slider', [
'get_callback' => function($atts) {
return get_field('page_slider', $atts['id']) ?? false;
},
'schema' => [
'description' => 'the slider for the page',
'type' => 'integer'
]
]);
});
}


}
20 changes: 20 additions & 0 deletions classes/objects/Posts.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,24 @@ public function loadObjectMeta(): void
public function loadObject(): void
{
}

/**
* Load rest fields
*
* @return void
*/
public function loadRestFields(): void
{
add_action('rest_api_init', function() {
register_rest_field('post', 'slider', [
'get_callback' => function($atts) {
return get_field('page_slider', $atts['id']) ?? false;
},
'schema' => [
'description' => 'the slider for the page',
'type' => 'integer'
]
]);
});
}
}
14 changes: 5 additions & 9 deletions classes/objects/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -387,16 +387,12 @@ public function registerEndpoints(): void
*/
public function getSettings(\WP_REST_Request $request): \WP_REST_Response
{
$chunkToLoad = $request->get_param('load');
if ('content' === $chunkToLoad) {
$postId = $request->get_header('F-PID');
$settings = $this->frontend()->getChunkdata($chunkToLoad, intval($postId));
$postId = $request->get_header('B-PID');
if (false != $postId) {
$settings = $this->frontend()->getSettings($postId);
$returnCode = 200;
} else {
$settings = $this->frontend()->getChunkdata($chunkToLoad);
}

$returnCode = 200;
if (isset($settings['is404']) && true === $settings['is404']) {
$settings['is404'] = true;
$returnCode = 404;
}

Expand Down
71 changes: 70 additions & 1 deletion classes/objects/Sliders.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

use StoutLogic\AcfBuilder\FieldsBuilder;
use blitz\interfaces\BlitzObject;
use blitz\interfaces\BlitzApiObject;
use blitz\core\BlitzApi;
use blitz\core\BlitzObjects;

/**
Expand All @@ -25,7 +27,7 @@
* @license GPLv2 https://opensource.org/licenses/gpl-2.0.php
* @link https://42geeks.gg/
*/
class Sliders extends BlitzObjects implements BlitzObject
class Sliders extends BlitzObjects implements BlitzObject, BlitzApiObject
{
const CPT_NAME = 'fet-slider';

Expand Down Expand Up @@ -124,4 +126,71 @@ public function loadObjectMeta(): void

acf_add_local_field_group($slider->build());
}

/**
* Register an endpoint to fetch slides for a given slider
*/
public function registerEndpoints(): void
{
if (false === BlitzApi::registerEndpoint(
'slides',
[$this, 'getSlides']
)){
echo 'WARNING: endpoint registration failed for some reason maybe your callback is not callable.'.PHP_EOL;
}
}

/**
* Return the slides for the slider
*
* @param \WP_REST_Request $request - the request object
*
* @return \WP_REST_Response - the slides array containing image urls
*/
public function getSlides(\WP_REST_Request $request): \WP_REST_Response
{
$sliderId = $request->get_header('B-PID');
if (false != $sliderId) {
$slides = $this->_getSlidesBySliderId($sliderId);
$returnCode = 200;
} else {
$slides['is404'] = true;
$returnCode = 404;
}

$response = new \WP_REST_Response($slides, $returnCode);
return $response;
}

/**
* Return the slides by provided slider id
* the slider MUST be an acf repeater
*
* @param int $sliderId - the id of the slider
*
* @return array - the array containing the slides including all data
*/
private function _getSlidesBySliderId(int $sliderId): array
{
$sliderData = [];

// slider is a WP_Post object containing acf repeater subfields
$slides = get_field('slides', $sliderId);
if (false != $slides) {
foreach ($slides as $slide) {
$s = new \stdClass;
$imgSrc = wp_get_attachment_image_src($slide['slider_image']['ID'], 'full');
$s->imageUrl = isset($imgSrc[0]) ? $imgSrc[0] : '';
$s->text = $slide['slide_text'];

if (false !== $slide['show_button']) {
$s->btnLink = $slide['button_link'];
}

$sliderData[] = $s;
}
}

return $sliderData;
}
}
47 changes: 38 additions & 9 deletions frontend/src/App.svelte
Original file line number Diff line number Diff line change
@@ -1,11 +1,40 @@
<script>
import Blitzheader from "./templates/Header.svelte";
import Blitzcontent from "./templates/Content.svelte";
import Blitzfooter from "./templates/Footer.svelte";
</script>
import { onMount } from 'svelte';
import BlitzHeader from './templates/Header.svelte';
import BlitzContent from './templates/Content.svelte';
let settings;
async function getSettings() {
const res = await fetch(
BLITZ.settingsUrl,
{
headers: {
'B-PID': BLITZ.currentID
}
}
);
<Blitzheader/>
<main class="min-h-screen" role="main">
<Blitzcontent/>
</main>
<Blitzfooter/>
// TODO: settings may return 404
const data = await res.json();
return data;
}
onMount(async() => {
settings = getSettings();
});
</script>
{#await settings then setting}
{#if setting && setting.showHeader}
<BlitzHeader
logoUrl={setting.logoUrl}
textColor={setting.textColor}
backgroundColor={setting.backgroundColor}
showNavigation={setting.showNavigation}
/>
<main class="min-h-screen" role="main">
<BlitzContent />
</main>
{/if}
{/await}
Loading

0 comments on commit 003e906

Please sign in to comment.