Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 49 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ The service provider can be registered from your configuration file:
```json
{
"service_providers": {
"charcoal/view/service-provider/view": {}
"charcoal/sitemap/service-provider/sitemap": {}
}
}
```
Expand All @@ -68,17 +68,54 @@ To register a route from your configuration file:
By default, the action controller will look for a sitemap hierarchy named `xml`
which can be changed via the `sitemap_ident` controller setting.

### Admin (static file generation)

To generate a static `www/sitemap.xml` from the back-end system menu, include
the package's admin config and JavaScript:

```php
$config->addFile(\Charcoal\Sitemap\SitemapModule::ADMIN_CONFIG);
```

```json
{
"assets": {
"collections": {
"js": {
"files": [
"vendor/charcoal/contrib-sitemap/assets/scripts/contrib-sitemap.js"
]
}
}
}
}
```

You can also generate the file from the CLI:

```shell
vendor/bin/charcoal sitemap/generate
```

It is recommended to add a cron job to regenerate the file so search engines
do not receive an outdated sitemap.

## Overview

### Routes

* **`GET /sitemap.xml`** — A route assigned to `Charcoal\Sitemap\Action\SitemapAction`.
Used to serve the XML document.
Used to serve the XML document dynamically.
* **`GET /sitemap/generate`** (CLI) — A route assigned to
`Charcoal\Sitemap\Script\GenerateSitemapScript`.
Writes a static `www/sitemap.xml` file (`vendor/bin/charcoal sitemap/generate`).

### Services

* **`charcoal/sitemap/builder`** — Instance of `Charcoal\Sitemap\Service\Builder`.
Used to generate the collections of links from the configured models.
* **`charcoal/sitemap/generator`** — Instance of `Charcoal\Sitemap\Service\SitemapGenerator`.
Builds the default `xml` hierarchy and formats it as an XML document.
* **`sitemap/formatter/xml`** — Instance of `Charcoal\Sitemap\Service\XmlFormatter`.
Used to generate the XML from one or more collections of links from the `Builder`.
* **`sitemap/presenter`** — Instance of `Charcoal\Sitemap\Service\SitemapPresenter`.
Expand Down Expand Up @@ -307,6 +344,16 @@ $formatter = $container['sitemap/formatter/xml'];
$sitemap = $formatter->createXmlFromCollections($links);
```

### Static sitemap.xml

The `SitemapGenerator` service builds the default `xml` hierarchy and formats
it as XML. It is used by the CLI script and the admin generate action:

```php
$generator = $container['charcoal/sitemap/generator'];
$sitemap = $generator->generate();
```

## Development

To install the development environment:
Expand Down
61 changes: 61 additions & 0 deletions assets/scripts/contrib-sitemap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
$(document).ready(function () {
$(document).on('click', '#btn-generate-sitemap', function (e) {
e.preventDefault();

var $button = $(this);
var url = $button.data('url') || $button.attr('href');

if (!url || $button.prop('disabled')) {
return;
}

var originalHtml = $button.html();
var loadingHtml = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="margin-right:6px;"></span>Syncing...';

$button
.prop('disabled', true)
.addClass('disabled')
.html(loadingHtml);

fetch(url, {
method: 'GET'
})
.then(function (response) {
if (!response.ok) {
throw new Error('HTTP ' + response.status);
}

return response.json();
})
.then(function (data) {
if (!data.success) {
Charcoal.Admin.feedback([ {
level: 'error',
message: 'Une erreur est survenue pendant la génération du sitemap. Veuillez réessayer.',
} ]);
} else {
Charcoal.Admin.feedback([ {
level: 'warning',
title: 'Génération du sitemap',
message: 'Le sitemap a été généré avec succès.',
} ]);
}
})
.catch(function (err) {
Charcoal.Admin.feedback([ {
level: 'error',
message: 'Une erreur est survenue pendant la génération du sitemap. Veuillez réessayer.',
} ]);

console.error('Request failed:', err);
})
.finally(function () {
$button
.prop('disabled', false)
.removeClass('disabled')
.html(originalHtml);

Charcoal.Admin.feedback().dispatch();
});
});
});
12 changes: 6 additions & 6 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@
},
"require": {
"php": "^7.4 || ^8.0",
"charcoal/app": "^4.0",
"charcoal/core": "^4.0",
"charcoal/factory": "^4.0",
"charcoal/object": "^4.0",
"charcoal/translator": "^4.0",
"charcoal/view": "^4.0"
"charcoal/app": "^4.0 || ^5.0",
"charcoal/core": "^4.0 || ^5.0",
"charcoal/factory": "^4.0 || ^5.0",
"charcoal/object": "^4.0 || ^5.0",
"charcoal/translator": "^4.0 || ^5.0",
"charcoal/view": "^4.0 || ^5.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
Expand Down
26 changes: 26 additions & 0 deletions config/admin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"admin": {
"routes": {
"actions": {
"sitemap/generate": {
"route": "/sitemap/generate",
"controller": "charcoal/sitemap/action/generate-sitemap",
"methods": [ "GET" ]
}
}
},

"system_menu": {
"items": {
"sitemap": {
"label": {
"en": "Generate Sitemap",
"fr": "Générer le sitemap"
},
"url": "sitemap/generate",
"id": "btn-generate-sitemap"
}
}
}
}
}
80 changes: 80 additions & 0 deletions src/Charcoal/Sitemap/Action/GenerateSitemapAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace Charcoal\Sitemap\Action;

use Charcoal\App\Action\AbstractAction;
use Charcoal\Sitemap\Service\SitemapGenerator;
use Pimple\Container;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;

/**
* Writes a static `sitemap.xml` file for search engines and CDNs.
*/
class GenerateSitemapAction extends AbstractAction
{
protected SitemapGenerator $sitemapGenerator;

/**
* Application base path.
*
* @var string
*/
protected $basePath;

/**
* Inject dependencies from a DI Container.
*
* @param Container $container A dependencies container instance.
* @return void
*/
public function setDependencies(Container $container)
{
parent::setDependencies($container);

$this->sitemapGenerator = $container['charcoal/sitemap/generator'];
$this->basePath = $container['config']['base_path'] ?? getcwd();
}

/**
* Generates and writes the sitemap XML file.
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
* @return ResponseInterface
* @throws RuntimeException If the sitemap file cannot be written.
*/
public function run(RequestInterface $request, ResponseInterface $response)
{
$this->setSuccess(false);
$this->setMode(self::MODE_JSON);

$xml = $this->sitemapGenerator->generate();

if (!empty($xml)) {
$sitemapPath = rtrim($this->basePath, '/\\')
. DIRECTORY_SEPARATOR . 'www'
. DIRECTORY_SEPARATOR . 'sitemap.xml';

if (file_put_contents($sitemapPath, $xml, LOCK_EX) === false) {
throw new RuntimeException(sprintf(
'Unable to write sitemap to "%s".',
$sitemapPath
));
}

$this->setSuccess(true);
}

return $response;
}

/**
* @return array{success: bool}
*/
public function results()
{
return [ 'success' => $this->success() ];
}
}
69 changes: 69 additions & 0 deletions src/Charcoal/Sitemap/Script/GenerateSitemapScript.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

namespace Charcoal\Sitemap\Script;

use Charcoal\App\Script\AbstractScript;
use Charcoal\Sitemap\Service\SitemapGenerator;
use Pimple\Container;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;

/**
* CLI script to write a static `sitemap.xml` file.
*
* Invoked as `vendor/bin/charcoal sitemap/generate`.
*/
class GenerateSitemapScript extends AbstractScript
{
protected SitemapGenerator $sitemapGenerator;

/**
* Application base path.
*
* @var string
*/
protected $basePath;

/**
* Inject dependencies from a DI Container.
*
* @param Container $container A dependencies container instance.
* @return void
*/
public function setDependencies(Container $container)
{
$this->sitemapGenerator = $container['charcoal/sitemap/generator'];
$this->basePath = $container['config']['base_path'] ?? getcwd();

parent::setDependencies($container);
}

/**
* Generates and writes the sitemap XML file.
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
* @return ResponseInterface
* @throws RuntimeException If the sitemap file cannot be written.
*/
public function run(RequestInterface $request, ResponseInterface $response)
{
$xml = $this->sitemapGenerator->generate();

if (!empty($xml)) {
$sitemapPath = rtrim($this->basePath, '/\\')
. DIRECTORY_SEPARATOR . 'www'
. DIRECTORY_SEPARATOR . 'sitemap.xml';

if (file_put_contents($sitemapPath, $xml, LOCK_EX) === false) {
throw new RuntimeException(sprintf(
'Unable to write sitemap to "%s".',
$sitemapPath
));
}
}

return $response;
}
}
48 changes: 48 additions & 0 deletions src/Charcoal/Sitemap/Service/SitemapGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

namespace Charcoal\Sitemap\Service;

/**
* Generates a sitemap XML document from a configured hierarchy.
*
* Uses the "xml" hierarchy ident by default to match the sitemap builder
* configuration and the public `/sitemap.xml` route.
*/
class SitemapGenerator
{
protected Builder $sitemapBuilder;

protected XmlFormatter $xmlFormatter;

/**
* The sitemap hierarchy to build.
*/
protected string $sitemapIdent;

/**
* @param Builder $sitemapBuilder The sitemap builder.
* @param XmlFormatter $xmlFormatter The XML formatter.
* @param string $sitemapIdent The hierarchy ident to build.
*/
public function __construct(
Builder $sitemapBuilder,
XmlFormatter $xmlFormatter,
string $sitemapIdent = 'xml'
) {
$this->sitemapBuilder = $sitemapBuilder;
$this->xmlFormatter = $xmlFormatter;
$this->sitemapIdent = $sitemapIdent;
}

/**
* Generates the sitemap XML.
*
* @return string|null The XML document, or null if generation failed.
*/
public function generate(): ?string
{
$collections = $this->sitemapBuilder->build($this->sitemapIdent);

return $this->xmlFormatter->createXmlFromCollections($collections);
}
}
Loading
Loading