expense_tracker-1.2.1/src/Plugin/DevelGenerate/EtTransactionDevelGenerate.php
src/Plugin/DevelGenerate/EtTransactionDevelGenerate.php
<?php
namespace Drupal\expense_tracker\Plugin\DevelGenerate;
use Drupal\Core\Field\Plugin\Field\FieldType\UriItem;
use Drupal\Core\Form\FormStateInterface;
use Drupal\devel_generate\DevelGenerateBase;
use Drupal\image\Plugin\Field\FieldType\ImageItem;
use Drupal\text\Plugin\Field\FieldType\TextLongItem;
use Drupal\expense_tracker\Entity\EtTransaction;
/**
* Provides a ContentDevelGenerate plugin.
*
* @DevelGenerate(
* id = "EtTransaction",
* label = @Translation("Transaction Devel Generate"),
* description = @Translation("Fenerate expense and income transactions"),
* url = "generate-transaction",
* permission = "administer devel_generate",
* settings = {
* "num" = 50,
* "kill" = FALSE,
* }
* )
*/
class EtTransactionDevelGenerate extends DevelGenerateBase {
/**
* Le formulaire à renseigner avant la génération du contenu
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$form['num'] = [
'#type' => 'textfield',
'#title' => $this->t('Combien de EtTransactionx voulez-vous générer ?'),
'#default_value' => $this->getSetting('num'),
'#size' => 10,
];
$form['kill'] = [
'#type' => 'checkbox',
'#title' => $this->t('Supprimer tous les EtTransactionx en base avant la génération ?'),
'#default_value' => $this->getSetting('kill'),
];
return $form;
}
protected function generateElements(array $values) {
$num = $values['num'];
$kill = $values['kill'];
if ($kill) {
$nbDeletedItems = 0;
// Suppression des contenus existants
foreach (EtTransaction::loadMultiple() as $EtTransaction) {
$EtTransaction->delete();
$nbDeletedItems++;
}
$this->setMessage($this->formatPlural($nbDeletedItems, '1 EtTransaction a été supprimé', '@count EtTransactionx supprimés'));
}
// $transaction_type = array( 'income', 'expense');
$transaction_category = array( 'new', 'existing');
$current_timestamp = time();
$one_week_ago = strtotime('-1 week', $current_timestamp);
$one_month_ago = strtotime('-1 months', $current_timestamp);
$two_month_ago = strtotime('-2 months', $current_timestamp);
$three_month_ago = strtotime('-3 months', $current_timestamp);
$five_month_ago = strtotime('-5 months', $current_timestamp);
$ten_month_ago = strtotime('-10 months', $current_timestamp);
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();
$entity_type = $definition_update_manager->getEntityType('EtTransaction'); // À modifier en fonction du nom machine de votre type d'entité
$this_year_start = strtotime("-0 year first day of january");
$end_timestamp = strtotime("last day of this year 11:59 p.m.");
$start_timestamp = strtotime('-10 year first day of this year 12:00 a.m.', $this_year_start);
for ($i = 1; $i <= $num; $i++) {
$category = \Drupal::entityQuery('et_transaction')
->accessCheck(TRUE)
->execute();
$random_transaction_data = $this->generate_random_transaction();
$transaction_title = $random_transaction_data['random_transaction'];
$transaction_type = $random_transaction_data['transaction_type'];
$rand_for_date = rand(0, 6);
// Création de l'entité avec des valeurs générée aléatoirement en fonction de leur type
// ImageItem, TextLongItem, UriItem sont a adapter en fonction des types de vos propriétés
$EtTransaction = EtTransaction::create([
// 'title' => $this->getRandom()->word(mt_rand(2, 50)),
// 'title' => $this->lorem(1, 5, false),
'title' => $transaction_title,
'transaction_type' => $transaction_type,
'amount' => rand(4,900),
'date' => rand($start_timestamp,$end_timestamp),
'transaction_category' => $transaction_category[array_rand($transaction_category)],
// 'category' => $category[array_rand($category)],
]);
if(!empty($category)) {
$EtTransaction->set('category',['target_id' => $category[array_rand($category)]]);
}
// On renseigne aussi les champs s'il y'en a.
$this->populateFields($EtTransaction);
// Et on sauvegarde notre contenu
$EtTransaction->save();
}
}
public function validateDrushParams(array $args, array $options = []) {
return [
'num' => $options['num'],
'kill' => $options['kill'],
];
}
public function lorem($count = 1, $max = 20, $standard = true) {
$output = '';
if ($standard) {
$output = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, ' .
'sed do eiusmod tempor incididunt ut labore et dolore magna ' .
'aliqua.';
}
$pool = explode(
' ',
'a ab ad accusamus adipisci alias aliquam amet animi aperiam ' .
'architecto asperiores aspernatur assumenda at atque aut beatae ' .
'blanditiis cillum commodi consequatur corporis corrupti culpa ' .
'cum cupiditate debitis delectus deleniti deserunt dicta ' .
'dignissimos distinctio dolor ducimus duis ea eaque earum eius ' .
'eligendi enim eos error esse est eum eveniet ex excepteur ' .
'exercitationem expedita explicabo facere facilis fugiat harum ' .
'hic id illum impedit in incidunt ipsa iste itaque iure iusto ' .
'laborum laudantium libero magnam maiores maxime minim minus ' .
'modi molestiae mollitia nam natus necessitatibus nemo neque ' .
'nesciunt nihil nisi nobis non nostrum nulla numquam occaecati ' .
'odio officia omnis optio pariatur perferendis perspiciatis ' .
'placeat porro possimus praesentium proident quae quia quibus ' .
'quo ratione recusandae reiciendis rem repellat reprehenderit ' .
'repudiandae rerum saepe sapiente sequi similique sint soluta ' .
'suscipit tempora tenetur totam ut ullam unde vel veniam vero ' .
'vitae voluptas'
);
$max = ($max <= 3) ? 4 : $max;
$count = ($count < 1) ? 1 : (($count > 2147483646) ? 2147483646 : $count);
for ($i = 0, $add = ($count - (int) $standard); $i < $add; $i++) {
shuffle($pool);
$words = array_slice($pool, 0, mt_rand(3, $max));
$output .= ((! $standard && $i === 0) ? '' : ' ') . ucfirst(implode(' ', $words)) . '.';
}
return $output;
}
/**
* Generate random transacrion
* @return
*/
function generate_random_transaction() {
$transactions = array(
'expense' => array(
'Concert tickets',
'Sporting events',
'Family activities & vacations',
'Streaming services and other subscriptions',
'Restaurants',
'Video games',
'Hobbies',
'Gym memberships',
'Clothes and shoes',
'Home decor and furnishings',
'Gifts',
'Housing',
'Transportation',
'Food',
'Utilities',
'Insurance',
'Medical & Healthcar',
'Miscellaneous',
),
'income' => array(
'Create a course',
'Write an e-book',
'Rental income',
'Affiliate marketing',
'Flip retail products',
'Sell photography online',
'Buy crowdfunded real estate',
'Peer-to-peer lending',
'Dividend stocks',
'Create an app',
'Rent out a parking space',
'REITs',
'A bond ladder',
'Sponsored posts on social media',
'Invest in a high-yield CD or savings account',
'Rent out your home short-term',
'Advertise on your car',
'Create a blog or YouTube channel',
'Rent out useful household items',
'Sell designs online',
'Salary',
)
);
$random_keys = array('expense', 'income');
$random_key = $random_keys[array_rand($random_keys)];
$random_transactions = $transactions[$random_key];
$random_transaction = $random_transactions[array_rand($random_transactions)];
$transaction_data = array(
'transaction_type' => $random_key,
'random_transaction' => $random_transaction,
);
return $transaction_data;
}
}