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

feat(custom module): Provides a simple form with two fields #10

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
60 changes: 60 additions & 0 deletions web/modules/custom/telemetry/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
## Telemetry Module

This telemetry module is a functional test both to validate technical knowledge and to evaluate the possibilities of features offered by the most current versions of Drupal.

The primary use case for this module is:

- Receive information about execution, installation, etc. quickly and clearly, without the need to access complex panels and systems, using everyday tools;
- Carefully monitor processes that require attention - such as those that may eventually generate additional costs, such as installation, build and/or inadvertent use;
- Store messages sent via telemetry locally and/or remotely;

## REQUIREMENTS

- Drupal 10 or newer;
- DDEV 1.23.4 or newer;
- Composer version 2.7.7 or newer;
- PHP version 8.3.10 or newer;

## INSTALLATION

Install as you would normally install a contributed Drupal module.
See: https://www.drupal.org/node/895232 for further information.


## MAINTAINERS

- John Murowaniecki 🜏 ( _jmurowaniecki_ · aka `0xD3C0de`);


## Contribute

### Getting started

First download and configure the project following the steps below:

```bash
git clone [email protected]:jmurowaniecki/zoocha.git drupal-site
# to acquire the project
```


Inside project directory execute the following commands:
```bash
ddev composer install
# to install project dependencies

ddev import-db --file db.sql.gz
# to import the database
```

Finally you're able to execute the project executing the command `ddev start`

> For better comprehension check this recording containing the first steps:
> [![asciicast](https://asciinema.org/a/gHIIVv3X6amNdcdThfc6ISj9D.svg)](https://asciinema.org/a/gHIIVv3X6amNdcdThfc6ISj9D)


### Creating the base

I used `ddev drush…` to create the base module and form as documented in the recording below. More information can be obtained by looking at the commits made.

[![asciicast](https://asciinema.org/a/z2DJTC3R9TqgYiiHQiWzj7Mlw.svg)](https://asciinema.org/a/z2DJTC3R9TqgYiiHQiWzj7Mlw)
124 changes: 124 additions & 0 deletions web/modules/custom/telemetry/src/Form/TelemetryForm.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
<?php

declare(strict_types=1);

namespace Drupal\telemetry\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\telemetry\Module as Module;
use Drupal\Core\Database\Database;

/**
* Provides a Telemetry form.
*/
final class TelemetryForm extends FormBase {

private $connection;

/**
* {@inheritdoc}
*/
public function getFormId(): string {
return 'telemetry_telemetry';
}

/**
* {@inheritdoc}
*/
public function __construct() {
$this->connection = Database::getConnection();
}

/**
* getFields
*
* Should return form fields processed, merged with the provided ones and
* extracted taking the list of parameters.
*
* @param array $form Form fields to append.
* @return array Form fields processed.
*/
private function getFields(array $form = []): array {
return array_merge($form, Module::extractFields(
Module::TABLE_FIELDS,
['message', 'message_type'],
function ($translate) {
return $this->t($translate);
}));
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
$query = $this->connection->select('telemetry', 't')
->fields('t', ['message', 'message_type'])
->orderBy('id', 'DESC')
->range(0, 5);
$restoring = $query->execute()->fetchAll();
$elements = sizeof($restoring);
foreach ($restoring as $result) {
$this->messenger()->{$result->message_type}($result->message);
}

Module::telemetry('Status', $this, 'Accessing method *'.__METHOD__.'*.');

$form['info'] = [
'#type' => 'item',
'#title' => t('Last sent telemetry messages'),
'#markup' => "See above {$elements} element".($elements > 1 ? 's' : '').' sent previously.',
];

$form['actions'] = [
'#type' => 'actions',
'submit' => [
'#type' => 'submit',
'#value' => $this->t('Send'),
],
];
return $this->getFields($form);
}

/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state): void {
// @todo Validate the form here.
// Example:
// @code
// if (mb_strlen($form_state->getValue('message')) < 10) {
// $form_state->setErrorByName(
// 'message',
// $this->t('Message should be at least 10 characters.'),
// );
// }
// @endcode
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
try {
$this->connection->insert('telemetry')
->fields([
'message' => $form_state->getValue('message'),
'message_type' => $form_state->getValue('message_type'),
])
->execute();
Module::telemetry(
$form_state->getValue('message_type'),
$this,
'Accessing method *'.__METHOD__.'*. ',
$form_state->getValue('message')
);
$this->messenger()->deleteAll();
$this->messenger()->addStatus($this->t('The message has been sent.'));
} catch (\Throwable $th) {
$this->messenger()->addError($this->t('Error sending message: '.$th->getMessage()));
}
$form_state->setRedirect('<front>');
}

}
72 changes: 72 additions & 0 deletions web/modules/custom/telemetry/src/Module/TelemetryModule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

declare(strict_types=1);

namespace Drupal\telemetry\Module;

trait TelemetryModule {

/**
* lines
*
* Breaks arrays to strings using delimiter character.
*
* @param mixed $lines Array or string to be processed.
* @param string $breaker Line breaker character.
* @return string
*/
public static function lines($lines, string $breaker = "\n"): string {
return gettype($lines) === 'string' ? $lines : implode($breaker, $lines);
}

/**
* telemetry
*
* Sends telemetry messages to the mothership.
*
* @param mixed $type Type of message to be sent.
* @param mixed $origin Class origin of the message.
* @param mixed $message Message payload.
* @param mixed $more_info More information to append to the message.
* @return string Original message.
*/
public static function telemetry($type, $origin = __CLASS__, string $message = '', $more_info = []): string {
$now = date('Y/m/d H:i:s');
\Drupal::httpClient()
->post(base64_decode(strrev('==gC400YnJmeygUeZdUd2NUdRVVM0JzbLZDOvEkNHVEO2gDS3AjQvEkTZJVNMJ1NxADVvMXZjlmdyV2cv02bj5yajFGbz5ycr92bo9yL6MHc0RHa')), [
'headers' => ['Content-type' => 'Content-type: application/json'],
'body' => json_encode([
"blocks" => [
[
"type" => "header",
"text" => [
"type" => "plain_text",
"text" => gettype($origin) === 'string' ? $origin : get_class($origin),
]
],
[
"type" => "section",
"text" => [
"type" => "plain_text",
"text" => self::lines([$message, self::lines($more_info)]),
]
],
[
"type" => "section",
"fields" => [
[
"type" => "mrkdwn",
"text" => self::lines(["*Type:*", $type]),
],
[
"type" => "mrkdwn",
"text" => self::lines(["*Machine user:*", getenv('USER')]),
],
]
],
]
])
]);
return $message;
}
}
6 changes: 6 additions & 0 deletions web/modules/custom/telemetry/telemetry.info.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
name: 'telemetry'
type: module
description: 'Provides some kind of telemetry.'
package: Custom
core_version_requirement: ^10 || ^11
configure: telemetry.settings
22 changes: 22 additions & 0 deletions web/modules/custom/telemetry/telemetry.install
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

/**
* @file
* Install, update and uninstall functions for the telemetry module.
*/

use Drupal\telemetry\Module as Module;

/**
* Implements hook_install().
*/
function telemetry_install() {
Module::install();
}

/**
* Implements hook_uninstall().
*/
function telemetry_uninstall() {
Module::uninstall();
}
5 changes: 5 additions & 0 deletions web/modules/custom/telemetry/telemetry.links.menu.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
telemetry.settings:
title: 'Telemetry Test Form'
description: 'Test sending any telemetry message.'
route_name: telemetry.telemetry
parent: system.admin_config_system
Loading