Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pages should have different scores for different sites #7

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
7 changes: 5 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Release Notes for carbon-tracker

## 4.1.0 - 2024-03-08
### Added
- Added multisite support ([#3](https://github.com/statikbe/craft-carbon-tracker/issues/3))

## 4.0.3 - 2024-01-12
### Fixed
- Fix typo in sidebar template
Expand All @@ -8,10 +12,9 @@
### Fixed
- Only run our job for enabled entries, because we need to be able to crawl them.


## 4.0.1 - 2024-01-04
### Fixed
- Fixed issue with failing jobs on multi-site installs

## 4.0.0 - 2024-01-02
- Initial release 🚀
- Initial release 🚀
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "statikbe/craft-carbon-tracker",
"description": "Carbon tracker aims to raise awareness of the carbon emissions created by webpages, by displaying these insights along side the content in Craft's control panel.",
"type": "craft-plugin",
"version": "4.0.3",
"version": "4.1.0",
"license": "mit",
"support": {
"email": "[email protected]",
Expand Down Expand Up @@ -41,7 +41,8 @@
"scripts": {
"check-cs": "ecs check --ansi",
"fix-cs": "ecs check --ansi --fix",
"phpstan": "phpstan --memory-limit=1G"
"phpstan": "phpstan --memory-limit=1G",
"ci": "ecs check --ansi --fix && phpstan --memory-limit=1G"
},
"config": {
"sort-packages": true,
Expand Down
4 changes: 2 additions & 2 deletions src/CarbonTracker.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
*/
class CarbonTracker extends Plugin
{
public string $schemaVersion = '1.0.0';
public string $schemaVersion = '1.1.0';
public bool $hasCpSettings = true;

/**
Expand Down Expand Up @@ -80,7 +80,7 @@ private function attachEventHandlers(): void
function(ModelEvent $event) {
/** @var Entry $entry */
$entry = $event->sender;
if (!ElementHelper::isDraftOrRevision($entry) && $entry->getUrl()) {
if (!ElementHelper::isDraftOrRevision($entry) && $entry->getUrl() && !$entry->propagating) {
Queue::push(new CarbonStatsJob([
'entryId' => $entry->id,
'siteId' => $entry->siteId,
Expand Down
1 change: 1 addition & 0 deletions src/migrations/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public function safeUp(): bool
[
'id' => $this->primaryKey(),
'entryId' => $this->integer()->notNull(),
'siteId' => $this->integer()->notNull(),
'url' => $this->string()->notNull(),
'green' => $this->boolean()->defaultValue(0),
'bytes' => $this->integer(),
Expand Down
35 changes: 35 additions & 0 deletions src/migrations/m240307_121231_addSiteIdCol.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace statikbe\carbontracker\migrations;

use craft\db\Migration;
use statikbe\carbontracker\records\SiteStatisticsRecord;

/**
* m240307_121231_addSiteIdCol migration.
*/
class m240307_121231_addSiteIdCol extends Migration
{
/**
* @inheritdoc
*/
public function safeUp(): bool
{
$this->addColumn(
SiteStatisticsRecord::tableName(),
'siteId',
$this->integer()->notNull()->after('entryId')
);

return true;
}

/**
* @inheritdoc
*/
public function safeDown(): bool
{
echo "m240307_121231_addSiteIdCol cannot be reverted.\n";
return false;
}
}
5 changes: 3 additions & 2 deletions src/models/SiteStatisticsModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
class SiteStatisticsModel extends Model
{
public int $entryId;
public int $siteId;
public string $url = "https://";
public bool $green = false;
public int $bytes = 0;
Expand All @@ -23,8 +24,8 @@ class SiteStatisticsModel extends Model
public function rules(): array
{
return [
[['entryId', 'url', 'green', 'bytes', 'cleanerThan', 'rating', 'dateUpdated'], 'required'],
[['entryId', 'url', 'green', 'bytes', 'cleanerThan', 'rating', 'dateUpdated'], 'safe'],
[['entryId', 'siteId', 'url', 'green', 'bytes', 'cleanerThan', 'rating', 'dateUpdated'], 'required'],
[['entryId', 'siteId', 'url', 'green', 'bytes', 'cleanerThan', 'rating', 'dateUpdated'], 'safe'],
];
}
}
1 change: 1 addition & 0 deletions src/records/SiteStatisticsRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

/**
* @property int $entryId entryId
* @property int $siteId siteId
* @property string $url url
* @property boolean $green green
* @property float $cleanerThan cleanerThan
Expand Down
45 changes: 37 additions & 8 deletions src/services/ApiService.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use craft\base\Component;
use craft\elements\Entry;
use GuzzleHttp\Client;
use statikbe\carbontracker\CarbonTracker;
use statikbe\carbontracker\models\SiteStatisticsModel;

class ApiService extends Component
Expand All @@ -22,28 +23,56 @@ public function init(): void
parent::init();
}

public function getSite(Entry $entry): SiteStatisticsModel
public function getSite(Entry $entry): SiteStatisticsModel|bool
{
$model = new SiteStatisticsModel();

if (getenv('CRAFT_ENVIRONMENT') === 'dev') {
$url = self::READ_MORE_LINK;
$json_data = '{
"url": "https://www.wholegraindigital.com/",
"green": true,
"rating": "A+",
"bytes": 443854,
"cleanerThan": 0.83,
"statistics": {
"adjustedBytes": 335109.77,
"energy": 0.0005633320052642376,
"co2": {
"grid": {
"grams": 0.26758270250051286,
"litres": 0.14882949913078525
},
"renewable": {
"grams": 0.24250694721722435,
"litres": 0.13488236404222018
}
}
}
}';

$data = json_decode($json_data, true);
} else {
$url = $entry->getUrl();
try {
$url = $entry->getUrl();
$data = $this->makeRequest('/site', [
'query' => [
'url' => $url,
],
]);
} catch (\Exception $e) {
\Craft::error($e->getMessage(), CarbonTracker::class);
return false;
}
}

$data = $this->makeRequest('/site', [
'query' => [
'url' => $url,
],
]);

if (empty($data)) {
return $model;
}

$model->setAttributes([
'entryId' => $entry->id,
'siteId' => $entry->siteId,
'url' => $data['url'],
'green' => $data['green'],
'bytes' => $data['bytes'],
Expand Down
29 changes: 18 additions & 11 deletions src/services/StatsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@ class StatsService extends Component
{
public function getDataForEntry(Entry $entry): SiteStatisticsModel|bool
{
$record = SiteStatisticsRecord::findOne(['entryId' => $entry->id]);

$record = SiteStatisticsRecord::findOne(['entryId' => $entry->id, 'siteId' => $entry->siteId]);
if (!$record) {
// What if we don't have any data yet?
return false;
// Search again without the siteId
$record = SiteStatisticsRecord::findOne(['entryId' => $entry->id]);
if (!$record) {
return false;
}
}

$model = new SiteStatisticsModel();
Expand All @@ -31,6 +34,7 @@ public function upsertDataForEntry(Entry $entry): void
$date = DateTimeHelper::currentUTCDateTime()->modify('-1 day');
$record = SiteStatisticsRecord::find()
->where(['=', 'entryId', $entry->id])
->andWhere(['=', 'siteId', $entry->siteId])
->andWhere(['>=', 'dateCreated', $date->format('c')])
->one();

Expand All @@ -41,12 +45,15 @@ public function upsertDataForEntry(Entry $entry): void
}

$stats = CarbonTracker::getInstance()->api->getSite($entry);
$record = new SiteStatisticsRecord();
$record->entryId = $stats->entryId;
$record->url = $stats->url;
$record->green = $stats->green;
$record->cleanerThan = $stats->cleanerThan;
$record->rating = $stats->rating;
$record->save();
if ($stats) {
$record = new SiteStatisticsRecord();
$record->entryId = $stats->entryId;
$record->siteId = $stats->siteId;
$record->url = $stats->url;
$record->green = $stats->green;
$record->cleanerThan = $stats->cleanerThan;
$record->rating = $stats->rating;
$record->save();
}
}
}