Initial commit of archive_tree module

This commit is contained in:
2026-01-23 21:52:25 -06:00
commit c16a1e6d7e
8 changed files with 613 additions and 0 deletions

View File

@@ -0,0 +1,75 @@
<?php
namespace Drupal\archive_tree\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides an 'Archive tree' block.
*
* @Block(
* id = "archive_tree_block",
* admin_label = @Translation("Archive tree"),
* )
*/
class ArchiveTreeBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$storage = \Drupal::entityTypeManager()->getStorage('node');
$query = $storage->getQuery()
->condition('type', 'article')
->condition('status', 1)
->sort('created', 'DESC')
->accessCheck(TRUE)
->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$nids = $query->execute();
$nodes = $storage->loadMultiple($nids);
$tree = [];
foreach ($nodes as $node) {
$created = $node->getCreatedTime();
$year = date('Y', $created);
$month = date('m', $created);
if (!isset($tree[$year])) {
$tree[$year] = ['count' => 0, 'months' => []];
}
if (!isset($tree[$year]['months'][$month])) {
$tree[$year]['months'][$month] = 0;
}
$tree[$year]['count']++;
$tree[$year]['months'][$month]++;
}
krsort($tree); // Descending years
foreach ($tree as &$data) {
krsort($data['months']); // Descending months
}
$output = '';
foreach ($tree as $year => $data) {
$year_url = '/archive-tree/' . $year;
$output .= '<details><summary class="archive-tree-year">';
$output .= '<a href="' . $year_url . '">' . $year . '</a> (' . $data['count'] . ')';
$output .= '</summary>';
foreach ($data['months'] as $month => $count) {
$month_url = '/archive-tree/' . $year . '/' . $month;
$output .= '<div class="archive-tree-month">';
$output .= '<a href="' . $month_url . '">' . $month . '</a> (' . $count . ')';
$output .= '</div>';
}
$output .= '</details>';
}
return [
'#markup' => $output,
'#allowed_tags' => ['details', 'summary', 'a', 'div'],
'#attached' => [
'library' => [
'archive_tree/archive_tree_styles',
],
],
];
}
}