Skip to content

Commit

Permalink
feat: add is_current and profile_link methods (#2924)
Browse files Browse the repository at this point in the history
  • Loading branch information
Levdbas committed Feb 27, 2024
1 parent e07751e commit b048da8
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 7 deletions.
52 changes: 45 additions & 7 deletions src/User.php
Expand Up @@ -200,6 +200,18 @@ public function get_field($field_name = null)
return $this->meta($field_name);
}

/**
* Check if the user object is the current user
*
* @api
*
* @return bool true if the user is the current user
*/
public function is_current(): bool
{
return \get_current_user_id() === $this->ID;
}

/**
* Get the name of the User
*
Expand Down Expand Up @@ -279,13 +291,13 @@ public function get_meta($field_name)
}

/**
* Creates an associative array with user role slugs and their translated names.
*
* @internal
* @since 1.8.5
* @param array $roles user roles.
* @return array|null
*/
* Creates an associative array with user role slugs and their translated names.
*
* @internal
* @since 1.8.5
* @param array $roles user roles.
* @return array|null
*/
protected function get_roles($roles)
{
if (empty($roles)) {
Expand Down Expand Up @@ -345,6 +357,32 @@ public function roles()
return $this->roles;
}

/**
* Gets the profile link to the user’s profile in the WordPress admin if the ID in the user object
* is the same as the current user’s ID.
*
* @api
* @since 2.1.0
* @example
*
* Get the profile URL for the current user:
*
* ```twig
* {% if user.profile_link %}
* <a href="{{ user.profile_link }}">My profile</a>
* {% endif %}
* ```
* @return string|null The profile link for the current user.
*/
public function profile_link(): ?string
{
if (!$this->is_current()) {
return null;
}

return \get_edit_profile_url($this->ID);
}

/**
* Checks whether a user has a capability.
*
Expand Down
28 changes: 28 additions & 0 deletions tests/test-timber-user.php
Expand Up @@ -195,6 +195,34 @@ public function testLinks()
$this->assertEquals('16th', $user->president);
}

public function testIsCurrent()
{
$uid = $this->factory->user->create([
'display_name' => 'Charles vonderZwen',
'user_login' => 'cvanderzwen',
]);

$user = Timber::get_user($uid);

wp_set_current_user($uid);

$this->assertTrue($user->is_current());
}

public function testProfileLink()
{
$uid = $this->factory->user->create([
'display_name' => 'Boaty McBoatface',
'user_login' => 'BMcBoatface',
]);

wp_set_current_user($uid);

$user = Timber::get_user($uid);

$this->assertEquals('http://example.org/wp-admin/profile.php', $user->profile_link());
}

public function testAvatar()
{
// Restore integration-free Class Map for users.
Expand Down

0 comments on commit b048da8

Please sign in to comment.