upskill-event-manager/wordpress-dev/includes/HVAC_Test_User_Factory.php
bengizmo d6211ee364 feat(testing): Implement HVAC_Test_User_Factory and update .gitignore
- Add HVAC_Test_User_Factory class with:
  * User creation with specific roles
  * Multiple role support
  * Persona management system
  * Account cleanup integration
- Create comprehensive test suite in HVAC_Test_User_Factory_Test.php
- Update testing improvement plan documentation
- Add implementation decisions to project memory bank
- Restructure .gitignore with:
  * Whitelist approach for better file management
  * Explicit backup exclusions
  * Specific bin directory inclusions

Part of the Account Management component from the testing framework improvement plan.
2025-04-14 17:41:36 -03:00

80 lines
No EOL
2.2 KiB
PHP

<?php
class HVAC_Test_User_Factory {
private static $personas = [];
public static function define_persona($name, $config) {
self::$personas[$name] = $config;
}
public static function create_user($config) {
$defaults = [
'username' => 'testuser_' . uniqid(),
'email' => null,
'password' => 'password',
'roles' => [],
'meta' => [],
'persona' => null
];
$config = wp_parse_args($config, $defaults);
// Apply persona if specified
if ($config['persona'] && isset(self::$personas[$config['persona']])) {
$persona = self::$personas[$config['persona']];
$config['roles'] = array_merge($config['roles'], $persona['roles'] ?? []);
$config['meta'] = array_merge($config['meta'], $persona['meta'] ?? []);
}
// Create user
$user_id = wp_insert_user([
'user_login' => $config['username'],
'user_pass' => $config['password'],
'user_email' => $config['email'] ?? ($config['username'] . '@example.com')
]);
if (is_wp_error($user_id)) {
return $user_id;
}
$user = new WP_User($user_id);
// Assign roles
foreach ($config['roles'] as $role) {
if (!HVAC_Role_Manager::role_exists($role)) {
HVAC_Role_Manager::create_role($role);
}
$user->add_role($role);
}
// Add meta
foreach ($config['meta'] as $key => $value) {
update_user_meta($user_id, $key, $value);
}
return $user;
}
public static function cleanup_user($user_id) {
$user = get_user_by('id', $user_id);
if (!$user) {
return;
}
// Clean up roles if they're no longer used
foreach ($user->roles as $role) {
$users_with_role = get_users([
'role' => $role,
'fields' => 'ids',
'exclude' => [$user_id]
]);
if (empty($users_with_role)) {
HVAC_Role_Manager::delete_role($role);
}
}
// Delete the user
wp_delete_user($user_id);
}
}