Skip to content

Commit

Permalink
Make the SERP preview a widget
Browse files Browse the repository at this point in the history
  • Loading branch information
leofeyer committed Oct 7, 2019
1 parent 621fd4e commit c339f75
Show file tree
Hide file tree
Showing 25 changed files with 485 additions and 212 deletions.
10 changes: 3 additions & 7 deletions calendar-bundle/src/EventListener/InsertTagsListener.php
Expand Up @@ -15,7 +15,6 @@
use Contao\CalendarEventsModel;
use Contao\CalendarFeedModel;
use Contao\CoreBundle\Framework\ContaoFramework;
use Contao\Events;
use Contao\StringUtil;

class InsertTagsListener
Expand Down Expand Up @@ -82,27 +81,24 @@ private function replaceEventInsertTag(string $insertTag, string $idOrAlias, arr
return '';
}

/** @var Events $events */
$events = $this->framework->getAdapter(Events::class);

switch ($insertTag) {
case 'event':
return sprintf(
'<a href="%s" title="%s">%s</a>',
$events->generateEventUrl($model, \in_array('absolute', $flags, true)),
\in_array('absolute', $flags, true) ? $model->getAbsoluteUrl() : $model->getFrontendUrl(),
StringUtil::specialchars($model->title),
$model->title
);

case 'event_open':
return sprintf(
'<a href="%s" title="%s">',
$events->generateEventUrl($model, \in_array('absolute', $flags, true)),
\in_array('absolute', $flags, true) ? $model->getAbsoluteUrl() : $model->getFrontendUrl(),
StringUtil::specialchars($model->title)
);

case 'event_url':
return $events->generateEventUrl($model, \in_array('absolute', $flags, true));
return \in_array('absolute', $flags, true) ? $model->getAbsoluteUrl() : $model->getFrontendUrl();

case 'event_title':
return StringUtil::specialchars($model->title);
Expand Down
Expand Up @@ -15,7 +15,6 @@
use Contao\CalendarEventsModel;
use Contao\CoreBundle\Event\PreviewUrlConvertEvent;
use Contao\CoreBundle\Framework\ContaoFramework;
use Contao\Events;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

Expand Down Expand Up @@ -52,10 +51,7 @@ public function onPreviewUrlConvert(PreviewUrlConvertEvent $event): void
return;
}

/** @var Events $eventsAdapter */
$eventsAdapter = $this->framework->getAdapter(Events::class);

$event->setUrl($request->getSchemeAndHttpHost().'/'.$eventsAdapter->generateEventUrl($eventModel));
$event->setUrl($request->getSchemeAndHttpHost().'/'.$eventModel->getFrontendUrl());
}

private function getEventModel(Request $request): ?CalendarEventsModel
Expand Down
7 changes: 6 additions & 1 deletion calendar-bundle/src/Resources/contao/classes/Events.php
Expand Up @@ -306,7 +306,7 @@ protected function addEvent($objEvents, $intStart, $intEnd, $intBegin, $intLimit
$arrEvent['link'] = $objEvents->title;
$arrEvent['target'] = '';
$arrEvent['title'] = StringUtil::specialchars($objEvents->title, true);
$arrEvent['href'] = $this->generateEventUrl($objEvents);
$arrEvent['href'] = $objEvents->current()->getFrontendUrl();
$arrEvent['class'] = $objEvents->cssClass ? ' ' . $objEvents->cssClass : '';
$arrEvent['recurring'] = $recurring;
$arrEvent['until'] = $until;
Expand Down Expand Up @@ -418,9 +418,14 @@ protected function addEvent($objEvents, $intStart, $intEnd, $intBegin, $intLimit
* @param boolean $blnAbsolute
*
* @return string
*
* @deprecated Deprecated since Contao 4.9, to be removed in Contao 5.0;
* use CalendardEventsModel::getFrontendUrl() instead

This comment has been minimized.

Copy link
@xchs

xchs Oct 7, 2019

Contributor
	 *             use CalendarEventsModel::getFrontendUrl() instead

Edit: Seems like the suggestion markdown is not supported here. :(


-	 *             use CalendardEventsModel::getFrontendUrl() instead
+	 *             use CalendarEventsModel::getFrontendUrl() instead
*/
public static function generateEventUrl($objEvent, $blnAbsolute=false)
{
@trigger_error('Using Events::generateEventUrl() has been deprecated and will no longer work in Contao 5.0. Use CalendardEventsModel::getFrontendUrl() instead.', E_USER_DEPRECATED);

This comment has been minimized.

Copy link
@xchs

xchs Oct 7, 2019

Contributor
		@trigger_error('Using Events::generateEventUrl() has been deprecated and will no longer work in Contao 5.0. Use CalendarEventsModel::getFrontendUrl() instead.', E_USER_DEPRECATED);

- 		@trigger_error('Using Events::generateEventUrl() has been deprecated and will no longer work in Contao 5.0. Use CalendardEventsModel::getFrontendUrl() instead.', E_USER_DEPRECATED);
+ 		@trigger_error('Using Events::generateEventUrl() has been deprecated and will no longer work in Contao 5.0. Use CalendarEventsModel::getFrontendUrl() instead.', E_USER_DEPRECATED);

$strCacheKey = 'id_' . $objEvent->id . ($blnAbsolute ? '_absolute' : '');

// Load the URL from cache
Expand Down
39 changes: 5 additions & 34 deletions calendar-bundle/src/Resources/contao/dca/tl_calendar_events.php
Expand Up @@ -117,7 +117,7 @@
'palettes' => array
(
'__selector__' => array('addTime', 'addImage', 'recurring', 'addEnclosure', 'source', 'overwriteMeta'),
'default' => '{title_legend},title,alias,author;{date_legend},addTime,startDate,endDate;{meta_legend},pageTitle,description,serp_preview;{details_legend},location,address,teaser;{image_legend},addImage;{recurring_legend},recurring;{enclosure_legend:hide},addEnclosure;{source_legend:hide},source;{expert_legend:hide},cssClass,noComments;{publish_legend},published,start,stop'
'default' => '{title_legend},title,alias,author;{date_legend},addTime,startDate,endDate;{meta_legend},pageTitle,description,serpPreview;{details_legend},location,address,teaser;{image_legend},addImage;{recurring_legend},recurring;{enclosure_legend:hide},addEnclosure;{source_legend:hide},source;{expert_legend:hide},cssClass,noComments;{publish_legend},published,start,stop'
),

// Subpalettes
Expand Down Expand Up @@ -254,11 +254,12 @@
'eval' => array('style'=>'height:60px', 'decodeEntities'=>true, 'tl_class'=>'clr'),
'sql' => "text NULL"
),
'serp_preview' => array
'serpPreview' => array
(
'label' => &$GLOBALS['TL_LANG']['MSC']['serp_preview'],
'label' => &$GLOBALS['TL_LANG']['MSC']['serpPreview'],
'exclude' => true,
'input_field_callback' => array('tl_calendar_events', 'showSerpPreview')
'inputType' => 'serpPreview',
'eval' => array('serpPreview'=>array('title'=>array('pageTitle', 'title'), 'description'=>array('description', 'teaser'))),
),
'location' => array
(
Expand Down Expand Up @@ -813,36 +814,6 @@ public function getArticleAlias(Contao\DataContainer $dc)
return $arrAlias;
}

/**
* Show the SERP preview
*
* @param Contao\DataContainer $dc
*
* @return string
*/
public function showSerpPreview(Contao\DataContainer $dc)
{
$event = Contao\CalendarEventsModel::findByPk($dc->activeRecord->id);
$url = Contao\Events::generateEventUrl($event, true);
$suffix = substr($dc->inputName, strlen($dc->field));

list($baseUrl) = explode($event->alias ?: $event->id, $url);

$template = new Contao\FrontendTemplate('be_serp');
$template->id = $event->id;
$template->title = $event->pageTitle ?: $event->title;
$template->url = $url;
$template->description = $event->description ?: strip_tags($event->teaser);
$template->baseUrl = $baseUrl;
$template->titleField = 'ctrl_pageTitle' . $suffix;
$template->titleFallbackField = 'ctrl_title' . $suffix;
$template->aliasField = 'ctrl_alias' . $suffix;
$template->descriptionField = 'ctrl_description' . $suffix;
$template->descriptionFallbackField = 'ctrl_teaser' . $suffix;

return $template->parse();
}

/**
* Add the source options depending on the allowed fields (see #5498)
*
Expand Down
100 changes: 99 additions & 1 deletion calendar-bundle/src/Resources/contao/models/CalendarEventsModel.php
Expand Up @@ -11,6 +11,7 @@
namespace Contao;

use Contao\Model\Collection;
use Contao\Model\Routable;

/**
* Reads and writes events
Expand Down Expand Up @@ -190,14 +191,24 @@
*
* @author Leo Feyer <https://github.com/leofeyer>
*/
class CalendarEventsModel extends Model
class CalendarEventsModel extends Model implements Routable
{
/**
* Table name
* @var string
*/
protected static $strTable = 'tl_calendar_events';

/**
* @var string
*/
private $strFrontendUrl;

/**
* @var string
*/
private $strAbsoluteUrl;

/**
* Find a published event from one or more calendars by its ID or alias
*
Expand Down Expand Up @@ -320,6 +331,93 @@ public static function findUpcomingByPids($arrIds, $intLimit=0, array $arrOption

return static::findBy($arrColumns, null, $arrOptions);
}

/**
* {@inheritdoc}
*/
public function getFrontendUrl()
{
if (!$this->strFrontendUrl)
{
$this->strFrontendUrl = $this->getUrl('getFrontendUrl');
}

return $this->strFrontendUrl;
}

/**
* {@inheritdoc}
*/
public function getAbsoluteUrl()
{
if (!$this->strAbsoluteUrl)
{
$this->strAbsoluteUrl = $this->getUrl('getAbsoluteUrl');
}

return $this->strAbsoluteUrl;
}

/**
* Reset the URLs if the record is refreshed
*
* @param integer $intType
*/
public function refresh()
{
parent::refresh();

$this->strFrontendUrl = null;
$this->strAbsoluteUrl = null;
}

/**
* Return the URL depending on the source
*
* @param $strMethod
*
* @return string
*/
private function getUrl($strMethod)
{
switch ($this->source)
{
// Link to an external page
case 'external':
if (0 === strncmp($this->url, 'mailto:', 7))
{
return StringUtil::encodeEmail($this->url);
}

return ampersand($this->url);

// Link to an internal page
case 'internal':
if (($objTarget = $this->getRelated('jumpTo')) instanceof PageModel)
{
return $objTarget->$strMethod();
}
break;

// Link to an article
case 'article':
if (($objArticle = ArticleModel::findByPk($this->articleId)) instanceof ArticleModel && ($objPid = $objArticle->getRelated('pid')) instanceof PageModel)
{
return $objPid->$strMethod('/articles/' . ($objArticle->alias ?: $objArticle->id));
}
break;
}

// Link to the default page
$objPage = PageModel::findByPk($this->getRelated('pid')->jumpTo);

if (!$objPage instanceof PageModel)
{
return ampersand(Environment::get('request'));
}

return $objPage->$strMethod((Config::get('useAutoItem') ? '/' : '/events/') . ($this->alias ?: $this->id));
}
}

class_alias(CalendarEventsModel::class, 'CalendarEventsModel');
22 changes: 8 additions & 14 deletions calendar-bundle/tests/EventListener/InsertTagsListenerTest.php
Expand Up @@ -15,7 +15,6 @@
use Contao\CalendarBundle\EventListener\InsertTagsListener;
use Contao\CalendarEventsModel;
use Contao\CalendarFeedModel;
use Contao\Events;
use Contao\TestCase\ContaoTestCase;
use PHPUnit\Framework\MockObject\MockObject;

Expand Down Expand Up @@ -47,23 +46,18 @@ public function testReplacesTheEventTags(): void
$eventModel->title = 'The "foobar" event';
$eventModel->teaser = '<p>The annual foobar event.</p>';

$events = $this->mockAdapter(['generateEventUrl']);
$events
->method('generateEventUrl')
->willReturnCallback(
static function (CalendarEventsModel $model, bool $absolute): string {
if ($absolute) {
return 'http://domain.tld/events/the-foobar-event.html';
}

return 'events/the-foobar-event.html';
}
)
$eventModel
->method('getFrontendUrl')
->willReturn('events/the-foobar-event.html')
;

$eventModel
->method('getAbsoluteUrl')
->willReturn('http://domain.tld/events/the-foobar-event.html')
;

$adapters = [
CalendarEventsModel::class => $this->mockConfiguredAdapter(['findByIdOrAlias' => $eventModel]),
Events::class => $events,
];

$listener = new InsertTagsListener($this->mockContaoFramework($adapters));
Expand Down
Expand Up @@ -16,7 +16,6 @@
use Contao\CalendarEventsModel;
use Contao\CoreBundle\Event\PreviewUrlConvertEvent;
use Contao\CoreBundle\Framework\ContaoFramework;
use Contao\Events;
use Contao\TestCase\ContaoTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
Expand All @@ -34,10 +33,14 @@ public function testConvertsThePreviewUrl(): void
$requestStack->push($request);

$eventModel = $this->createMock(CalendarEventsModel::class);
$eventModel
->expects($this->once())
->method('getFrontendUrl')
->willReturn('events/winter-holidays.html')
;

$adapters = [
CalendarEventsModel::class => $this->mockConfiguredAdapter(['findByPk' => $eventModel]),
Events::class => $this->mockConfiguredAdapter(['generateEventUrl' => 'events/winter-holidays.html']),
];

$framework = $this->mockContaoFramework($adapters);
Expand Down
3 changes: 2 additions & 1 deletion core-bundle/src/Resources/contao/config/config.php
Expand Up @@ -233,7 +233,8 @@
'imageSize' => 'Contao\ImageSize',
'timePeriod' => 'Contao\TimePeriod',
'metaWizard' => 'Contao\MetaWizard',
'sectionWizard' => 'Contao\SectionWizard'
'sectionWizard' => 'Contao\SectionWizard',
'serpPreview' => 'Contao\SerpPreview'
);

// Front end form fields
Expand Down

0 comments on commit c339f75

Please sign in to comment.