Skip to content
Open
Show file tree
Hide file tree
Changes from 8 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
116 changes: 116 additions & 0 deletions CLI/GenerateUsersCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
<?php

declare(strict_types=1);

namespace openvk\CLI;

use Chandler\Security\User as ChandlerUser;
use Faker\Factory as FakerFactory;
use openvk\Web\Models\Entities\User;
use openvk\Web\Models\Exceptions\InvalidUserNameException;
use openvk\Web\Util\Validator;
use Random\RandomException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class GenerateUsersCommand extends Command
{
protected static $defaultName = "generate-users";
protected function configure(): void
{
$this->setDescription("Generate test user accounts for development")
->addOption(
"count",
"c",
InputOption::VALUE_REQUIRED,
"Number of users to create",
1
);
}

//Duplicate the logic from the Web/Presenters/AuthPresenter.php class
/**
* @throws RandomException
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$faker = FakerFactory::create("en_US");
$count = (int) $input->getOption("count");

if ($count < 1) {
$io->error("Count must be at least 1.");

return Command::FAILURE;
}

$created = [];

for ($i = 1; $i <= $count; $i++) {
$email = $faker->unique()->safeEmail();
$password = $this->generatePassword();

try {
$user = new User();
$user->setFirst_Name($faker->firstName());
$user->setLast_Name($faker->lastName());
$user->setSex(0);
$user->setEmail($email);
$user->setSince(date("Y-m-d H:i:s"));
$user->setRegistering_Ip("127.0.0.1");
$user->setBirthday($faker->dateTimeBetween("-60 years", "-18 years")->getTimestamp());
$user->setActivated(1);
} catch (InvalidUserNameException $ex) {
$io->error("Failed to set name for user #{$i}: " . $ex->getMessage());
Comment thread
MrKrasnov marked this conversation as resolved.

return Command::FAILURE;
}

$chUser = ChandlerUser::create($email, $password);
if (!$chUser) {
$io->error("Failed to create Chandler user for {$email}");

return Command::FAILURE;
}

$user->setUser($chUser->getId());
$user->save(false);

$created[] = [
"id" => $user->getId(),
"email" => $email,
"password" => $password,
"url" => "/id" . $user->getId(),
];
}

$io->success("Created " . count($created) . " user(s).");

$rows = array_map(static fn(array $u): array => [
$u["id"],
$u["email"],
$u["password"],
$u["url"],
], $created);

$io->table(["ID", "Email", "Password", "Profile URL"], $rows);

return Command::SUCCESS;
}

/**
* @throws RandomException
*/
private function generatePassword(): string
{
do {
$password = "OvK" . bin2hex(random_bytes(4)) . "A1";
} while (!Validator::i()->passwordStrong($password));

return $password;
}

}
24 changes: 23 additions & 1 deletion CLI/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,26 @@ Rebuilds photo thumbnails and image sizes.
Fetches Toncoin transactions for payment processing.

### upgrade
Performs database upgrades and migrations.
Performs database upgrades and migrations.

## Available Commands for local development

### generate-users
Creates test user accounts for local development.

**Usage:**
```bash
# Create one user (default)
php openvkctl generate-users

# Create 20 users
php openvkctl generate-users --count=20

# Create 20 users
php openvkctl generate-users -c 20
```

**Options:**
- `--count`, `-c`: Number of users to create (default: 1)

The command prints a table with profile ID, email, password, and profile URL for each created user.
16 changes: 9 additions & 7 deletions Web/Presenters/UserPresenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,16 +199,18 @@ public function renderEdit(): void
}

if ($this->postParam("marialstatus") <= 8 && $this->postParam("marialstatus") >= 0) {
$user->setMarital_Status($this->postParam("marialstatus"));
}
$maritalStatus = (int) $this->postParam("marialstatus");
$user->setMarital_Status($maritalStatus);

if ($this->postParam("maritalstatus-user")) {
if (in_array((int) $this->postParam("marialstatus"), [0, 1, 8])) {
if (in_array($maritalStatus, [0, 1, 8], true)) {
Comment thread
veselcraft marked this conversation as resolved.
$user->setMarital_Status_User(null);
} else {
$mUser = (new Users())->getByAddress($this->postParam("maritalstatus-user"));
if ($mUser) {
if ($mUser->getId() !== $this->user->id) {
$partnerAddress = trim((string) $this->postParam("maritalstatus-user"));
if (empty($partnerAddress)) {
$user->setMarital_Status_User(null);
} else {
$mUser = (new Users())->getByAddress($partnerAddress);
if ($mUser && $mUser->getId() !== $this->user->id) {
$user->setMarital_Status_User($mUser->getId());
}
}
Expand Down
4 changes: 2 additions & 2 deletions Web/Presenters/templates/User/Edit.latte
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@
n:attr="style => $user->getMaritalStatusUser() || ($user->getMaritalStatus() && !in_array($user->getMaritalStatus(), [0, 1, 8])) ? '' : 'display: none;'">
<td width="120" valign="top"></td>
<td>
<input type="text" placeholder="{_page_address}" name="maritalstatus-user"
n:attr="value => $user->getMaritalStatusUser() ? $user->getMaritalStatusUser()->getId() : ''" />
<input type="text" placeholder="{_marital_status_user_id}" name="maritalstatus-user"
n:attr="value => $user->getMaritalStatusUser() ? ltrim($user->getMaritalStatusUser()->getURL(), '/') : ''" />
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вместо того, чтобы городить костыли с ltrim, можно было создать в объекте User отдельную функцию для screenname

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В корне не согласен. Для показа чего либо во вьюхе совсем не повод захломлять методами и без того большую модель. Модель в целом должна использоваться для возрата данных в данном случае а стилизация текста это задача самой вьюхи.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исключением может быть yii2 😭

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Блин 1822 строчки, его бы декомпозировать как-то по хорошему
image

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Рефакторы только после тестов, пожалуйста

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В корне не согласен. Для показа чего либо во вьюхе совсем не повод захломлять методами и без того большую модель. Модель в целом должна использоваться для возрата данных в данном случае а стилизация текста это задача самой вьюхи.

Остаюсь на своём - это костыли. В API используется (увы) один уже такой связанный со screen_name (он просто повторяет функцию, без /), и вот ещё один тут. Но вот для отдельной ф-ции я погорячился, можно прост добавить отдельный аргумент в getURL() с параметром типа nobackslash

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это более рациональное решение, добавил b21d088

</td>
</tr>
<tr>
Expand Down
8 changes: 4 additions & 4 deletions Web/static/js/al_wall.js
Original file line number Diff line number Diff line change
Expand Up @@ -799,12 +799,12 @@ async function withdraw(id) {
}

function toggleMaritalStatus(e) {
let elem = $("#maritalstatus-user");
$("#maritalstatus-user-select").empty();
let maritalstatus = $("#maritalstatus-user");
if ([0, 1, 8].includes(Number(e.value))) {
elem.hide();
maritalstatus.hide();
maritalstatus.find('input[name="maritalstatus-user"]').val('');
} else {
elem.show();
maritalstatus.show();
}
}

Expand Down
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"analyse": "phpstan analyse --memory-limit 1G"
},
"require": {
"php": "~7.3||~8.1",
"php": "~7.3||~8.2",
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не видел инстансов, где 7 пыха всё ещё используется, можно смело дропать, но это лучше оставить на другой ПР, ибо придётся тянуть изменения в доках

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

солидарен, лучше дропнуть отдельным PR. 7.3 и уж тем более 7.4 уже 4 года как EOL, дистры его не предоставляют в пакетах

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вернул версию - revert(composer.json): revert php version

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Создал отдельный ПР - #1592

"whichbrowser/parser": "dev-master",
"james-heinrich/getid3": "^1.9@dev",
"rybakit/msgpack": "dev-master",
Expand All @@ -30,6 +30,7 @@
"minimum-stability": "beta",
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.68",
"phpstan/phpstan": "^2.1"
"phpstan/phpstan": "^2.1",
"fakerphp/faker": "^1.24"
}
}
69 changes: 66 additions & 3 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions locales/by.strings
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@
"your_email_address" = "Адрас Вашай электроннай пошты";
"your_page_address" = "Адрас Вашай старонкі";
"page_address" = "Адрас старонкі";
"marital_status_user_id" = "ID карыстальніка";
"current_email_address" = "Ныняшні адрас";
"page_id" = "ID старонкі";
"you_can_also" = "Вы таксама можаце";
Expand Down
1 change: 1 addition & 0 deletions locales/by_lat.strings
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@
"your_email_address" = "Adras Vašaj elektronaj pošty";
"your_page_address" = "Adras Vašaj staronki";
"page_address" = "Adras staronki";
"marital_status_user_id" = "ID karystálnika";
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не трогайте плиз локали на языках которых вы не разговариваете. этим занимаются переводчики

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне писать все в латиницу или вообще не писать ключи на другие strings ?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Все языки фолбэчатся на русский или английский. Как следствие, русского и английского достаточно

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

исчерпывающий ответ @WerySkok

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"current_email_address" = "Ciapierašni adras";
"page_id" = "ID staronki";
"you_can_also" = "Vy majecie racyju";
Expand Down
1 change: 1 addition & 0 deletions locales/de.strings
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@
"your_email_address" = "Deine E-Mail-Adresse";
"your_page_address" = "Deine Profil-URL";
"page_address" = "Profil-URL";
"marital_status_user_id" = "Benutzer-ID";
"current_email_address" = "Aktuelle E-Mail-Adresse";
"page_id" = "Seiten-ID";
"you_can_also" = "Du kannst auch";
Expand Down
1 change: 1 addition & 0 deletions locales/en.strings
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,7 @@
"your_email_address" = "Your Email address";
"your_page_address" = "Your address page";
"page_address" = "Address page";
"marital_status_user_id" = "User ID";
"current_email_address" = "Current email address";
"new_email_address" = "New email address";
"save_email_address" = "Save email address";
Expand Down
1 change: 1 addition & 0 deletions locales/eo.strings
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@
"your_email_address" = "Via retpoŝta adreso";
"your_page_address" = "Via adrespaĝo";
"page_address" = "Adrespaĝo";
"marital_status_user_id" = "Uzanta ID";
"current_email_address" = "Aktuala retadreso";
"page_id" = "Paĝa ID";
"you_can_also" = "Vi povas anka";
Expand Down
1 change: 1 addition & 0 deletions locales/hy.strings
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,7 @@
"your_email_address" = "Ձեր էլեկտրոնային հասցեն";
"your_page_address" = "Ձեր էջի հասցեն";
"page_address" = "Էջի հասցեն";
"marital_status_user_id" = "Օգտատիրոջ ID";
"current_email_address" = "Ներկայիս էլեկտրոնային հասցեն";
"new_email_address" = "Նոր էլեկտրոնային հասցեն";
"save_email_address" = "Պահպանել էլեկտրոնային հասցեն";
Expand Down
1 change: 1 addition & 0 deletions locales/id.strings
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,7 @@
"your_email_address" = "Alamat Surelmu";
"your_page_address" = "Alamat halamanmu";
"page_address" = "Address page";
"marital_status_user_id" = "ID pengguna";
"current_email_address" = "Alamat surel sekarang";
"page_id" = "ID Halaman";
"you_can_also" = "Kamu juga dapat";
Expand Down
1 change: 1 addition & 0 deletions locales/kk.strings
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,7 @@
"your_email_address" = "Сіздің Email-мекенжайыңыз";
"your_page_address" = "Сіздің парақшаңыздың мекенжайы";
"page_address" = "Парақшаңыздың мекенжайы";
"marital_status_user_id" = "Пайдаланушы ID";
"current_email_address" = "Қазіргі Email-мекенжайы";
"new_email_address" = "Жаңа Email-мекенжайы";
"save_email_address" = "Email-мекенжайын сақтау";
Expand Down
1 change: 1 addition & 0 deletions locales/kk_lat.strings
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,7 @@
"your_email_address" = "Sizdiń Email-mekenjayıńız";
"your_page_address" = "Sizdiń paraqcańızdıń mekenjayı";
"page_address" = "Paraqcańızdıń mekenjayı";
"marital_status_user_id" = "Paýdalanwşı ID";
"current_email_address" = "Qazirgi Email-mekenjayı";
"new_email_address" = "Jańa Email-mekenjayı";
"save_email_address" = "Email-mekenjayın saqtaw";
Expand Down
1 change: 1 addition & 0 deletions locales/pl.strings
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,7 @@
"your_email_address" = "Twój adres e-mail";
"your_page_address" = "Adres Twojej strony";
"page_address" = "Adres strony";
"marital_status_user_id" = "ID użytkownika";
"current_email_address" = "Aktualny adres";
"page_id" = "ID strony";
"you_can_also" = "Możesz także";
Expand Down
1 change: 1 addition & 0 deletions locales/ru.strings
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,7 @@
"your_email_address" = "Адрес Вашей электронной почты";
"your_page_address" = "Адрес Вашей страницы";
"page_address" = "Адрес страницы";
"marital_status_user_id" = "ID пользователя";
"current_email_address" = "Текущий адрес";
"new_email_address" = "Новый адрес";
"save_email_address" = "Сохранить адрес";
Expand Down
Loading
Loading