repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Resources/Gen/GoalsBase.php
src/Asana/Resources/Gen/GoalsBase.php
<?php namespace Asana\Resources\Gen; class GoalsBase { /** * @param Asana/Client client The client instance */ public function __construct($client) { $this->client = $client; } /** Add a collaborator to a goal * * @param string $goal_gid (required) Globally unique identifier for the goal. * @param array $params * @param array $options * @return response */ public function addFollowers($goal_gid, $params = array(), $options = array()) { $path = "/goals/{goal_gid}/addFollowers"; $path = str_replace("{goal_gid}", $goal_gid, $path); return $this->client->post($path, $params, $options); } /** Create a goal * * @param array $params * @param array $options * @return response */ public function createGoal($params = array(), $options = array()) { $path = "/goals"; return $this->client->post($path, $params, $options); } /** Create a goal metric * * @param string $goal_gid (required) Globally unique identifier for the goal. * @param array $params * @param array $options * @return response */ public function createGoalMetric($goal_gid, $params = array(), $options = array()) { $path = "/goals/{goal_gid}/setMetric"; $path = str_replace("{goal_gid}", $goal_gid, $path); return $this->client->post($path, $params, $options); } /** Delete a goal * * @param string $goal_gid (required) Globally unique identifier for the goal. * @param array $params * @param array $options * @return response */ public function deleteGoal($goal_gid, $params = array(), $options = array()) { $path = "/goals/{goal_gid}"; $path = str_replace("{goal_gid}", $goal_gid, $path); return $this->client->delete($path, $params, $options); } /** Get a goal * * @param string $goal_gid (required) Globally unique identifier for the goal. * @param array $params * @param array $options * @return response */ public function getGoal($goal_gid, $params = array(), $options = array()) { $path = "/goals/{goal_gid}"; $path = str_replace("{goal_gid}", $goal_gid, $path); return $this->client->get($path, $params, $options); } /** Get goals * * @param array $params * @param array $options * @return response */ public function getGoals($params = array(), $options = array()) { $path = "/goals"; return $this->client->getCollection($path, $params, $options); } /** Get parent goals from a goal * * @param string $goal_gid (required) Globally unique identifier for the goal. * @param array $params * @param array $options * @return response */ public function getParentGoalsForGoal($goal_gid, $params = array(), $options = array()) { $path = "/goals/{goal_gid}/parentGoals"; $path = str_replace("{goal_gid}", $goal_gid, $path); return $this->client->getCollection($path, $params, $options); } /** Remove a collaborator from a goal * * @param string $goal_gid (required) Globally unique identifier for the goal. * @param array $params * @param array $options * @return response */ public function removeFollowers($goal_gid, $params = array(), $options = array()) { $path = "/goals/{goal_gid}/removeFollowers"; $path = str_replace("{goal_gid}", $goal_gid, $path); return $this->client->post($path, $params, $options); } /** Update a goal * * @param string $goal_gid (required) Globally unique identifier for the goal. * @param array $params * @param array $options * @return response */ public function updateGoal($goal_gid, $params = array(), $options = array()) { $path = "/goals/{goal_gid}"; $path = str_replace("{goal_gid}", $goal_gid, $path); return $this->client->put($path, $params, $options); } /** Update a goal metric * * @param string $goal_gid (required) Globally unique identifier for the goal. * @param array $params * @param array $options * @return response */ public function updateGoalMetric($goal_gid, $params = array(), $options = array()) { $path = "/goals/{goal_gid}/setMetricCurrentValue"; $path = str_replace("{goal_gid}", $goal_gid, $path); return $this->client->post($path, $params, $options); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Resources/Gen/ProjectsBase.php
src/Asana/Resources/Gen/ProjectsBase.php
<?php namespace Asana\Resources\Gen; class ProjectsBase { /** * @param Asana/Client client The client instance */ public function __construct($client) { $this->client = $client; } /** Add a custom field to a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function addCustomFieldSettingForProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}/addCustomFieldSetting"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->post($path, $params, $options); } /** Add followers to a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function addFollowersForProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}/addFollowers"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->post($path, $params, $options); } /** Add users to a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function addMembersForProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}/addMembers"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->post($path, $params, $options); } /** Create a project * * @param array $params * @param array $options * @return response */ public function createProject($params = array(), $options = array()) { $path = "/projects"; return $this->client->post($path, $params, $options); } /** Create a project in a team * * @param string $team_gid (required) Globally unique identifier for the team. * @param array $params * @param array $options * @return response */ public function createProjectForTeam($team_gid, $params = array(), $options = array()) { $path = "/teams/{team_gid}/projects"; $path = str_replace("{team_gid}", $team_gid, $path); return $this->client->post($path, $params, $options); } /** Create a project in a workspace * * @param string $workspace_gid (required) Globally unique identifier for the workspace or organization. * @param array $params * @param array $options * @return response */ public function createProjectForWorkspace($workspace_gid, $params = array(), $options = array()) { $path = "/workspaces/{workspace_gid}/projects"; $path = str_replace("{workspace_gid}", $workspace_gid, $path); return $this->client->post($path, $params, $options); } /** Delete a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function deleteProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->delete($path, $params, $options); } /** Duplicate a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function duplicateProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}/duplicate"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->post($path, $params, $options); } /** Get a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function getProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->get($path, $params, $options); } /** Get multiple projects * * @param array $params * @param array $options * @return response */ public function getProjects($params = array(), $options = array()) { $path = "/projects"; return $this->client->getCollection($path, $params, $options); } /** Get projects a task is in * * @param string $task_gid (required) The task to operate on. * @param array $params * @param array $options * @return response */ public function getProjectsForTask($task_gid, $params = array(), $options = array()) { $path = "/tasks/{task_gid}/projects"; $path = str_replace("{task_gid}", $task_gid, $path); return $this->client->getCollection($path, $params, $options); } /** Get a team's projects * * @param string $team_gid (required) Globally unique identifier for the team. * @param array $params * @param array $options * @return response */ public function getProjectsForTeam($team_gid, $params = array(), $options = array()) { $path = "/teams/{team_gid}/projects"; $path = str_replace("{team_gid}", $team_gid, $path); return $this->client->getCollection($path, $params, $options); } /** Get all projects in a workspace * * @param string $workspace_gid (required) Globally unique identifier for the workspace or organization. * @param array $params * @param array $options * @return response */ public function getProjectsForWorkspace($workspace_gid, $params = array(), $options = array()) { $path = "/workspaces/{workspace_gid}/projects"; $path = str_replace("{workspace_gid}", $workspace_gid, $path); return $this->client->getCollection($path, $params, $options); } /** Get task count of a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function getTaskCountsForProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}/task_counts"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->get($path, $params, $options); } /** Create a project template from a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function projectSaveAsTemplate($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}/saveAsTemplate"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->post($path, $params, $options); } /** Remove a custom field from a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function removeCustomFieldSettingForProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}/removeCustomFieldSetting"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->post($path, $params, $options); } /** Remove followers from a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function removeFollowersForProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}/removeFollowers"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->post($path, $params, $options); } /** Remove users from a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function removeMembersForProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}/removeMembers"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->post($path, $params, $options); } /** Update a project * * @param string $project_gid (required) Globally unique identifier for the project. * @param array $params * @param array $options * @return response */ public function updateProject($project_gid, $params = array(), $options = array()) { $path = "/projects/{project_gid}"; $path = str_replace("{project_gid}", $project_gid, $path); return $this->client->put($path, $params, $options); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Resources/Gen/AuditLogAPIBase.php
src/Asana/Resources/Gen/AuditLogAPIBase.php
<?php namespace Asana\Resources\Gen; class AuditLogAPIBase { /** * @param Asana/Client client The client instance */ public function __construct($client) { $this->client = $client; } /** Get audit log events * * @param string $workspace_gid (required) Globally unique identifier for the workspace or organization. * @param array $params * @param array $options * @return response */ public function getAuditLogEvents($workspace_gid, $params = array(), $options = array()) { $path = "/workspaces/{workspace_gid}/audit_log_events"; $path = str_replace("{workspace_gid}", $workspace_gid, $path); return $this->client->getCollection($path, $params, $options); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Resources/Gen/GoalRelationshipsBase.php
src/Asana/Resources/Gen/GoalRelationshipsBase.php
<?php namespace Asana\Resources\Gen; class GoalRelationshipsBase { /** * @param Asana/Client client The client instance */ public function __construct($client) { $this->client = $client; } /** Add a supporting goal relationship * * @param string $goal_gid (required) Globally unique identifier for the goal. * @param array $params * @param array $options * @return response */ public function addSupportingRelationship($goal_gid, $params = array(), $options = array()) { $path = "/goals/{goal_gid}/addSupportingRelationship"; $path = str_replace("{goal_gid}", $goal_gid, $path); return $this->client->post($path, $params, $options); } /** Get a goal relationship * * @param string $goal_relationship_gid (required) Globally unique identifier for the goal relationship. * @param array $params * @param array $options * @return response */ public function getGoalRelationship($goal_relationship_gid, $params = array(), $options = array()) { $path = "/goal_relationships/{goal_relationship_gid}"; $path = str_replace("{goal_relationship_gid}", $goal_relationship_gid, $path); return $this->client->get($path, $params, $options); } /** Get goal relationships * * @param array $params * @param array $options * @return response */ public function getGoalRelationships($params = array(), $options = array()) { $path = "/goal_relationships"; return $this->client->getCollection($path, $params, $options); } /** Removes a supporting goal relationship * * @param string $goal_gid (required) Globally unique identifier for the goal. * @param array $params * @param array $options * @return response */ public function removeSupportingRelationship($goal_gid, $params = array(), $options = array()) { $path = "/goals/{goal_gid}/removeSupportingRelationship"; $path = str_replace("{goal_gid}", $goal_gid, $path); return $this->client->post($path, $params, $options); } /** Update a goal relationship * * @param string $goal_relationship_gid (required) Globally unique identifier for the goal relationship. * @param array $params * @param array $options * @return response */ public function updateGoalRelationship($goal_relationship_gid, $params = array(), $options = array()) { $path = "/goal_relationships/{goal_relationship_gid}"; $path = str_replace("{goal_relationship_gid}", $goal_relationship_gid, $path); return $this->client->put($path, $params, $options); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Errors/RateLimitEnforcedError.php
src/Asana/Errors/RateLimitEnforcedError.php
<?php namespace Asana\Errors; use Asana\Errors\RetryableAsanaError; class RateLimitEnforcedError extends RetryableAsanaError { const MESSAGE = 'Rate Limit Enforced'; const STATUS = 429; public function __construct($response) { parent::__construct(self::MESSAGE, self::STATUS, $response); $this->retryAfter = isset($response->headers['Retry-After']) ? (float)$response->headers['Retry-After'] : null; } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Errors/ServerError.php
src/Asana/Errors/ServerError.php
<?php namespace Asana\Errors; use Asana\Errors\RetryableAsanaError; class ServerError extends RetryableAsanaError { const MESSAGE = 'Server Error'; const STATUS = 500; public function __construct($response) { parent::__construct(self::MESSAGE, self::STATUS, $response); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Errors/AsanaError.php
src/Asana/Errors/AsanaError.php
<?php namespace Asana\Errors; use Asana\Errors\ForbiddenError; use Asana\Errors\InvalidRequestError; use Asana\Errors\InvalidTokenError; use Asana\Errors\NoAuthorizationError; use Asana\Errors\NotFoundError; use Asana\Errors\RateLimitEnforcedError; use Asana\Errors\ServerError; class AsanaError extends \Exception { public function __construct($message, $status, $response) { $this->message = $message; $this->status = $status; $this->response = $response; } public static function handleErrorResponse($response) { switch ($response->code) { case ForbiddenError::STATUS: throw new ForbiddenError($response); case InvalidRequestError::STATUS: throw new InvalidRequestError($response); case InvalidTokenError::STATUS: throw new InvalidTokenError($response); case NoAuthorizationError::STATUS: throw new NoAuthorizationError($response); case NotFoundError::STATUS: throw new NotFoundError($response); case PremiumOnlyError::STATUS: throw new PremiumOnlyError($response); case RateLimitEnforcedError::STATUS: throw new RateLimitEnforcedError($response); case ServerError::STATUS: throw new ServerError($response); } } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Errors/RetryableAsanaError.php
src/Asana/Errors/RetryableAsanaError.php
<?php namespace Asana\Errors; use Asana\Errors\AsanaError; class RetryableAsanaError extends AsanaError { }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Errors/PremiumOnlyError.php
src/Asana/Errors/PremiumOnlyError.php
<?php namespace Asana\Errors; use Asana\Errors\AsanaError; class PremiumOnlyError extends AsanaError { const MESSAGE = 'Payment Required'; const STATUS = 402; public function __construct($response) { parent::__construct(self::MESSAGE, self::STATUS, $response); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Errors/ForbiddenError.php
src/Asana/Errors/ForbiddenError.php
<?php namespace Asana\Errors; use Asana\Errors\AsanaError; class ForbiddenError extends AsanaError { const MESSAGE = 'Forbidden'; const STATUS = 403; public function __construct($response) { parent::__construct(self::MESSAGE, self::STATUS, $response); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Errors/NotFoundError.php
src/Asana/Errors/NotFoundError.php
<?php namespace Asana\Errors; use Asana\Errors\AsanaError; class NotFoundError extends AsanaError { const MESSAGE = 'Not Found'; const STATUS = 404; public function __construct($response) { parent::__construct(self::MESSAGE, self::STATUS, $response); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Errors/InvalidRequestError.php
src/Asana/Errors/InvalidRequestError.php
<?php namespace Asana\Errors; use Asana\Errors\AsanaError; class InvalidRequestError extends AsanaError { const MESSAGE = 'Invalid Request'; const STATUS = 400; public function __construct($response) { parent::__construct(self::MESSAGE, self::STATUS, $response); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Errors/InvalidTokenError.php
src/Asana/Errors/InvalidTokenError.php
<?php namespace Asana\Errors; use Asana\Errors\AsanaError; class InvalidTokenError extends AsanaError { const MESSAGE = 'Sync token invalid or too old'; const STATUS = 412; public function __construct($response) { parent::__construct(self::MESSAGE, self::STATUS, $response); $this->sync = $response != null ? $response->body->sync : null; } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/src/Asana/Errors/NoAuthorizationError.php
src/Asana/Errors/NoAuthorizationError.php
<?php namespace Asana\Errors; use Asana\Errors\AsanaError; class NoAuthorizationError extends AsanaError { const MESSAGE = 'No Authorization'; const STATUS = 401; public function __construct($response) { parent::__construct(self::MESSAGE, self::STATUS, $response); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/tests/Bootstrap.php
tests/Bootstrap.php
<?php // Setup autoloading require dirname(__FILE__) . '/../vendor/autoload.php';
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/tests/Asana/ClientTest.php
tests/Asana/ClientTest.php
<?php namespace Asana; use Asana\Test\AsanaTest; use Asana\Errors\Error; use Asana\Errors\ServerError; use PHPUnit\Framework\Error\Warning; class ClientTest extends Test\AsanaTest { var $errors = array(); public function testClientGet() { $this->dispatcher->registerResponse('/users/me', 200, null, '{ "data": "foo" }'); $result = $this->client->users->getUser('me'); $this->assertEquals($result, 'foo'); } public function testNotAuthorized() { $this->expectException(Errors\NoAuthorizationError::class); $this->dispatcher->registerResponse('/users/me', 401, null, '{ "errors": [{ "message": "Not Authorized" }]}'); $this->client->users->getUser('me'); } public function testInvalidRequest() { $this->expectException(Errors\InvalidRequestError::class); $this->dispatcher->registerResponse('/tasks?limit=50', 400, null, '{ "errors": [{ "message": "Missing input" }] }'); $this->client->tasks->getTasks(null, array('iterator_type' => false)); } public function testServerError() { $this->expectException(Errors\ServerError::class); $res = '{ "errors": [ { "message": "Server Error", "phrase": "6 sad squid snuggle softly" } ] }'; $this->dispatcher->registerResponse('/users/me', 500, null, $res); $this->client->users->getUser('me'); } public function testNotFound() { $this->expectException(Errors\NotFoundError::class); $res = '{ "errors": [ { "message": "user: Unknown object: 1234" } ] }'; $this->dispatcher->registerResponse('/users/1234', 404, null, $res); $this->client->users->getUser(1234); } public function testForbidden() { $this->expectException(Errors\ForbiddenError::class); $res = '{ "errors": [ { "message": "user: Forbidden" } ] }'; $this->dispatcher->registerResponse('/users/1234', 403, null, $res); $this->client->users->getUser(1234); } public function testOptionPretty() { $this->dispatcher->registerResponse('/users/me?opt_pretty=true', 200, null, '{ "data": "foo" }'); $this->assertEquals($this->client->users->getUser('me', null, array('pretty' => true)), 'foo'); } public function testOptionFields() { $this->dispatcher->registerResponse('/tasks/1224?opt_fields=name%2Cnotes', 200, null, '{ "data": "foo" }'); $result = $this->client->tasks->getTask(1224, null, array("fields" => array('name','notes'))); $this->assertEquals($result, 'foo'); } public function testOptionExpand() { $req = '{ "data": { "assignee": 1234 }, "options": { "expand" : ["projects"] } }'; $this->dispatcher->registerResponse('/tasks/1001', 200, null, '{ "data": "foo" }'); $result = $this->client->tasks->updateTask(1001, array('assignee' => 1234), array('expand' => array('projects'))); $this->assertEquals($result, 'foo'); $this->assertEquals(json_decode($this->dispatcher->calls[0]['request']->payload), json_decode($req)); } public function testPagination() { $res = '{ "data": [ { "id": 1000, "name": "Task 1" } ], "next_page": { "offset": "ABCDEF", "path": "/tasks?project=1337&limit=5&offset=ABCDEF", "uri": "https://app.asana.com/api/1.0/tasks?project=1337&limit=5&offset=ABCDEF" } }'; $this->dispatcher->registerResponse('/projects/1337/tasks?limit=5&offset=ABCDEF', 200, null, $res); $options = array( 'limit' => 5, 'offset' => 'ABCDEF', 'iterator_type' => false ); $result = $this->client->tasks->getTasksForProject(1337, null, $options); $this->assertEquals($result, json_decode($res)); } public function testItemIteratorItemLimitLessThanItems() { $res = '{ "data": ["a", "b"], "next_page": { "offset": "a", "path": "/projects/1337/tasks?limit=2&offset=a" } }'; $this->dispatcher->registerResponse('/projects/1337/tasks?limit=2', 200, null, $res); $options = array('item_limit' => 2, 'page_size' => 2, 'iterator_type' => 'items'); $iterator = $this->client->tasks->getTasksForProject(1337, null, $options); $iterator->rewind(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'a'); $iterator->next(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'b'); $iterator->next(); $this->assertEquals($iterator->valid(), false); } public function testItemIteratorItemLimitEqualItems() { $res = '{ "data": ["a", "b"], "next_page": { "offset": "a", "path": "/projects/1337/tasks?limit=2&offset=a" } }'; $this->dispatcher->registerResponse('/projects/1337/tasks?limit=2', 200, null, $res); $res = '{ "data": ["c"], "next_page": null }'; $this->dispatcher->registerResponse('/projects/1337/tasks?limit=1&offset=a', 200, null, $res); $options = array('item_limit' => 3, 'page_size' => 2, 'iterator_type' => 'items'); $iterator = $this->client->tasks->getTasksForProject(1337, null, $options); $iterator->rewind(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'a'); $iterator->next(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'b'); $iterator->next(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'c'); $iterator->next(); $this->assertEquals($iterator->valid(), false); } public function testItemIteratorItemLimitGreaterThanItems() { $res = '{ "data": ["a", "b"], "next_page": { "offset": "a", "path": "/projects/1337/tasks?limit=2&offset=a" } }'; $this->dispatcher->registerResponse('/projects/1337/tasks?limit=2', 200, null, $res); $res = '{ "data": ["c"], "next_page": null }'; $this->dispatcher->registerResponse('/projects/1337/tasks?limit=2&offset=a', 200, null, $res); $options = array('item_limit' => 4, 'page_size' => 2, 'iterator_type' => 'items'); $iterator = $this->client->tasks->getTasksForProject(1337, null, $options); $iterator->rewind(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'a'); $iterator->next(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'b'); $iterator->next(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'c'); $iterator->next(); $this->assertEquals($iterator->valid(), false); } public function testItemIteratorPreserveOptFields() { $res = '{ "data": ["a", "b"], "next_page": { "offset": "a", "path": "/projects/1337/tasks?limit=2&offset=a" } }'; $this->dispatcher->registerResponse('/projects/1337/tasks?limit=2&opt_fields=foo', 200, null, $res); $res = '{ "data": ["c"], "next_page": null }'; $this->dispatcher->registerResponse('/projects/1337/tasks?limit=1&offset=a&opt_fields=foo', 200, null, $res); $options = array('fields' => array('foo'), 'item_limit' => 3, 'page_size' => 2, 'iterator_type' => 'items'); $iterator = $this->client->tasks->getTasksForProject(1337, null, $options); $iterator->rewind(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'a'); $iterator->next(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'b'); $iterator->next(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'c'); $iterator->next(); $this->assertEquals($iterator->valid(), false); } public function testRateLimiting() { global $sleepCalls; $res = array( array(429, array('Retry-After' => '0.1' ), '{}'), array(200, null, '{ "data": "me" }') ); $this->dispatcher->registerResponse( '/users/me', function () use (&$res) { return array_shift($res); } ); $result = $this->client->users->getUser('me'); $this->assertEquals($result, 'me'); $this->assertEquals(count($this->dispatcher->calls), 2); $this->assertEquals($sleepCalls, array(0.1)); } public function testRateLimitedTwice() { global $sleepCalls; $res = array( array(429, array('Retry-After' => '0.1' ), '{}'), array(429, array('Retry-After' => '0.1' ), '{}'), array(200, null, '{ "data": "me" }') ); $this->dispatcher->registerResponse( '/users/me', function () use (&$res) { return array_shift($res); } ); $result = $this->client->users->getUser('me'); $this->assertEquals($result, 'me'); $this->assertEquals(count($this->dispatcher->calls), 3); $this->assertEquals($sleepCalls, array(0.1, 0.1)); } public function testServerErrorRetry() { global $sleepCalls; $res = array( array(500, null, '{}'), array(200, null, '{ "data": "me" }') ); $this->dispatcher->registerResponse( '/users/me', function () use (&$res) { return array_shift($res); } ); $result = $this->client->users->getUser('me', null, array('max_retries' => 1)); $this->assertEquals(count($this->dispatcher->calls), 2); $this->assertEquals($sleepCalls, array(1.0)); } public function testServerErrorRetryBackoff() { global $sleepCalls; $res = array( array(500, null, '{}'), array(500, null, '{}'), array(500, null, '{}'), array(200, null, '{ "data": "me" }') ); $this->dispatcher->registerResponse( '/users/me', function () use (&$res) { return array_shift($res); } ); $result = $this->client->users->getUser('me'); $this->assertEquals(count($this->dispatcher->calls), 4); $this->assertEquals($sleepCalls, array(1.0, 2.0, 4.0)); } public function testGetNamedParameters() { $res = '{ "data": "foo" }'; $this->dispatcher->registerResponse('/tasks?limit=50&workspace=14916&assignee=me', 200, null, $res); $options = array('iterator_type' => false); $result = $this->client->tasks->getTasks(array('workspace' => 14916, 'assignee' => 'me'), $options); $this->assertEquals($result, json_decode('{ "data": "foo" }')); } public function testPostNamedParameters() { $req = '{ "data": { "assignee": 1235, "followers": [5678], "name": "Hello, world." } }'; $this->dispatcher->registerResponse('/tasks', 201, null, '{ "data": "foo" }'); $result = $this->client->tasks->createTask( array('assignee' => 1235, 'followers' => array(5678), 'name' => "Hello, world.") ); $this->assertEquals($result, 'foo'); $this->assertEquals(json_decode($this->dispatcher->calls[0]['request']->payload), json_decode($req)); } public function testPutNamedParameters() { $req = '{ "data": { "assignee": 1235, "followers": [5678], "name": "Hello, world." } }'; $this->dispatcher->registerResponse('/tasks/1001', 200, null, '{ "data": "foo" }'); $result = $this->client->tasks->updateTask( 1001, array('assignee' => 1235, 'followers' => array(5678), 'name' => "Hello, world.") ); $this->assertEquals($result, 'foo'); $this->assertEquals(json_decode($this->dispatcher->calls[0]['request']->payload), json_decode($req)); } public function testAsanaChangeHeaderNone() { $this->errors = array(); set_error_handler(array($this,'handleError')); $this->dispatcher->registerResponse('/tasks/1001', 200, null, '{ "data": "foo" }'); $this->client->tasks->updateTask( 1001, array('assignee' => 1235, 'followers' => array(5678), 'name' => "Hello, world.") ); $this->assertEquals(0, count($this->errors)); } public function testAsanaChangeHeaderEnable() { $this->errors = array(); set_error_handler(array($this,'handleError')); $this->dispatcher->registerResponse('/tasks/1001', 200, array('asana-change' => 'name=string_ids;info=something;affected=true'), '{ "data": "foo" }'); $this->client->tasks->updateTask( 1001, array('assignee' => 1235, 'followers' => array(5678), 'name' => "Hello, world."), array('headers' => array('asana-enable' => 'string_ids')) ); $this->assertEquals(0, count($this->errors)); } public function testAsanaChangeHeaderDisable() { $this->errors = array(); set_error_handler(array($this,'handleError')); $this->dispatcher->registerResponse('/tasks/1001', 200, array('asana-change' => 'name=string_ids;info=something;affected=true'), '{ "data": "foo" }'); $this->client->tasks->updateTask( 1001, array('assignee' => 1235, 'followers' => array(5678), 'name' => "Hello, world."), array('headers' => array('asana-disable' => 'string_ids')) ); $this->assertEquals(0, count($this->errors)); } public function testAsanaChangeHeaderSingle() { $this->errors = array(); set_error_handler(array($this,'handleError')); $this->dispatcher->registerResponse('/tasks/1001', 200, array('asana-change' => 'name=string_ids;info=something;affected=true'), '{ "data": "foo" }'); $this->client->tasks->updateTask( 1001, array('assignee' => 1235, 'followers' => array(5678), 'name' => "Hello, world.") ); $this->assertEquals(1, count($this->errors)); } public function testAsanaChangeHeaderMultiple() { $this->errors = array(); set_error_handler(array($this,'handleError')); $this->dispatcher->registerResponse('/tasks/1001', 200, array('asana-change' => 'name=string_ids;info=something;affected=true,name=new_sections;info=something;affected=true'), '{ "data": "foo" }'); $this->client->tasks->updateTask( 1001, array('assignee' => 1235, 'followers' => array(5678), 'name' => "Hello, world.") ); $this->assertEquals(2, count($this->errors)); } public function handleError($n, $m, $f, $l) { array_push($this->errors, array($n, $m, $f, $l)); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/tests/Asana/ResourcesTest.php
tests/Asana/ResourcesTest.php
<?php namespace Asana; use Asana\Test\AsanaTest; class ResourcesTest extends Test\AsanaTest { private static $RESOURCES = array( 'attachments', 'events', 'projects', 'stories', 'tags', 'tasks', 'teams', 'users', 'workspaces', 'webhooks' ); public function testResourcesExist() { foreach (ResourcesTest::$RESOURCES as $name) { $this->assertTrue(!!$result = $this->client->{$name}); } } public function testAttachmentsGetAttachment() { $this->dispatcher->registerResponse('/attachments/1', 200, null, '{ "data": "foo" }'); $result = $this->client->attachments->getAttachment(1); $this->assertEquals($result, 'foo'); } public function testCustomFieldsGetCustomField() { $this->dispatcher->registerResponse('/custom_fields/1', 200, null, '{ "data": "foo" }'); $result = $this->client->customfields->getCustomField(1); $this->assertEquals($result, 'foo'); } public function testProjectsGetProject() { $this->dispatcher->registerResponse('/projects/1', 200, null, '{ "data": "foo" }'); $result = $this->client->projects->getProject(1); $this->assertEquals($result, 'foo'); } public function testStoriesGetStory() { $this->dispatcher->registerResponse('/stories/1', 200, null, '{ "data": "foo" }'); $result = $this->client->stories->getStory(1); $this->assertEquals($result, 'foo'); } public function testTagsGetTag() { $this->dispatcher->registerResponse('/tags/1', 200, null, '{ "data": "foo" }'); $result = $this->client->tags->getTag(1); $this->assertEquals($result, 'foo'); } public function testTasksGetTask() { $this->dispatcher->registerResponse('/tasks/1', 200, null, '{ "data": "foo" }'); $result = $this->client->tasks->getTask(1); $this->assertEquals($result, 'foo'); } public function testTeamsGetTeam() { $this->dispatcher->registerResponse('/teams/1', 200, null, '{ "data": "foo" }'); $result = $this->client->teams->getTeam(1); $this->assertEquals($result, 'foo'); } public function testUsersGetUser() { $this->dispatcher->registerResponse('/users/1', 200, null, '{ "data": "foo" }'); $result = $this->client->users->getUser(1); $this->assertEquals($result, 'foo'); } public function testWorkspacesGetWorkspace() { $this->dispatcher->registerResponse('/workspaces/1', 200, null, '{ "data": "foo" }'); $result = $this->client->workspaces->getWorkspace(1); $this->assertEquals($result, 'foo'); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/tests/Asana/OAuthDispatcherTest.php
tests/Asana/OAuthDispatcherTest.php
<?php namespace Asana; use Asana\Test\AsanaTest; use Asana\Test\MockRequest; use Asana\Dispatcher\OAuthDispatcher; // Extend dispatcher to expose protected methods for testing. class FakeOauthDispatcher extends OAuthDispatcher { public function authenticate($request) { return parent::authenticate($request); } } class OAuthDispatcherTest extends \PHPUnit\Framework\TestCase { protected function setUp(): void { $this->dispatcher = new FakeOAuthDispatcher( array( 'client_id' => 'fake_client_id' ) ); } public function testAuthenticateNoToken() { $this->expectException(\Exception::class); $this->expectExceptionMessage('access token not set'); $request = new MockRequest($this->dispatcher); $this->dispatcher->authenticate($request); } public function testAuthenticateUsesToken() { $this->dispatcher->accessToken = 'fake_token'; $request = new MockRequest($this->dispatcher); $this->dispatcher->authenticate($request); $this->assertEquals( $request->headers, array('Authorization' => 'Bearer fake_token') ); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/tests/Asana/Resources/AttachmentsTest.php
tests/Asana/Resources/AttachmentsTest.php
<?php namespace Asana; use Asana\Test\AsanaTest; class AttachmentsTest extends Test\AsanaTest { public function testAttachmentsCreateOnTask() { $res = '{ "data": { "id": 5678, "name": "file.txt" } }'; $this->dispatcher->registerResponse('/tasks/1337/attachments', 200, null, $res); $result = $this->client->attachments->createOnTask(1337, 'file contents', 'file name', 'file content-type'); $this->assertEquals($result, json_decode($res)->data); $fileDescription = $this->dispatcher->calls[0]['request']->payload['file']; $this->assertEquals('multipart/form-data', $this->dispatcher->calls[0]['request']->content_type); // If the user's PHP version supports curl_file_create, use it. if (function_exists('curl_file_create')) { $this->assertInstanceOf('CURLFile', $fileDescription); $this->assertEquals('file name', $fileDescription->getPostFilename()); $this->assertEquals('file content-type', $fileDescription->getMimeType()); } else { $this->assertStringMatchesFormat('%Sfilename=file name%S', $fileDescription); $this->assertStringMatchesFormat('%Stype=file content-type%S', $fileDescription); } } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/tests/Asana/Resources/EventsTest.php
tests/Asana/Resources/EventsTest.php
<?php namespace Asana; use Asana\Errors; use Asana\Test\AsanaTest; class EventsTest extends Test\AsanaTest { public function testEventsGet() { $res = '{ "data": ["a", "b"], "sync": "b" }'; $this->dispatcher->registerResponse('/events?resource=14321&sync=a', 200, null, $res); $result = $this->client->events->get(array('resource' => 14321, 'sync' => 'a' )); $this->assertEquals($result, json_decode($res)); } public function testEventsGetInvalidToken() { $this->expectException(Errors\InvalidTokenError::class); $res = '{ "message": "Sync token invalid or too old", "sync": "b" }'; $this->dispatcher->registerResponse('/events?resource=14321&sync=a', 412, null, $res); $this->client->events->get(array('resource' => 14321, 'sync' => 'a' )); } public function testEventsGetNext() { $res = '{ "sync": "1" }'; $this->dispatcher->registerResponse('/events?limit=50&resource=1', 412, null, $res); $res = '{ "data": [], "sync": "2" }'; $this->dispatcher->registerResponse('/events?limit=50&sync=1&resource=1', 200, null, $res); $res = '{ "data": [{}, {}], "sync": "3" }'; $this->dispatcher->registerResponse('/events?limit=50&sync=2&resource=1', 200, null, $res); $this->assertEquals(count($this->client->events->getNext(array('resource' => '1'))), 2); } public function testEventsGetNextUnknownObject() { $this->expectException(Errors\InvalidRequestError::class); $this->dispatcher->registerResponse('/events?limit=50&resource=1', 400, null, '{ "sync": "1" }'); $this->client->events->getNext(array('resource' => '1')); } public function testEventsGetNextInvalidToken() { $this->expectException(Errors\InvalidTokenError::class); $this->dispatcher->registerResponse('/events?limit=50&sync=invalid&resource=1', 412, null, '{ "sync": "1" }'); $this->client->events->getNext(array('resource' => '1', 'sync' => 'invalid')); } public function testEventsGetIterator() { $res = '{ "sync": "1" }'; $this->dispatcher->registerResponse('/events?limit=50&resource=1', 412, null, $res); $res = '{ "data": [], "sync": "2" }'; $this->dispatcher->registerResponse('/events?limit=50&sync=1&resource=1', 200, null, $res); $res = '{ "data": ["a", "b"], "sync": "3" }'; $this->dispatcher->registerResponse('/events?limit=50&sync=2&resource=1', 200, null, $res); $res = '{ "data": ["c"], "sync": "4" }'; $this->dispatcher->registerResponse('/events?limit=50&sync=3&resource=1', 200, null, $res); $iterator = $this->client->events->getIterator(array('resource' => '1')); $iterator->rewind(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'a'); $iterator->next(); $this->assertEquals($iterator->valid(), true); $this->assertEquals($iterator->current(), 'b'); // FIXME: ItemIterator currently fetches one page ahead // $iterator->next(); // $this->assertEquals($iterator->valid(), true); // $this->assertEquals($iterator->current(), 'c'); } public function testEventsGetIteratorUnknownObject() { $this->expectException(Errors\InvalidRequestError::class); $this->dispatcher->registerResponse('/events?limit=50&resource=1', 400, null, '{ "sync": "1" }'); $this->client->events->getIterator(array('resource' => '1'))->rewind(); } public function testEventsGetIteratorInvalidToken() { $this->expectException(Errors\InvalidTokenError::class); $this->dispatcher->registerResponse('/events?limit=50&sync=invalid&resource=1', 412, null, '{ "sync": "1" }'); $this->client->events->getIterator(array('resource' => '1', 'sync' => 'invalid'))->rewind(); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/tests/Asana/Resources/WebhooksTest.php
tests/Asana/Resources/WebhooksTest.php
<?php namespace Asana; use Asana\Test\AsanaTest; class WebhooksTest extends Test\AsanaTest { private $data = array( 'id' => 222, 'resource' => array( 'id' => 111, 'name' => 'the resource' ), 'target' => 'https://foo/123', 'active' => true ); private function verifyWebhookData($webhook) { $this->assertEquals($webhook->id, $this->data['id']); $this->assertEquals((array)$webhook->resource, $this->data['resource']); $this->assertEquals($webhook->target, $this->data['target']); $this->assertEquals($webhook->active, $this->data['active']); } public function testWebhooksCreateWebhook() { $this->dispatcher->registerResponse('/webhooks', 200, null, '{ "data": ' . json_encode($this->data) . ' }'); $result = $this->client->webhooks->createWebhook(array('resource' => 111, 'target' => 'https://foo/123')); $this->verifyWebhookData($result); } public function testWebhooksGetAll() { $res = '{ "data": [' . json_encode($this->data) . '] }'; $this->dispatcher->registerResponse('/webhooks?limit=50&workspace=1337', 200, null, $res); $result = $this->client->webhooks->getAll(array("workspace" => 1337)); foreach ($result as $res) { $this->verifyWebhookData($res); } } public function testWebhooksGetById() { $this->dispatcher->registerResponse('/webhooks/222', 200, null, '{ "data": ' . json_encode($this->data) . ' }'); $result = $this->client->webhooks->getById(222); $this->verifyWebhookData($result, $this->data); } public function testWebhooksDeleteById() { $this->dispatcher->registerResponse('/webhooks/222', 200, null, '{ "data": {} }'); $result = $this->client->webhooks->deleteById(222); $this->assertEmpty((array)$result); } }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/examples/example-create-project-and-stream-events.php
examples/example-create-project-and-stream-events.php
<?php require dirname(__FILE__) . '/../vendor/autoload.php'; use Asana\Client; $ASANA_ACCESS_TOKEN = getenv('ASANA_ACCESS_TOKEN'); // Access Token Instructions: // 1. set your ASANA_ACCESS_TOKEN environment variable to a Personal Access Token found in Asana Account Settings if ($ASANA_ACCESS_TOKEN === false) { echo "Please set the ASANA_ACCESS_TOKEN environment variable.\n"; exit; } // create a $client->with a Personal Access Token $client = Asana\Client::accessToken($ASANA_ACCESS_TOKEN); $me = $client->users->getUser('me'); echo "me="; var_dump($client->users->getUser('me')); // find your "Personal Projects" project $personalProjectsArray = array_filter($me->workspaces, function($item) { return $item->name === 'Personal Projects'; }); $personalProjects = array_pop($personalProjectsArray); var_dump($personalProjects); $projects = $client->projects->getProjectsForWorkspace($personalProjects->id, null, array('iterator_type' => false, 'page_size' => null))->data; echo "personal projects="; var_dump($projects); // create a "demo project" if it doesn't exist $projectArray = array_filter($projects, function($project) { return $project->name === 'demo project'; }); $project = array_pop($projectArray); if ($project === null) { echo "creating 'demo project'\n"; $project = $client->projects->createInWorkspace($personalProjects->id, array('name' => 'demo project')); } echo "project="; var_dump($project); // start streaming modifications to the demo project. // make some changes in Asana to see this working echo "starting streaming events for " . $project->name . "\n"; $eventsIterator = $client->events->getIterator(array('resource' => $project->id)); foreach ($eventsIterator as $event) { var_dump($event); }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/examples/example-accesstoken.php
examples/example-accesstoken.php
<?php require dirname(__FILE__) . '/../vendor/autoload.php'; use Asana\Client; $ASANA_ACCESS_TOKEN = getenv('ASANA_ACCESS_TOKEN'); // Access Token Instructions: // 1. set your ASANA_ACCESS_TOKEN environment variable to a Personal Access Token found in Asana Account Settings if ($ASANA_ACCESS_TOKEN === false) { echo "Please set the ASANA_ACCESS_TOKEN environment variable.\n"; exit; } echo "== Example using Personal Access Token:\n"; // create a $client->with a Personal Access Token $client = Asana\Client::accessToken($ASANA_ACCESS_TOKEN); $me = $client->users->getUser('me'); echo "me="; var_dump($client->users->getUser('me'));
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/examples/example-server.php
examples/example-server.php
<?php require dirname(__FILE__) . '/../vendor/autoload.php'; use Asana\Client; function client($token=null) { return Asana\Client::oauth(array( 'client_id' => getenv('ASANA_CLIENT_ID'), 'client_secret' => getenv('ASANA_CLIENT_SECRET'), 'redirect_uri' => 'http://localhost:5000/auth/asana/callback', 'token' => $token )); } session_start(); try { if ('/' == $_SERVER['SCRIPT_NAME']) { if (isset($_SESSION['token'])) { $me = client($_SESSION['token'])->users->getUser('me'); echo '<p>Hello ' . $me->name . '</p><p><a href="/logout">Logout</a></p>'; } else { $state = null; $url = client()->dispatcher->authorizationUrl($state); $_SESSION['state'] = $state; echo '<p><a href="' . $url . '">'; echo '<img src="https://github.com/Asana/oauth-examples/raw/master/public/asana-oauth-button-blue.png?raw=true">'; echo '</a></p>'; } } else if ('/logout' == $_SERVER['SCRIPT_NAME']) { unset($_SESSION['token']); header('Location: /'); } else if ('/auth/asana/callback' == $_SERVER['SCRIPT_NAME']) { if ($_SESSION['state'] == $_GET['state']) { $_SESSION['token'] = client()->dispatcher->fetchToken($_GET['code']); header('Location: /'); } else { echo "State doesn't match"; } } else { http_response_code(404); echo 'Not found'; } } catch (Exception $e) { http_response_code(500); echo "Internal Error\n" . $e; }
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/examples/example-create-task-and-upload.php
examples/example-create-task-and-upload.php
<?php require dirname(__FILE__) . '/../vendor/autoload.php'; use Asana\Client; $ASANA_ACCESS_TOKEN = getenv('ASANA_ACCESS_TOKEN'); // Access Token Instructions: // 1. set your ASANA_ACCESS_TOKEN environment variable to a Personal Access Token found in Asana Account Settings if ($ASANA_ACCESS_TOKEN === false) { echo "Please set the ASANA_ACCESS_TOKEN environment variable.\n"; exit; } // create a $client->with a Personal Access Token $client = Asana\Client::accessToken($ASANA_ACCESS_TOKEN); $me = $client->users->getUser('me'); echo "me="; var_dump($client->users->getUser('me')); // find your "Personal Projects" workspace $personalProjectsArray = array_filter($me->workspaces, function($item) { return $item->name === 'Personal Projects'; }); $personalProjects = array_pop($personalProjectsArray); var_dump($personalProjects); $projects = $client->projects->getProjectsForWorkspace($personalProjects->gid, null, array('iterator_type' => false, 'page_size' => null))->data; echo "personal projects="; var_dump($projects); // create a "demo project" if it doesn't exist $projectArray = array_filter($projects, function($project) { return $project->name === 'demo project'; }); $project = array_pop($projectArray); if ($project === null) { echo "creating 'demo project'\n"; $project = $client->projects->createInWorkspace($personalProjects->gid, array('name' => 'demo project')); } echo "project="; var_dump($project); // create a task in the project $demoTask = $client->tasks->createInWorkspace($personalProjects->gid, array( "name" => "demo task created at " . date('m/d/Y h:i:s a'), "projects" => array($project->gid) )); echo "Task " . $demoTask->gid . " created.\n"; // add an attachment to the task $demoAttachment = $client->attachments->createOnTask( $demoTask->gid, "hello world", "upload.txt", "text/plain" ); echo "Attachment " . $demoAttachment->gid . " created.\n";
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
Asana/php-asana
https://github.com/Asana/php-asana/blob/88868108be00da49fbf0c101d0c078edebc0bf3f/examples/example-oauth.php
examples/example-oauth.php
<?php require dirname(__FILE__) . '/../vendor/autoload.php'; $ASANA_CLIENT_ID = getenv('ASANA_CLIENT_ID'); $ASANA_CLIENT_SECRET = getenv('ASANA_CLIENT_SECRET'); // OAuth Instructions: // 1. create a new application in your Asana Account Settings ("App" panel) // 2. set the redirect URL to "urn:ietf:wg:oauth:2.0:oob" // 3. set your ASANA_CLIENT_ID and ASANA_CLIENT_SECRET environment variables if ($ASANA_CLIENT_ID === false || $ASANA_CLIENT_SECRET === false) { echo "Please set the ASANA_CLIENT_ID and ASANA_CLIENT_SECRET environment variables.\n"; exit; } echo "== Example using OAuth Client ID and Client Secret:\n"; // create a $client->with the OAuth credentials: $client = Asana\Client::oauth(array( 'client_id' => getenv('ASANA_CLIENT_ID'), 'client_secret' => getenv('ASANA_CLIENT_SECRET'), // this special redirect URI will prompt the user to copy/paste the code. // useful for command line scripts and other non-web apps 'redirect_uri' => Asana\Dispatcher\OAuthDispatcher::NATIVE_REDIRECT_URI )); echo "authorized=" . $client->dispatcher->authorized . "\n"; # get an authorization URL: $state = null; $url = $client->dispatcher->authorizationUrl($state); try { // in a web app you'd redirect the user to this URL when they take action to // login with Asana or connect their account to Asana exec("open " . escapeshellarg($url)); } catch (Exception $e) { echo "Open the following URL in a browser to authorize:\n"; echo "$url\n"; } echo "Copy and paste the returned code from the browser and press enter:\n"; $code = trim(fgets(fopen("php://stdin", "r"))); // exchange the code for a bearer token $token = $client->dispatcher->fetchToken($code); if ($client->dispatcher->authorized) { echo "Authorization successful\n"; } else { echo "Authorization failed, exiting..."; exit(1); } echo "Hello " . $client->users->getUser('me')->name . "\n"; echo "Your access token is: " . json_encode($token) . "\n"; echo "Exchanging your refresh token for a new access token because access tokens expire\n"; // access tokens will expire, use a refresh token to get a fresh access token $token = $client->dispatcher->refreshAccessToken(); echo "Your new access token is: " . json_encode($token) . "\n"; echo "You are a member of the following workspaces:\n"; $workspaces = $client->workspaces->getWorkspaces(); foreach ($workspaces as $workspace) { echo $workspace->name . "\n"; } // normally you'd persist this token somewhere $token = json_encode($token); // (see below) // demonstrate creating a client using a previously obtained bearer token echo "== Example using OAuth Access Token:\n"; $client = Asana\Client::oauth(array( 'client_id' => $ASANA_CLIENT_ID, 'token' => json_decode($token) )); echo "Your registered email address is: " . $client->users->getUser('me')->email;
php
MIT
88868108be00da49fbf0c101d0c078edebc0bf3f
2026-01-05T04:58:34.842652Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/rector.php
rector.php
<?php declare(strict_types=1); use Rector\CodeQuality\Rector\FunctionLike\SimplifyUselessVariableRector; use Rector\Config\RectorConfig; use Rector\Php74\Rector\Closure\ClosureToArrowFunctionRector; use Rector\Php81\Rector\Array_\FirstClassCallableRector; use Rector\Php81\Rector\FuncCall\NullToStrictStringFuncCallArgRector; use Rector\Php81\Rector\Property\ReadOnlyPropertyRector; use Rector\Set\ValueObject\LevelSetList; use Rector\Set\ValueObject\SetList; use Rector\Strict\Rector\BooleanNot\BooleanInBooleanNotRuleFixerRector; use Rector\Strict\Rector\If_\BooleanInIfConditionRuleFixerRector; use Rector\TypeDeclaration\Rector\ClassMethod\ReturnNeverTypeRector; return static function (RectorConfig $rectorConfig): void { $rectorConfig->paths([ __DIR__.'/src', ]); $rectorConfig->sets([ LevelSetList::UP_TO_PHP_81, SetList::EARLY_RETURN, SetList::TYPE_DECLARATION, ]); $rectorConfig->skip([ ReadOnlyPropertyRector::class, ClosureToArrowFunctionRector::class, FirstClassCallableRector::class, NullToStrictStringFuncCallArgRector::class, BooleanInIfConditionRuleFixerRector::class, BooleanInBooleanNotRuleFixerRector::class, SimplifyUselessVariableRector::class, ReturnNeverTypeRector::class, ]); };
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/src/Autoload.php
src/Autoload.php
<?php declare(strict_types=1); namespace Spatie\RouteTesting; use Pest\Plugin; Plugin::uses(RouteTestable::class); if (! function_exists('routeTesting')) { function routeTesting(string $description) { return new RouteTestingTestCall(test($description)); } }
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/src/RouteResolver.php
src/RouteResolver.php
<?php namespace Spatie\RouteTesting; use Exception; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Process; use Illuminate\Support\Str; use Symfony\Component\Process\Process as SymfonyProcess; class RouteResolver { /** @var array<int, string>|null */ protected ?array $paths = null; /** @var array<int, string>|null */ protected ?array $exceptPaths = null; /** @var array<int, string> */ protected array $methods = ['GET']; protected bool $exceptRoutesWithMissingBindings = false; /** @var array<int, string> */ protected array $bindingNames = []; /** @var Collection<int, array{method: string, uri: string}> */ protected Collection $fullRouteList; public function __construct() { $this->fullRouteList = $this->resolveFullRouteList(); } /** @return Collection<int, array{method: string, uri: string}> */ protected function resolveFullRouteList(): Collection { $command = 'php artisan route:list --json --method=GET'; try { $result = Process::run($command); $output = $result->output(); } catch (Exception) { $process = SymfonyProcess::fromShellCommandline($command); $process->run(); $output = $process->getOutput(); } $routes = json_decode($output, true); return collect($routes)->flatMap( fn (array $route) => Str::of($route['method']) ->explode('|') ->intersect($this->methods) ->map(fn ($method) => ['method' => $method, 'uri' => $route['uri']]) ); } public function paths(array $paths): self { $this->paths = array_merge($this->paths ?? [], $paths); return $this; } public function exceptPaths(array $paths): self { $this->exceptPaths = array_merge($this->exceptPaths ?? [], $paths); return $this; } public function bindingNames(array $bindingNames): self { $this->bindingNames = $bindingNames; return $this; } public function exceptRoutesWithMissingBindings(): self { $this->exceptRoutesWithMissingBindings = true; return $this; } /** * @return array<int, array<int, string>> */ public function getFilteredRouteList(): array { return $this->fullRouteList ->filter(function (array $route) { if ($this->paths) { return collect($this->paths)->contains(fn ($path) => Str::is($path, $route['uri'])); } return true; }) ->filter(function (array $route) { if ($this->exceptPaths) { return ! collect($this->exceptPaths)->contains(fn ($path) => Str::is($path, $route['uri'])); } return true; }) ->when($this->exceptRoutesWithMissingBindings, function (Collection $routes) { return $routes->filter(function (array $route) { $uriBindings = $this->getBindingsFromUrl($route['uri']); if (count($uriBindings) === 0) { return true; } return count(array_diff($uriBindings, $this->bindingNames)) === 0; }); }) ->map(fn (array $route) => array_values($route)) ->toArray(); } protected function getBindingsFromUrl(string $uri): array { $pattern = '/{([^}]*)}/'; preg_match_all($pattern, $uri, $matches); return $matches[1]; } }
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/src/RouteTest.php
src/RouteTest.php
<?php namespace Spatie\RouteTesting; use Closure; use Illuminate\Routing\Exceptions\UrlGenerationException; use Illuminate\Routing\Route; use Illuminate\Support\Facades\Route as RouteFacade; use Illuminate\Testing\TestResponse; use Pest\PendingCalls\BeforeEachCall; use Pest\PendingCalls\TestCall; use Pest\Support\Backtrace; use Pest\TestSuite; class RouteTest { public static function bind(string $binding, Closure $closure): void { new BeforeEachCall( TestSuite::getInstance(), Backtrace::testFile(), fn () => $this->parameters[$binding] = $closure() ); } public static function test(TestCall $test, array $assertions): void { /** @var TestResponse $testResponse */ $testResponse = $test ->defer(function (string $method, string $uri) { /** @var Route $route */ $route = collect(RouteFacade::getRoutes() ->getRoutesByMethod()[$method]) ->first(fn (Route $route) => $route->uri === $uri); if ($route === null) { $this->markTestIncomplete("Route not found: {$method} {$uri}"); } try { $this->url = url()->toRoute($route, $this->parameters ?? null, false); } catch (UrlGenerationException) { $this->markTestSkipped("Missing parameters for route: {$method} {$uri}"); } }) ->expect(fn (string $method, string $uri) => $this->{$method}($this->url)); foreach ($assertions as [$method, $parameters]) { $testResponse->{$method}(...$parameters); } } }
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/src/RouteTestable.php
src/RouteTestable.php
<?php declare(strict_types=1); namespace Spatie\RouteTesting; /** * @internal */ trait RouteTestable { public function bind(string $binding, mixed $value): self { $this->parameters[$binding] = $value; return $this; } }
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/src/RouteTestingTestCall.php
src/RouteTestingTestCall.php
<?php namespace Spatie\RouteTesting; use Closure; use Illuminate\Support\Arr; use Illuminate\Support\Traits\ForwardsCalls; use Illuminate\Testing\TestResponse; use Pest\PendingCalls\TestCall; /** @mixin TestResponse|TestCall */ class RouteTestingTestCall { use ForwardsCalls; protected TestCall $testCall; protected RouteResolver $routeResolver; /** @var array<int, string> */ protected array $bindingNames = []; /** @var array<array{0: string, 1: string}> */ protected array $assertions = []; public function __construct(TestCall $testCall) { $this->testCall = $testCall; $this->routeResolver = new RouteResolver; $this->with($this->routeResolver->getFilteredRouteList()); $this->exclude([ '_ignition', '_debugbar*', 'horizon*', 'pulse*', 'sanctum*', ]); } protected function with(array $routes): self { $this->testCall->testCaseMethod->datasets = [$routes]; return $this; } public function ignoreRoutesWithMissingBindings(): self { $this->routeResolver->exceptRoutesWithMissingBindings(); $this->with($this->routeResolver->getFilteredRouteList()); return $this; } public function setUp(Closure $closure): static { $this->testCall->defer($closure); return $this; } /** * There is some weird Pest magic going on here... We can't create closures in this class. * Instead, just pass the arguments to a different class where we can create closures. * It's 3 AM and this took me like 3 days to figure out and I just want to sleep. */ public function bind(string $binding, Closure $closure): self { RouteTest::bind($binding, $closure); $this->bindingNames = array_merge($this->bindingNames, [$binding]); $this->routeResolver->bindingNames($this->bindingNames); $this->with($this->routeResolver->getFilteredRouteList()); return $this; } /** * @param array|string[] $path * @return $this */ public function include(array|string ...$path): self { $this->routeResolver->paths(Arr::wrap($path)); $this->with($this->routeResolver->getFilteredRouteList()); return $this; } /** * @param string[]|array $path * @return $this */ public function exclude(string|array ...$path): self { $this->routeResolver->exceptPaths(Arr::wrap($path)); $this->with($this->routeResolver->getFilteredRouteList()); return $this; } public function __call($method, $parameters): self { // Assertions cannot be chained on the test call yet until the user is done adding bindings and other Pest test methods. // We'll capture assertions and apply them to the TestResponse later (in the __destruct method). if (in_array($method, get_class_methods(TestResponse::class)) || $method === 'toMatchSnapshot' || TestResponse::hasMacro($method)) { $this->assertions[] = [$method, $parameters]; return $this; } // Make sure Pest's methods (skip, group, etc...) are still callable. $this->forwardCallTo($this->testCall, $method, $parameters); return $this; } public function __destruct() { RouteTest::test($this->testCall, $this->assertions); } }
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/tests/RouteTestingTestCallTest.php
tests/RouteTestingTestCallTest.php
<?php use Pest\PendingCalls\TestCall; use Pest\TestSuite; use Spatie\RouteTesting\RouteTestingTestCall; it('can use any assertion', function (string $assertion, array $expectedAssertions) { $routeTestingTestCall = createRouteTestingTestCall(); $routeTestingTestCall->$assertion(); expect($routeTestingTestCall)->toHaveProtectedProperty('assertions', $expectedAssertions); })->with([ 'assertion' => ['assertSuccessful', [['assertSuccessful', []]]], 'snapshot testing' => ['toMatchSnapshot', [['toMatchSnapshot', []]]], 'pest\'s method' => ['skip', []], ]); function createRouteTestingTestCall(): RouteTestingTestCall { $testSuite = new TestSuite('', ''); $testCall = new TestCall($testSuite, ''); return new RouteTestingTestCall($testCall); }
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/tests/Pest.php
tests/Pest.php
<?php use Pest\Matchers\Any; use PHPUnit\Framework\Assert; use Tests\TestCase; uses(TestCase::class)->in(__DIR__); expect()->extend('toContainRoutes', function (array $expectedRoutes) { $routesNames = collect($this->value)->map(fn ($route) => $route[1])->values()->toArray(); Assert::assertEqualsCanonicalizing($expectedRoutes, $routesNames); }); expect()->extend('toHaveProtectedProperty', function (string $name, mixed $value = new Any, string $message = '') { $this->toBeObject(); Assert::assertTrue(property_exists($this->value, $name), $message); $reflection = new ReflectionClass($this->value); $property = $reflection->getProperty($name); $property->setAccessible(true); Assert::assertTrue($property->isProtected(), $message); if (! $value instanceof Any) { Assert::assertEquals($value, $property->getValue($this->value), $message); } return $this; });
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/tests/TestCase.php
tests/TestCase.php
<?php namespace Tests; use Orchestra\Testbench\TestCase as BaseTestCase; class TestCase extends BaseTestCase {}
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/tests/RouteResolverTest.php
tests/RouteResolverTest.php
<?php use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Process; use Illuminate\Support\Facades\Route; use Spatie\RouteTesting\RouteResolver; it('can get a routes', function () { setUpRoutes([ 'one', 'two', 'three', ]); $routes = (new RouteResolver)->getFilteredRouteList(); expect($routes)->toContainRoutes([ 'one', 'two', 'three', ]); }); it('can can only get specific paths', function () { setUpRoutes([ 'one', 'one-another', 'two', 'three', ]); $routes = (new RouteResolver) ->paths(['one', 'two']) ->getFilteredRouteList(); expect($routes)->toContainRoutes([ 'one', 'two', ]); }); it('can use a wildcard to get specific paths', function () { setUpRoutes([ 'one', 'one-another', 'three', ]); $routes = (new RouteResolver) ->paths(['one*']) ->getFilteredRouteList(); expect($routes)->toContainRoutes([ 'one', 'one-another', ]); }); it('can exclude paths', function () { setUpRoutes([ 'one', 'two', 'three', ]); $routes = (new RouteResolver) ->exceptPaths(['two']) ->getFilteredRouteList(); expect($routes)->toContainRoutes([ 'one', 'three', ]); }); it('can exclude paths using a wildcard', function () { setUpRoutes([ 'one', 'one-another', 'two', 'three', ]); $routes = (new RouteResolver) ->exceptPaths(['one*']) ->getFilteredRouteList(); expect($routes)->toContainRoutes([ 'two', 'three', ]); }); it('by default it will also return routes with missing bindings', function () { setUpRoutes([ 'home', 'user/{user}', ]); $routes = (new RouteResolver)->getFilteredRouteList(); expect($routes)->toContainRoutes([ 'home', 'user/{user}', ]); }); it('can ignore routes with missing bindings', function () { setUpRoutes([ 'home', 'user/{user}', ]); $routes = (new RouteResolver) ->exceptRoutesWithMissingBindings() ->getFilteredRouteList(); expect($routes)->toContainRoutes([ 'home', ]); }); it('will not ignore routes whose bindings are not missing', function () { setUpRoutes([ 'home', 'user/{user}', ]); $routes = (new RouteResolver) ->exceptRoutesWithMissingBindings() ->bindingNames(['user']) ->getFilteredRouteList(); expect($routes)->toContainRoutes([ 'home', 'user/{user}', ]); }); function setUpRoutes(array $urls) { foreach ($urls as $url) { Route::get($url, function () use ($url) { return "Hello {$url}"; }); } $command = 'route:list --json --method=GET'; Artisan::call($command); $output = Artisan::output(); Process::fake([ "php artisan {$command}" => Process::result(output: $output), ]); }
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
spatie/pest-plugin-route-testing
https://github.com/spatie/pest-plugin-route-testing/blob/aafb6ca72216d7f00589cb7ae5cdc167de4402bc/tests/ArchTest.php
tests/ArchTest.php
<?php arch('it will not use debugging functions') ->expect(['dd', 'dump', 'ray']) ->each->not->toBeUsed();
php
MIT
aafb6ca72216d7f00589cb7ae5cdc167de4402bc
2026-01-05T04:58:46.751633Z
false
davidearl/webauthn
https://github.com/davidearl/webauthn/blob/91d2011226193eadd383ff407b41d7e8261d43f4/tests/units/WebAuthn.php
tests/units/WebAuthn.php
<?php namespace test\units\Davidearl\WebAuthn; use atoum; class WebAuthn extends atoum { public function testPublicKeyOptions() { $this ->given($this->newTestedInstance('app.com')) ->then ->string($this->testedInstance->prepareChallengeForRegistration('test', 123)) ->isNotEmpty(); } }
php
MIT
91d2011226193eadd383ff407b41d7e8261d43f4
2026-01-05T04:58:53.807707Z
false
davidearl/webauthn
https://github.com/davidearl/webauthn/blob/91d2011226193eadd383ff407b41d7e8261d43f4/example/index.php
example/index.php
<?php /* If you put the whole webauthn directory in the www document root and put an index.php in there which just includes this file, it should then work. Alternatively set it as a link to this file. */ require_once(dirname(__DIR__).'/vendor/autoload.php'); /* In this example, the user database is simply a directory of json files named by their username (urlencoded so there are no weird characters in the file names). For simplicity, it's in the HTML tree so someone could look at it - you really, really don't want to do this for a live system */ define('USER_DATABASE', dirname(dirname(__DIR__)).'/.users'); if (! file_exists(USER_DATABASE)) { if (! @mkdir(USER_DATABASE)) { error_log(sprintf('Cannot create user database directory - is the html directory writable by the web server? If not: "mkdir %s; chmod 777 %s"', USER_DATABASE, USER_DATABASE)); die(sprintf("cannot create %s - see error log", USER_DATABASE)); } } session_start(); function oops($s){ http_response_code(400); echo "{$s}\n"; exit; } function userpath($username){ $username = str_replace('.', '%2E', $username); return sprintf('%s/%s.json', USER_DATABASE, urlencode($username)); } function getuser($username){ $user = @file_get_contents(userpath($username)); if (empty($user)) { oops('user not found'); } $user = json_decode($user); if (empty($user)) { oops('user not json decoded'); } return $user; } function saveuser($user){ file_put_contents(userpath($user->name), json_encode($user)); } /* A post is an ajax request, otherwise display the page */ if (! empty($_POST)) { try { $webauthn = new \Davidearl\WebAuthn\WebAuthn($_SERVER['HTTP_HOST']); switch(TRUE){ case isset($_POST['registerusername']): /* initiate the registration */ $username = $_POST['registerusername']; $crossplatform = ! empty($_POST['crossplatform']) && $_POST['crossplatform'] == 'Yes'; $userid = md5(time() . '-'. rand(1,1000000000)); if (file_exists(userpath($username))) { oops("user '{$username}' already exists"); } /* Create a new user in the database. In principle, you can store more than one key in the user's webauthnkeys, but you'd probably do that from a user profile page rather than initial registration. The procedure is the same, just don't cancel existing keys like this.*/ $user = (object)['name'=> $username, 'id'=> $userid, 'webauthnkeys' => $webauthn->cancel()]; saveuser($user); $_SESSION['username'] = $username; $j = ['challenge' => $webauthn->prepareChallengeForRegistration($username, $userid, $crossplatform)]; break; case isset($_POST['register']): /* complete the registration */ if (empty($_SESSION['username'])) { oops('username not set'); } $user = getuser($_SESSION['username']); /* The heart of the matter */ $user->webauthnkeys = $webauthn->register($_POST['register'], $user->webauthnkeys); /* Save the result to enable a challenge to be raised agains this newly created key in order to log in */ saveuser($user); $j = 'ok'; break; case isset($_POST['loginusername']): /* initiate the login */ $username = $_POST['loginusername']; $user = getuser($username); $_SESSION['loginname'] = $user->name; /* note: that will emit an error if username does not exist. That's not good practice for a live system, as you don't want to have a way for people to interrogate your user database for existence */ $j['challenge'] = $webauthn->prepareForLogin($user->webauthnkeys); /* Save user again, which sets server state to include the challenge expected */ saveuser($user); break; case isset($_POST['login']): /* authenticate the login */ if (empty($_SESSION['loginname'])) { oops('username not set'); } $user = getuser($_SESSION['loginname']); if (! $webauthn->authenticate($_POST['login'], $user->webauthnkeys)) { http_response_code(401); echo 'failed to authenticate with that key'; exit; } /* Save user again, which sets server state to include the challenge expected */ saveuser($user); $j = 'ok'; break; default: http_response_code(400); echo "unrecognized POST\n"; break; } } catch(Exception $ex) { oops($ex->getMessage()); } header('Content-type: application/json'); echo json_encode($j); exit; } ?><!doctype html> <html> <head> <title>webauthn php server side example and test</title> <style> body { font-family: Verdana, sans-serif; } h1 { font-size: 1.5em; } h2 { font-size: 1.2em; } .ccontent { display: flex; flex-wrap: wrap; margin: 10px; } .cbox { width: 100%; max-width: 480px; min-height: 150px; border: 1px solid black; padding: 10px; margin: 10px; line-height: 2; } .cdokey { display: none; background-color: orange; color: white; font-weight: bold; margin: 10px 0; padding: 10px; } .cerror { display: none; background-color: tomato; color: white; padding: 10px; font-weight: bold; } .cdone { display: none; background-color: darkgreen; color: white; padding: 10px; font-weight: bold; } .chint { max-width: 450px; margin-left: 2em; } </style> </head> <body> <h1>webauthn php server side example and test</h1> <ul> <li><a href='https://github.com/davidearl/webauthn'>GitHub</a> </ul> <div class='cerror'></div> <div class='cdone'></div> <div class='ccontent'> <div class='cbox' id='iregister'> <h2>User Registration</h2> <form id='iregisterform' action='/' method='POST'> <label> enter a new username (eg email address): <input type='text' name='registerusername'></label><br> cross-platform?<sup>*</sup> <select name='cp'> <option value=''>(choose one)</option> <option>No</option> <option>Yes</option> </select><br> <input type='submit' value='Submit'><br> </form> <div class='cdokey' id='iregisterdokey'> Do your thing: press button on key, swipe fingerprint or whatever </div> </div> <div class='cbox' id='ilogin'> <h2>User Login</h2> <form id='iloginform' action='/' method='POST'> <label> enter existing username: <input type='text' name='loginusername'></label><br> <input type='submit' value='Submit'> </form> <div class='cdokey' id='ilogindokey'> Do your thing: press button on key, swipe fingerprint or whatever </div> </div> </div> <p class='chint'>* Use cross-platform 'Yes' when you have a removable device, like a Yubico key, which you would want to use to login on different computers; say 'No' when your device is attached to the computer (in that case in Windows 10 1903 release, your login is linked to Windows Hello and you can use any device it supports whether registered with that device or not, but only on that computer). The choice affects which device(s) are offered by the browser and/or computer security system.</p> <script type="application/javascript"> <?php echo file_get_contents(dirname(__DIR__).'/src/webauthnregister.js'); echo file_get_contents(dirname(__DIR__).'/src/webauthnauthenticate.js'); ?> </script> <!-- only for the example, the webauthn js does not need jquery itself --> <script src='https://code.jquery.com/jquery-3.3.1.min.js'></script> <script> $(function(){ $('#iregisterform').submit(function(ev){ var self = $(this); ev.preventDefault(); var cp = $('select[name=cp]').val(); if (cp == "") { $('.cerror').show().text("Please choose cross-platform setting - see note below about what this means"); return; } $('.cerror').empty().hide(); $.ajax({url: '/', method: 'POST', data: {registerusername: self.find('[name=registerusername]').val(), crossplatform: cp}, dataType: 'json', success: function(j){ $('#iregisterform,#iregisterdokey').toggle(); /* activate the key and get the response */ webauthnRegister(j.challenge, function(success, info){ if (success) { $.ajax({url: '/', method: 'POST', data: {register: info}, dataType: 'json', success: function(j){ $('#iregisterform,#iregisterdokey').toggle(); $('.cdone').text("registration completed successfully").show(); setTimeout(function(){ $('.cdone').hide(300); }, 2000); }, error: function(xhr, status, error){ $('.cerror').text("registration failed: "+error+": "+xhr.responseText).show(); } }); } else { $('.cerror').text(info).show(); } }); }, error: function(xhr, status, error){ $('#iregisterform').show(); $('#iregisterdokey').hide(); $('.cerror').text("couldn't initiate registration: "+error+": "+xhr.responseText).show(); } }); }); $('#iloginform').submit(function(ev){ var self = $(this); ev.preventDefault(); $('.cerror').empty().hide(); $.ajax({url: '/', method: 'POST', data: {loginusername: self.find('[name=loginusername]').val()}, dataType: 'json', success: function(j){ $('#iloginform,#ilogindokey').toggle(); /* activate the key and get the response */ webauthnAuthenticate(j.challenge, function(success, info){ if (success) { $.ajax({url: '/', method: 'POST', data: {login: info}, dataType: 'json', success: function(j){ $('#iloginform,#ilogindokey').toggle(); $('.cdone').text("login completed successfully").show(); setTimeout(function(){ $('.cdone').hide(300); }, 2000); }, error: function(xhr, status, error){ $('.cerror').text("login failed: "+error+": "+xhr.responseText).show(); } }); } else { $('.cerror').text(info).show(); } }); }, error: function(xhr, status, error){ $('#iloginform').show(); $('#ilogindokey').hide(); $('.cerror').text("couldn't initiate login: "+error+": "+xhr.responseText).show(); } }); }); }); </script> </body> </html>
php
MIT
91d2011226193eadd383ff407b41d7e8261d43f4
2026-01-05T04:58:53.807707Z
false
davidearl/webauthn
https://github.com/davidearl/webauthn/blob/91d2011226193eadd383ff407b41d7e8261d43f4/WebAuthn/WebAuthn.php
WebAuthn/WebAuthn.php
<?php namespace Davidearl\WebAuthn; //use phpseclib\Crypt\RSA; use phpseclib3\Crypt\PublicKeyLoader; use phpseclib3\Math\BigInteger; /** * @package davidearl\webauthn * * * A class to help manage keys via the webauthn protocol. * * Webauthn allows for browser logins using a physical key (such as a * Yubikey 2) or, in due course, biometrics such as fingerprints, that * support the protocol. * * This is based on the Javascript example at * https://webauthn.bin.coffee/, but offers a PHP server side. * * You need to store a webauthn string (which does not need to be * indexed) in user records in your database, the value of which is * consulted and amended by the various functions in this class. * * Errors are thrown as simple Exception, with code 0 for user errors (such as validation failure) or 1 for * programming errors (wrong argument types etc) * * Dependencies * ------------ * * - You will need to include https://github.com/2tvenom/CBOREncode * - openssl that supports SHA256 */ class WebAuthn { const ES256 = -7; const RS256 = -257; // Windows Hello support var $appid; /** * construct object on which to operate * * @param string $appid a string identifying your app, typically the domain of your website which people * are using the key to log in to. If you have the URL (ie including the * https:// on the front) to hand, give that; * if it's not https, well what are you doing using this code? */ public function __construct($appid) { if (! is_string($appid)) { $this->oops('appid must be a string'); } $this->appid = $appid; if (strpos($this->appid, 'https://') === 0) { $this->appid = substr($this->appid, 8); /* drop the https:// */ } } /** * cancel all keys for a user * @return string to store as the user's webauthn field in your database */ public function cancel() { return ''; } /** * generate a challenge ready for registering a hardware key, fingerprint or whatever: * @param $username string by which the user is known potentially displayed on the hardware key * @param $userid string by which the user can be uniquely identified. Don't use email address as this can change, * user perhaps the database record id * @param $crossPlatform bool default=FALSE, whether to link the identity to the key (TRUE, so it * can be used cross-platofrm, on different computers) or the platform (FALSE, only on * this computer, but with any available authentication device, e.g. known to Windows Hello) * @return string pass this JSON string back to the browser */ public function prepareChallengeForRegistration($username, $userid, $crossPlatform=FALSE) { $result = (object)array(); $rbchallenge = self::randomBytes(16); $result->challenge = self::stringToArray($rbchallenge); $result->user = (object)array(); $result->user->name = $result->user->displayName = $username; $result->user->id = self::stringToArray($userid); $result->rp = (object)array(); $result->rp->name = $result->rp->id = $this->appid; $result->pubKeyCredParams = [ [ 'alg' => self::ES256, 'type' => 'public-key' ], [ 'alg' => self::RS256, 'type' => 'public-key' ] ]; $result->authenticatorSelection = (object)array(); if ($crossPlatform) { $result->authenticatorSelection->authenticatorAttachment = 'cross-platform'; } $result->authenticatorSelection->requireResidentKey = false; $result->authenticatorSelection->userVerification = 'discouraged'; $result->attestation = null; $result->timeout = 60000; $result->excludeCredentials = []; // No excludeList $result->extensions = (object)array(); $result->extensions->exts = true; return json_encode(array('publicKey'=>$result, 'b64challenge'=>rtrim(strtr(base64_encode($rbchallenge), '+/', '-_'), '='))); } /** * registers a new key for a user * requires info from the hardware via javascript given below * @param string $info supplied to the PHP script via a POST, constructed by the Javascript given below, ultimately * provided by the key * @param string $userwebauthn the exisitng webauthn field for the user from your * database (it's actaully a JSON string, but that's entirely internal to * this code) * @return string modified to store in the user's webauthn field in your database */ public function register($info, $userwebauthn) { if (! is_string($info)) { $this->oops('info must be a string', 1); } $info = json_decode($info); if (empty($info)) { $this->oops('info is not properly JSON encoded', 1); } if (empty($info->response->attestationObject)) { $this->oops('no attestationObject in info', 1); } if (empty($info->rawId)) { $this->oops('no rawId in info'); } /* check response from key and store as new identity. This is a hex string representing the raw CBOR attestation object received from the key */ $aos = self::arrayToString($info->response->attestationObject); $ao = (object)(\CBOR\CBOREncoder::decode($aos)); if (empty($ao)) { $this->oops('cannot decode key response (1)'); } if (empty($ao->fmt)) { $this->oops('cannot decode key response (2)'); } if (empty($ao->authData)) { $this->oops('cannot decode key response (3)'); } $bs = $ao->authData->get_byte_string(); if ($ao->fmt == 'fido-u2f') { $this->oops("cannot decode FIDO format responses, sorry"); } elseif ($ao->fmt != 'none' && $ao->fmt != 'packed') { $this->oops('cannot decode key response (4)'); } $ao->rpIdHash = substr($bs, 0, 32); $ao->flags = ord(substr($bs, 32, 1)); $ao->counter = substr($bs, 33, 4); $hashId = hash('sha256', $this->appid, true); if ($hashId != $ao->rpIdHash) { //log(bin2hex($hashId).' '.bin2hex($ao->rpIdHash)); $this->oops('cannot decode key response (5)'); } if (! ($ao->flags & 0x41)) { $this->oops('cannot decode key response (6)'); } /* TUP and AT must be set */ $ao->attData = (object)array(); $ao->attData->aaguid = substr($bs, 37, 16); $ao->attData->credIdLen = (ord($bs[53])<<8)+ord($bs[54]); $ao->attData->credId = substr($bs, 55, $ao->attData->credIdLen); $cborPubKey = substr($bs, 55+$ao->attData->credIdLen); // after credId to end of string $ao->attData->keyBytes = self::COSEECDHAtoPKCS($cborPubKey); if (is_null($ao->attData->keyBytes)) { /* There is a bug in Firefox whereby it provides only one byte for the aaguid field. This means everything else is shifted down by 15 bytes, resulting in a failure to pick up the key algortihm field in COSEECDHAtoPKCS. So if that happens, try again with just that one byte, and only then produce an error if that also fails. Thank you: https://www.antradar.com/blog-firefox-webauthn-incompability */ $ao->attData->aaguid = substr($bs, 37, 1); $ao->attData->credIdLen = (ord($bs[38])<<8)+ord($bs[39]); $ao->attData->credId = substr($bs, 40, $ao->attData->credIdLen); $cborPubKey = substr($bs, 40+$ao->attData->credIdLen); // after credId to end of string $ao->attData->keyBytes = self::COSEECDHAtoPKCS($cborPubKey); if (is_null($ao->attData->keyBytes)) { $this->oops('cannot decode key response (8)'); } } $rawId = self::arrayToString($info->rawId); if ($ao->attData->credId != $rawId) { $this->oops('cannot decode key response (16)'); } $publicKey = (object)array(); $publicKey->key = $ao->attData->keyBytes; $publicKey->id = $info->rawId; //log($publicKey->key); if (empty($userwebauthn)) { $userwebauthn = [$publicKey]; } else { $userwebauthn = json_decode($userwebauthn); $found = false; foreach ($userwebauthn as $idx => $key) { if (implode(',', $key->id) != implode(',', $publicKey->id)) { continue; } $userwebauthn[$idx]->key = $publicKey->key; $found = true; break; } if (! $found) { array_unshift($userwebauthn, $publicKey); } } $userwebauthn = json_encode($userwebauthn); return $userwebauthn; } /** * generates a new key string for the physical key, fingerprint * reader or whatever to respond to on login. * You should store the revised userwebauthn back to your database after calling this function * (to avoid replay attacks) * @param string &$userwebauthn the existing webauthn field for the user from your database * @return string to pass to javascript webauthnAuthenticate */ public function prepareForLogin(&$userwebauthn) { $allow = (object)array(); $allow->type = 'public-key'; $allow->transports = array('usb','nfc','ble','internal'); $allow->id = null; $allows = array(); $challengebytes = self::randomBytes(16); $challengeb64 = rtrim(strtr(base64_encode($challengebytes), '+/', '-_'), '='); if (! empty($userwebauthn)) { $webauthn = json_decode($userwebauthn); foreach ($webauthn as $idx => $key) { $allow->id = $key->id; $allows[] = clone $allow; $webauthn[$idx]->challenge = $challengeb64; } $userwebauthn = json_encode($webauthn); } else { /* including empty user, so they can't tell whether the user exists or not (need same result each time for each user) */ // log("fabricating key"); $allow->id = array(); $rb = md5((string)time()); $allow->id = self::stringToArray($rb); $allows[] = clone $allow; } /* generate key request */ $publickey = (object)array(); $publickey->challenge = self::stringToArray($challengebytes); $publickey->timeout = 60000; $publickey->allowCredentials = $allows; $publickey->userVerification = 'discouraged'; $publickey->extensions = (object)array(); $publickey->extensions->txAuthSimple = 'Execute order 66'; $publickey->rpId = str_replace('https://', '', $this->appid); return json_encode($publickey); } /** * validates a response for login or 2fa * requires info from the hardware via javascript given below. * You should store the revised userwebauthn back to your database after calling this function * (to avoid replay attacks) * @param string $info supplied to the PHP script via a POST, constructed by the Javascript given below, ultimately * provided by the key * @param string &$userwebauthn the exisiting webauthn field for the user from your * database (it's actaully a JSON string, but that's entirely internal to * this code) * @return boolean true for valid authentication or false for failed validation */ public function authenticate($info, &$userwebauthn) { if (! is_string($info)) { $this->oops('info must be a string', 1); } $info = json_decode($info); if (empty($info)) { $this->oops('info is not properly JSON encoded', 1); } $webauthn = empty($userwebauthn) ? array() : json_decode($userwebauthn); /* find appropriate key from those stored for user (usually there'll only be one, but if someone has, say, a physical yubikey on desktop and fingerprint reader on mobile, for example, may be more than one. */ $key = null; foreach ($webauthn as $candkey) { if (implode(',', $candkey->id) != implode(',', $info->rawId)) { continue; } $key = $candkey; break; } if (empty($key)) { $this->oops("no key with id ".implode(',', $info->rawId)); } /* cross-check challenge */ $oc = rtrim(strtr(base64_encode(self::arrayToString($info->originalChallenge)), '+/', '-_'), '='); if ($oc != $info->response->clientData->challenge) { $this->oops("challenge mismatch"); } /* Does the challenge Correspond to the one we stored for the user? If no challenge is stored, that implies $userwebauthn was not saved back to the user database after prepareForLogin. It would be better to produce an error here, but for the purposes of backward compatibility, it'll allow it, but with a replay vulnerability */ //log(print_r($key->challenge,1).' '.print_r($info->response->clientData->challenge,1)); if (isset($key->challenge) && $key->challenge != $info->response->clientData->challenge) { $this->oops("you cannot use the same login more than once"); } /* clear the challenge (but retain it as a property) from each of the keys, so it cannot be re-used */ foreach($webauthn as $idx => $candkey) { $webauthn[$idx]->challenge = ''; } $userwebauthn = json_encode($webauthn); /* cross check origin */ $origin = parse_url($info->response->clientData->origin); if ($this->appid != $origin['host']) { $this->oops("origin mismatch '{$info->response->clientData->origin}'"); } if ($info->response->clientData->type != 'webauthn.get') { $this->oops("type mismatch '{$info->response->clientData->type}'"); } $bs = self::arrayToString($info->response->authenticatorData); $ao = (object)array(); $ao->rpIdHash = substr($bs, 0, 32); $ao->flags = ord(substr($bs, 32, 1)); $ao->counter = substr($bs, 33, 4); $hashId = hash('sha256', $this->appid, true); if ($hashId != $ao->rpIdHash) { // log(bin2hex($hashId).' '.bin2hex($ao->rpIdHash)); $this->oops('cannot decode key response (2b)'); } /* experience shows that at least one device (OnePlus 6T/Pie (Android phone)) doesn't set this, so this test would fail. This is not correct according to the spec, so pragmatically it may have to be removed */ if (($ao->flags & 0x1) != 0x1) { $this->oops('cannot decode key response (2c)'); } /* only TUP must be set */ /* assemble signed data */ $clientdata = self::arrayToString($info->response->clientDataJSONarray); $signeddata = $hashId . chr($ao->flags) . $ao->counter . hash('sha256', $clientdata, true); if (count($info->response->signature) < 70) { $this->oops('cannot decode key response (3)'); } $signature = self::arrayToString($info->response->signature); //$key = str_replace(chr(13), '', $key->key); $key = $key->key; // log($key); switch (@openssl_verify($signeddata, $signature, $key, OPENSSL_ALGO_SHA256)) { case 1: return true; /* hooray, we're in */ case 0: return false; default: $this->oops('cannot decode key response (4) '.openssl_error_string()); } return true; } /** * convert an array of uint8's to a binary string * @param array $a to be converted (array of unsigned 8 bit integers) * @return string converted to bytes */ private static function arrayToString($a) { $s = ''; foreach ($a as $c) { $s .= chr($c); } return $s; } /** * convert a binary string to an array of uint8's * @param string $s to be converted * @return array converted to array of unsigned integers */ private static function stringToArray($s) { /* convert binary string to array of uint8 */ $a = []; for ($idx = 0; $idx < strlen($s); $idx++) { $a[] = ord($s[$idx]); } return $a; } /** * convert a public key from the hardware to PEM format * @param string $key to be converted to PEM format * @return string converted to PEM format */ private function pubkeyToPem($key) { /* see https://github.com/Yubico/php-u2flib-server/blob/master/src/u2flib_server/U2F.php */ if (strlen($key) !== 65 || $key[0] !== "\x04") { return null; } /* * Convert the public key to binary DER format first * Using the ECC SubjectPublicKeyInfo OIDs from RFC 5480 * * SEQUENCE(2 elem) 30 59 * SEQUENCE(2 elem) 30 13 * OID1.2.840.10045.2.1 (id-ecPublicKey) 06 07 2a 86 48 ce 3d 02 01 * OID1.2.840.10045.3.1.7 (secp256r1) 06 08 2a 86 48 ce 3d 03 01 07 * BIT STRING(520 bit) 03 42 ..key.. */ $der = "\x30\x59\x30\x13\x06\x07\x2a\x86\x48\xce\x3d\x02\x01"; $der .= "\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x03\x42"; $der .= "\x00".$key; $pem = "-----BEGIN PUBLIC KEY-----\x0A"; $pem .= chunk_split(base64_encode($der), 64, "\x0A"); $pem .= "-----END PUBLIC KEY-----\x0A"; return $pem; } /** * Convert COSE ECDHA to PKCS * @param string binary string to be converted * @return string converted public key */ private function COSEECDHAtoPKCS($binary) { $cosePubKey = \CBOR\CBOREncoder::decode($binary); if (! isset($cosePubKey[3] /* cose_alg */)) { return NULL; } switch ($cosePubKey[3]) { case self::ES256: /* COSE Alg: ECDSA w/ SHA-256 */ if (! isset($cosePubKey[-1] /* cose_crv */)) { $this->oops('cannot decode key response (9)'); } if (! isset($cosePubKey[-2] /* cose_crv_x */)) { $this->oops('cannot decode key response (10)'); } if ($cosePubKey[-1] != 1 /* cose_crv_P256 */) { $this->oops('cannot decode key response (14)'); } if (!isset($cosePubKey[-2] /* cose_crv_x */)) { $this->oops('x coordinate for curve missing'); } if (! isset($cosePubKey[1] /* cose_kty */)) { $this->oops('cannot decode key response (7)'); } if (! isset($cosePubKey[-3] /* cose_crv_y */)) { $this->oops('cannot decode key response (11)'); } if (!isset($cosePubKey[-3] /* cose_crv_y */)) { $this->oops('y coordinate for curve missing'); } if ($cosePubKey[1] != 2 /* cose_kty_ec2 */) { $this->oops('cannot decode key response (12)'); } $x = $cosePubKey[-2]->get_byte_string(); $y = $cosePubKey[-3]->get_byte_string(); if (strlen($x) != 32 || strlen($y) != 32) { $this->oops('cannot decode key response (15)'); } $tag = "\x04"; return $this->pubkeyToPem($tag.$x.$y); break; case self::RS256: /* COSE Alg: RSASSA-PKCS1-v1_5 w/ SHA-256 */ if (!isset($cosePubKey[-2])) { $this->oops('RSA Exponent missing'); } if (!isset($cosePubKey[-1])) { $this->oops('RSA Modulus missing'); } $e = new BigInteger(bin2hex($cosePubKey[-2]->get_byte_string()), 16); $n = new BigInteger(bin2hex($cosePubKey[-1]->get_byte_string()), 16); return (string)PublicKeyLoader::load(compact('e', 'n')); default: $this->oops('cannot decode key response (13)'); } } /** * shim for random_bytes which doesn't exist pre php7 * @param int $length the number of bytes required * @return string length cryptographically random bytes */ private static function randomBytes($length) { if (function_exists('random_bytes')) { return random_bytes($length); } else if (function_exists('openssl_random_pseudo_bytes')) { $bytes = openssl_random_pseudo_bytes($length, $crypto_strong); if (! $crypto_strong) { throw new \Exception("openssl_random_pseudo_bytes did not return a cryptographically strong result", 1); } return $bytes; } else { throw new \Exception("Neither random_bytes not openssl_random_pseudo_bytes exists. PHP too old? openssl PHP extension not installed?", 1); } } /** * just an abbreviation to throw an error: never returns * @param string $s error message * @param int $c error code (0 for user error, 1 for incorrect usage) * */ private function oops($s, $c=0) { error_log("oops: {$s} {$c}"); throw new \Exception($s, $c); } protected function getUrlSuffix() { } }
php
MIT
91d2011226193eadd383ff407b41d7e8261d43f4
2026-01-05T04:58:53.807707Z
false
wotzebra/unique-codes
https://github.com/wotzebra/unique-codes/blob/ec9ee4c994bfea4922a13dae98e8388c4e0f34d7/.php-cs-fixer.php
.php-cs-fixer.php
<?php use AdamWojs\PhpCsFixerPhpdocForceFQCN\Fixer\Phpdoc\ForceFQCNFixer; use PhpCsFixer\Config; use PhpCsFixer\Finder; $rules = [ '@PSR2' => true, // Each line of multi-line DocComments must have an asterisk [PSR-5] and must be aligned with the first one. // 'align_multiline_comment' => true, // Each element of an array must be indented exactly once. 'array_indentation' => true, // PHP arrays should be declared using the configured syntax. 'array_syntax' => ['syntax' => 'short'], // Binary operators should be surrounded by space as configured. 'binary_operator_spaces' => true, // Ensure there is no code on the same line as the PHP open tag and it is followed by a blank line. 'blank_line_after_opening_tag' => true, // An empty line feed must precede any configured statement. 'blank_line_before_statement' => true, // A single space or none should be between cast and variable. 'cast_spaces' => true, // Class, trait and interface elements must be separated with one blank line. 'class_attributes_separation' => true, // Remove extra spaces in a nullable typehint. 'compact_nullable_typehint' => true, // Concatenation should be spaced according configuration. 'concat_space' => ['spacing' => 'one'], // Add curly braces to indirect variables to make them clear to understand. // Requires PHP >= 7.0. 'explicit_indirect_variable' => true, // Converts implicit variables into explicit ones in double-quoted strings or heredoc syntax. 'explicit_string_variable' => true, // Transforms imported FQCN parameters and return types in function arguments to short version. 'fully_qualified_strict_types' => true, // Add missing space between function's argument and its typehint. 'function_typehint_space' => true, // Pre- or post-increment and decrement operators should be used if possible. 'increment_style' => ['style' => 'post'], // Ensure there is no code on the same line as the PHP open tag. 'linebreak_after_opening_tag' => true, // Cast should be written in lower case. 'lowercase_cast' => true, // Class static references `self`, `static` and `parent` MUST be in lower case. 'lowercase_static_reference' => true, // Magic constants should be referred to using the correct casing. 'magic_constant_casing' => true, // Magic method definitions and calls must be using the correct casing. 'magic_method_casing' => true, // Method chaining MUST be properly indented. // Method chaining with different levels of indentation is not supported. 'method_chaining_indentation' => true, // DocBlocks must start with two asterisks, multiline comments must start with a single asterisk, after the opening slash. // Both must end with a single asterisk before the closing slash. 'multiline_comment_opening_closing' => true, // Forbid multi-line whitespace before the closing semicolon or move the semicolon to the new line for chained calls. 'multiline_whitespace_before_semicolons' => true, // Function defined by PHP should be called using the correct casing. 'native_function_casing' => true, // All instances created with new keyword must be followed by braces. 'new_with_braces' => true, // Replace control structure alternative syntax to use braces. 'no_alternative_syntax' => true, // There should be no empty lines after class opening brace. 'no_blank_lines_after_class_opening' => true, // There should not be blank lines between docblock and the documented element. 'no_blank_lines_after_phpdoc' => true, // There should not be empty PHPDoc blocks. 'no_empty_phpdoc' => true, // Remove useless semicolon statements. 'no_empty_statement' => true, // Removes extra blank lines and/or blank lines following configuration. 'no_extra_blank_lines' => ['tokens' => ['break', 'continue', 'curly_brace_block', 'extra', 'parenthesis_brace_block', 'return', 'square_brace_block', 'throw', 'use', 'use_trait', 'switch', 'case', 'default']], // Remove leading slashes in `use` clauses. 'no_leading_import_slash' => true, // The namespace declaration line shouldn't contain leading whitespace. 'no_leading_namespace_whitespace' => true, // Operator `=>` should not be surrounded by multi-line whitespaces. 'no_multiline_whitespace_around_double_arrow' => true, // Short cast `bool` using double exclamation mark should not be used. 'no_short_bool_cast' => true, // Single-line whitespace before closing semicolon are prohibited. 'no_singleline_whitespace_before_semicolons' => true, // There MUST NOT be spaces around offset braces. 'no_spaces_around_offset' => true, // Remove trailing commas in list function calls. 'no_trailing_comma_in_list_call' => true, // PHP single-line arrays should not have trailing comma. 'no_trailing_comma_in_singleline_array' => true, // Removes unneeded parentheses around control statements. 'no_unneeded_control_parentheses' => true, // Unused `use` statements must be removed. 'no_unused_imports' => true, // There should not be useless `else` cases. 'no_useless_else' => true, // There should not be an empty `return` statement at the end of a function. 'no_useless_return' => true, // In array declaration, there MUST NOT be a whitespace before each comma. 'no_whitespace_before_comma_in_array' => true, // Remove trailing whitespace at the end of blank lines. 'no_whitespace_in_blank_line' => true, // Array index should always be written by using square braces. 'normalize_index_brace' => true, // Logical NOT operators (`!`) should have one trailing whitespace. 'not_operator_with_successor_space' => true, // There should not be space before or after object `T_OBJECT_OPERATOR` `->`. 'object_operator_without_whitespace' => true, // Ordering `use` statements. 'ordered_imports' => ['sort_algorithm' => 'alpha'], // Enforce camel (or snake) case for PHPUnit test methods, following configuration. 'php_unit_method_casing' => ['case' => 'snake_case'], // All items of the given phpdoc tags must be either left-aligned or (by default) aligned vertically. 'phpdoc_align' => ['align' => 'left'], // PHPDoc annotation descriptions should not be a sentence. 'phpdoc_annotation_without_dot' => true, // Docblocks should have the same indentation as the documented subject. 'phpdoc_indent' => true, // Fix PHPDoc inline tags, make `@inheritdoc` always inline. // `@access` annotations should be omitted from PHPDoc. 'phpdoc_no_access' => true, // No alias PHPDoc tags should be used. 'phpdoc_no_alias_tag' => true, // `@package` and `@subpackage` annotations should be omitted from PHPDoc. 'phpdoc_no_package' => true, // Classy that does not inherit must not have `@inheritdoc` tags. 'phpdoc_no_useless_inheritdoc' => true, // Annotations in PHPDoc should be ordered so that `@param` annotations come first, then `@throws` annotations, then `@return` annotations. 'phpdoc_order' => true, // The type of `@return` annotations of methods returning a reference to itself must the configured one. 'phpdoc_return_self_reference' => true, // Scalar types should always be written in the same form. // `int` not `integer`, `bool` not `boolean`, `float` not `real` or `double`. 'phpdoc_scalar' => true, // Annotations in PHPDoc should be grouped together so that annotations of the same type immediately follow each other, and annotations of a different type are separated by a single blank line. 'phpdoc_separation' => true, // Single line `@var` PHPDoc should have proper spacing. 'phpdoc_single_line_var_spacing' => true, // PHPDoc summary should end in either a full stop, exclamation mark, or question mark. 'phpdoc_summary' => true, // Docblocks should only be used on structural elements. 'phpdoc_to_comment' => true, // PHPDoc should start and end with content, excluding the very first and last line of the docblocks. 'phpdoc_trim' => true, // Removes extra blank lines after summary and after description in PHPDoc. 'phpdoc_trim_consecutive_blank_line_separation' => true, // The correct case must be used for standard PHP types in PHPDoc. 'phpdoc_types' => true, // Sorts PHPDoc types. 'phpdoc_types_order' => ['null_adjustment' => 'always_last'], // `@var` and `@type` annotations should not contain the variable name. 'phpdoc_var_without_name' => true, // There should be one or no space before colon, and one space after it in return type declarations, according to configuration. 'return_type_declaration' => ['space_before' => 'one'], // Instructions must be terminated with a semicolon. 'semicolon_after_instruction' => true, // Cast `(boolean)` and `(integer)` should be written as `(bool)` and `(int)`, `(double)` and `(real)` as `(float)`, `(binary)` as `(string)`. 'short_scalar_cast' => true, // There should be exactly one blank line before a namespace declaration. 'single_blank_line_before_namespace' => true, // Convert double quotes to single quotes for simple strings. 'single_quote' => ['strings_containing_single_quote_chars' => true], // Fix whitespace after a semicolon. 'space_after_semicolon' => true, // Increment and decrement operators should be used if possible. 'standardize_increment' => true, // Replace all `<>` with `!=`. 'standardize_not_equals' => true, // Standardize spaces around ternary operator. 'ternary_operator_spaces' => true, // Use `null` coalescing operator `??` where possible. // Requires PHP >= 7.0. 'ternary_to_null_coalescing' => true, // PHP multi-line arrays should have a trailing comma. 'trailing_comma_in_multiline' => true, // Arrays should be formatted like function/method arguments, without leading or trailing single line space. 'trim_array_spaces' => true, // Unary operators should be placed adjacent to their operands. 'unary_operator_spaces' => true, // In array declaration, there MUST be a whitespace after each comma. 'whitespace_after_comma_in_array' => true, // Force Fully-Qualified Class Name in docblocks 'AdamWojs/phpdoc_force_fqcn_fixer' => true, ]; $finder = Finder::create() ->notPath('bootstrap') ->notPath('storage') ->notPath('vendor') ->in(__DIR__) ->name('*.php') ->name('_ide_helper') ->notName('*.blade.php') ->ignoreDotFiles(true) ->ignoreVCS(true); return (new Config()) ->registerCustomFixers([ new ForceFQCNFixer(), ]) ->setRules($rules) ->setFinder($finder);
php
MIT
ec9ee4c994bfea4922a13dae98e8388c4e0f34d7
2026-01-05T04:59:19.140159Z
false
wotzebra/unique-codes
https://github.com/wotzebra/unique-codes/blob/ec9ee4c994bfea4922a13dae98e8388c4e0f34d7/src/UniqueCodes.php
src/UniqueCodes.php
<?php namespace Wotz\UniqueCodes; use RuntimeException; class UniqueCodes { /** * The prime number that is used to convert a number to a unique other number within the maximum range. * * @var int */ protected $obfuscatingPrime; /** * The prime number that is one larger than the maximum number that can be converted to a code. * * @var int */ protected $maxPrime; /** * The suffix that will be added to every code. * * @var string|null */ protected $suffix; /** * The prefix that will be added to every code. * * @var string|null */ protected $prefix; /** * The delimiter that separates the different parts of the generated code. * * @var string|null */ protected $delimiter; /** * The size of every part of the generated code. * * @var int|null */ protected $splitLength; /** * The list of characters that a generated code can contain. * * @var string */ protected $characters; /** * The length of the code. * * @var int */ protected $length; /** * Set the obfuscating prime number. * * @param int $prime * * @return self */ public function setObfuscatingPrime(int $obfuscatingPrime) { $this->obfuscatingPrime = $obfuscatingPrime; return $this; } /** * Set the max prime number. * * @param int $maxPrime * * @return self */ public function setMaxPrime(int $maxPrime) { $this->maxPrime = $maxPrime; return $this; } /** * Set the suffix. * * @param string $suffix * * @return self */ public function setSuffix(string $suffix) { $this->suffix = $suffix; return $this; } /** * Set the prefix. * * @param string $prefix * * @return self */ public function setPrefix(string $prefix) { $this->prefix = $prefix; return $this; } /** * Set the delimiter. * * @param string $delimiter * @param int|null $splitLength * * @return self */ public function setDelimiter(string $delimiter, int $splitLength = null) { $this->delimiter = $delimiter; $this->splitLength = $splitLength; return $this; } /** * Set the characters. * * @param array|string $characters * * @return self */ public function setCharacters($characters) { if (is_array($characters)) { $characters = implode('', $characters); } $this->characters = $characters; return $this; } /** * Set the length. * * @param int $length * * @return self */ public function setLength(int $length) { $this->length = $length; return $this; } /** * Generate the necessary amount of codes. * * @param int $start * @param int|null $end * @param bool $toArray * * @return array|\Generator|string */ public function generate(int $start, int $end = null, bool $toArray = false) { $this->validateInput($start, $end); $generator = (function () use ($start, $end) { for ($i = $start; $i <= ($end ?? $start); $i++) { $number = $this->obfuscateNumber($i); $string = $this->encodeNumber($number); yield $this->constructCode($string); } })(); if ($end === null) { return iterator_to_array($generator)[0]; } if ($toArray) { return iterator_to_array($generator); } return $generator; } /** * Map number to a unique other number smaller than the max prime number. * * @param int $number * * @return int */ protected function obfuscateNumber(int $number) { return ($number * $this->obfuscatingPrime) % $this->maxPrime; } /** * Encode number into characters. * * @param int $number * * @return string */ protected function encodeNumber(int $number) { $string = ''; $characters = $this->characters; for ($i = 0; $i < $this->length; $i++) { $digit = intval($number) % strlen($characters); $string = $characters[$digit] . $string; $number = $number / strlen($characters); } return $string; } /** * Construct the code. * * @param string $string * * @return string */ protected function constructCode($string) { $code = ''; if ($this->prefix !== null) { $code .= $this->prefix . $this->delimiter; } if ($this->splitLength !== null) { $code .= implode($this->delimiter, str_split($string, $this->splitLength)); } else { $code .= $string; } if ($this->suffix !== null) { $code .= $this->delimiter . $this->suffix; } return $code; } /** * Check if all property values are valid. * * @param int $start * @param int|null $end * * @throws \RuntimeException * * @return void */ protected function validateInput(int $start, int $end = null) { if (empty($this->obfuscatingPrime)) { throw new RuntimeException('Obfuscating prime number must be specified'); } if (empty($this->maxPrime)) { throw new RuntimeException('Max prime number must be specified'); } if (empty($this->characters)) { throw new RuntimeException('Character list must be specified'); } if (empty($this->length)) { throw new RuntimeException('Length must be specified'); } if ($this->obfuscatingPrime <= $this->maxPrime) { throw new RuntimeException('Obfuscating prime number must be larger than the max prime number'); } if (count(array_unique(str_split($this->characters))) !== strlen($this->characters)) { throw new RuntimeException('The character list can not contain duplicates'); } if ($this->getMaximumUniqueCodes() <= $this->maxPrime) { throw new RuntimeException( 'The length of the code is too short or the character list is too small ' . 'to create the number of unique codes equal to the max prime number' ); } if ($start <= 0) { throw new RuntimeException('The start number must be bigger than zero'); } if ($end !== null && $end >= $this->maxPrime) { throw new RuntimeException('The end number can not be bigger or equal to the max prime number'); } } /** * Get the maximum amount of unique codes that can create based the characters. * * @return int */ protected function getMaximumUniqueCodes() { return pow(strlen($this->characters), $this->length); } }
php
MIT
ec9ee4c994bfea4922a13dae98e8388c4e0f34d7
2026-01-05T04:59:19.140159Z
false
wotzebra/unique-codes
https://github.com/wotzebra/unique-codes/blob/ec9ee4c994bfea4922a13dae98e8388c4e0f34d7/tests/UniqueCodesTest.php
tests/UniqueCodesTest.php
<?php namespace Wotz\UniqueCodes\Tests; use Generator; use PHPUnit\Framework\TestCase; use ReflectionClass; use RuntimeException; use Wotz\UniqueCodes\UniqueCodes; class UniqueCodesTest extends TestCase { /** * @test * * @dataProvider uniqueCodesProvider */ public function it_generates_unique_codes($maxPrime, $obfuscatingPrime, $obfuscatingPrimeMultiplicativeInverse, $length, $characters) { $uniqueCodes = (new UniqueCodes()) ->setObfuscatingPrime($obfuscatingPrime) ->setMaxPrime($maxPrime) ->setCharacters($characters) ->setLength($length) ->generate(1, $maxPrime - 1, true); $this->assertCount($maxPrime - 1, $uniqueCodes); $this->assertCount($maxPrime - 1, array_unique($uniqueCodes)); foreach ($uniqueCodes as $index => $code) { $obfuscatedNumber = $this->decode($code, $characters); $this->assertEquals($index + 1, ($obfuscatedNumber * $obfuscatingPrimeMultiplicativeInverse) % $maxPrime); } } public function uniqueCodesProvider() : array { return [ [101, 387420489, 47, 3, 'ABCDE'], [101, 191, 55, 3, '12345'], [30983, 98893, 3925, 4, '123456ABCDEFGH'], [495563, 968197, 86214, 6, 'ABCDEFGHI'], [1340021, 6824473, 46234, 8, 'ABCDEF'], [7230323, 9006077, 4263725, 6, 'LQJCKZMWDPTSXRGANYVBHF'], ]; } /** * @test * * @dataProvider obfuscateNumbersProvider */ public function it_obfuscates_numbers($maxPrime, $obfuscatingPrime, $obfuscatingPrimeMultiplicativeInverse, $number, $expectedObfuscatedNumber) { $uniqueCodes = (new UniqueCodes())->setObfuscatingPrime($obfuscatingPrime)->setMaxPrime($maxPrime); $class = new ReflectionClass($uniqueCodes); $method = $class->getMethod('obfuscateNumber'); $method->setAccessible(true); $this->assertEquals($expectedObfuscatedNumber, $obfuscatedNumber = $method->invokeArgs($uniqueCodes, [$number])); $this->assertEquals($number, ($obfuscatedNumber * $obfuscatingPrimeMultiplicativeInverse) % $maxPrime); $this->assertEquals(0, $method->invokeArgs($uniqueCodes, [$maxPrime])); $this->assertEquals($expectedObfuscatedNumber, $method->invokeArgs($uniqueCodes, [$number + $maxPrime])); } public function obfuscateNumbersProvider() : array { return [ [101, 387420489, 47, 1, 43], [101, 387420489, 47, 2, 86], [101, 387420489, 47, 3, 28], [101, 387420489, 47, 4, 71], [101, 387420489, 47, 5, 13], [101, 387420489, 47, 6, 56], [101, 387420489, 47, 7, 99], [101, 387420489, 47, 8, 41], [101, 387420489, 47, 9, 84], [101, 387420489, 47, 10, 26], [495563, 968197, 86214, 1, 472634], [495563, 968197, 86214, 2, 449705], [495563, 968197, 86214, 3, 426776], [495563, 968197, 86214, 4, 403847], [495563, 968197, 86214, 5, 380918], [495563, 968197, 86214, 6, 357989], [495563, 968197, 86214, 7, 335060], [3469, 8311, 2471, 1, 1373], [3469, 8311, 2471, 2, 2746], [3469, 8311, 2471, 3, 650], [3469, 8311, 2471, 4, 2023], [3469, 8311, 2471, 5, 3396], [3469, 8311, 2471, 6, 1300], [3469, 8311, 2471, 7, 2673], ]; } /** * @test * * @dataProvider obfuscateNumbersWithinRangeProvider */ public function it_obfuscates_numbers_within_range($maxPrime, $obfuscatingPrime) { $uniqueCodes = (new UniqueCodes())->setObfuscatingPrime($obfuscatingPrime)->setMaxPrime($maxPrime); $class = new ReflectionClass($uniqueCodes); $method = $class->getMethod('obfuscateNumber'); $method->setAccessible(true); $result = []; for ($i = 1; $i < $maxPrime; $i++) { $result[] = $method->invokeArgs($uniqueCodes, [$i]); } sort($result); $this->assertEquals(range(1, $maxPrime - 1), $result); } public function obfuscateNumbersWithinRangeProvider() : array { return [ [101, 387420489], [101, 191], [30983, 98893], [495563, 968197], [1340021, 6824473], [7230323, 9006077], [495563, 968197], ]; } /** * @test * * @dataProvider encodeNumbersProvider */ public function it_encodes_numbers($start, $end, $length, $characters) { $uniqueCodes = (new UniqueCodes())->setLength($length)->setCharacters($characters); $class = new ReflectionClass($uniqueCodes); $method = $class->getMethod('encodeNumber'); $method->setAccessible(true); $result = []; for ($i = $start; $i <= $end; $i++) { $string = $method->invokeArgs($uniqueCodes, [$i]); $this->assertEquals($i, $this->decode($string, $characters)); $result[] = $string; } $this->assertCount($end - $start + 1, $result); $this->assertCount($end - $start + 1, array_unique($result)); $this->assertEquals(0, $this->decode($string, $method->invokeArgs($uniqueCodes, [$end + 1]))); } public function encodeNumbersProvider() : array { return [ [1, 1295, 4, 'ABCDEF'], [1, 531440, 6, 'ABCDEFGHI'], [1, 1419856, 5, 'ABCDEFGHIJLKMNOPQ'], ]; } /** @test */ public function it_returns_generator_by_default() { $codes = (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(1, 100); $this->assertInstanceOf(Generator::class, $codes); } /** @test */ public function it_returns_array_if_requested() { $codes = (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(1, 100, true); $this->assertIsArray($codes); } /** @test */ public function it_returns_string_if_no_end_provided() { $code = (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(100); $this->assertIsString($code); } /** @test */ public function it_generates_unique_codes_within_range() { $codes = iterator_to_array( (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(25, 75) ); $this->assertCount(51, $codes); $this->assertCount(51, array_unique($codes)); } /** @test */ public function it_generates_one_unique_code() { $codes = iterator_to_array( (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(25, 25) ); $this->assertCount(1, $codes); $this->assertCount(1, array_unique($codes)); } /** @test */ public function it_generates_codes_that_only_contain_characters_from_specified_character_list() { $codes = iterator_to_array( (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters($characters = 'ABCDEFG') ->setLength(6) ->generate(1, 100) ); foreach ($codes as $code) { $this->assertEquals(6, strlen($code)); $this->assertCount(0, array_diff(str_split($code), str_split($characters))); } } /** @test */ public function it_generates_codes_with_character_list_array() { $codes = iterator_to_array( (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters($characters = ['A', 'B', 'C', 'D', 'E', 'F', 'G']) ->setLength(6) ->generate(1, 100) ); $this->assertCount(100, array_unique($codes)); foreach ($codes as $code) { $this->assertEquals(6, strlen($code)); $this->assertCount(0, array_diff(str_split($code), $characters)); } } /** @test */ public function it_generates_codes_with_prefix() { $codes = iterator_to_array( (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->setPrefix('TEST') ->generate(1, 100) ); $this->assertCount(100, array_unique($codes)); foreach ($codes as $code) { $this->assertEquals(10, strlen($code)); $this->assertEquals('TEST', substr($code, 0, 4)); } } /** @test */ public function it_generates_codes_with_suffix() { $codes = iterator_to_array( (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->setSuffix('TEST') ->generate(1, 100) ); $this->assertCount(100, array_unique($codes)); foreach ($codes as $code) { $this->assertEquals(10, strlen($code)); $this->assertEquals('TEST', substr($code, 6, 4)); } } /** @test */ public function it_generates_codes_with_prefix_and_suffix() { $codes = iterator_to_array( (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->setPrefix('PREFIX') ->setSuffix('SUFFIX') ->generate(1, 100) ); $this->assertCount(100, array_unique($codes)); foreach ($codes as $code) { $this->assertEquals(18, strlen($code)); $this->assertEquals('PREFIX', substr($code, 0, 6)); $this->assertEquals('SUFFIX', substr($code, 12, 6)); } } /** @test */ public function it_generates_codes_with_delimiter() { $codes = iterator_to_array( (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->setDelimiter('-', 3) ->generate(1, 100) ); $this->assertCount(100, array_unique($codes)); foreach ($codes as $code) { $this->assertEquals(7, strlen($code)); $this->assertEquals('-', substr($code, 3, 1)); } } /** @test */ public function it_generates_codes_with_suffix_and_prefix_and_delimiter() { $codes = iterator_to_array( (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->setPrefix('PREFIX') ->setSuffix('SUFFIX') ->setDelimiter('-', 3) ->generate(1, 100) ); $this->assertCount(100, array_unique($codes)); foreach ($codes as $code) { $this->assertEquals(21, strlen($code)); $this->assertEquals('PREFIX-', substr($code, 0, 7)); $this->assertEquals('-', substr($code, 10, 1)); $this->assertEquals('-SUFFIX', substr($code, 14, 7)); } } /** @test */ public function it_throws_exception_if_obfuscating_prime_is_not_specified() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Obfuscating prime number must be specified'); (new UniqueCodes()) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(1, 100); } /** @test */ public function it_throws_exception_if_max_prime_is_not_specified() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Max prime number must be specified'); (new UniqueCodes()) ->setObfuscatingPrime(191) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(1, 100); } /** @test */ public function it_throws_exception_if_characters_are_not_specified() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Character list must be specified'); (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setLength(6) ->generate(1, 100); } /** @test */ public function it_throws_exception_if_length_is_not_specified() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Length must be specified'); (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->generate(1, 100); } /** @test */ public function it_throws_exception_if_obfuscating_prime_number_is_smaller_than_max_prime_number() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Obfuscating prime number must be larger than the max prime number'); (new UniqueCodes()) ->setObfuscatingPrime(17) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(1, 100); } /** @test */ public function it_throws_exception_if_obfuscating_prime_number_is_equal_to_max_prime_number() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Obfuscating prime number must be larger than the max prime number'); (new UniqueCodes()) ->setObfuscatingPrime(101) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(1, 100); } /** @test */ public function it_throws_exception_if_character_list_contains_duplicates() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The character list can not contain duplicates'); (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHIA') ->setLength(6) ->generate(1, 100); } /** @test */ public function it_throws_exception_if_max_prime_number_is_too_big_for_the_specified_character_list_and_code_length() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The length of the code is too short or the character list is too small to create the number of unique codes equal to the max prime number'); (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCD') ->setLength(3) ->generate(1, 100); } /** @test */ public function it_throws_exception_if_start_is_less_than_zero() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The start number must be bigger than zero'); (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(-1, 100); } /** @test */ public function it_throws_exception_if_start_equals_zero() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The start number must be bigger than zero'); (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(0, 100); } /** @test */ public function it_throws_exception_if_end_is_bigger_than_max_prime_number() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The end number can not be bigger or equal to the max prime number'); (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(50, 150); } /** @test */ public function it_throws_exception_if_end_equals_max_prime_number() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The end number can not be bigger or equal to the max prime number'); (new UniqueCodes()) ->setObfuscatingPrime(191) ->setMaxPrime(101) ->setCharacters('ABCDEFGHI') ->setLength(6) ->generate(50, 101); } public function decode(string $value, string $alphabet) : int { $digits = str_split($value); $characters = str_split($alphabet); $result = 0; for ($i = 1; $i <= strlen($value); $i++) { $result += (array_search($digits[$i - 1], $characters) * bcpow(strlen($alphabet), strlen($value) - $i)); } return $result; } }
php
MIT
ec9ee4c994bfea4922a13dae98e8388c4e0f34d7
2026-01-05T04:59:19.140159Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/rector.php
rector.php
<?php declare(strict_types=1); use Rector\Config\RectorConfig; use Rector\Set\ValueObject\LevelSetList; use Rector\Set\ValueObject\SetList; return static function (RectorConfig $rectorConfig): void { $rectorConfig->paths([ __DIR__.'/src', ]); $rectorConfig->sets([ LevelSetList::UP_TO_PHP_81, SetList::CODE_QUALITY, // SetList::DEAD_CODE, // TODO: Enable when everything is finished SetList::EARLY_RETURN, SetList::TYPE_DECLARATION, ]); };
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/TailwindMerge.php
src/TailwindMerge.php
<?php namespace TailwindMerge; use Psr\SimpleCache\CacheInterface; use TailwindMerge\Contracts\TailwindMergeContract; use TailwindMerge\Support\Collection; use TailwindMerge\Support\Config; use TailwindMerge\Support\Str; use TailwindMerge\Support\TailwindClassParser; use TailwindMerge\ValueObjects\ParsedClass; class TailwindMerge implements TailwindMergeContract { public static function instance(): self { return self::factory() ->make(); } /** * Creates a new factory instance */ public static function factory(): Factory { return new Factory(); } /** * @param array<string, mixed> $configuration */ public function __construct( private readonly array $configuration, private readonly ?CacheInterface $cache = null, ) { } /** * @param string|array<array-key, string|array<array-key, string>> ...$args */ public function merge(...$args): string { $input = Collection::make($args)->flatten()->join(' '); return $this->withCache($input, function (string $input): string { $conflictingClassGroups = []; $parser = new TailwindClassParser($this->configuration); return Str::of($input) ->trim() ->split('/\s+/') ->map(fn (string $class): ParsedClass => $parser->parse($class)) // @phpstan-ignore-line ->reverse() ->map(function (ParsedClass $class) use (&$conflictingClassGroups): ?string { $classId = $class->modifierId.$class->classGroupId; if (array_key_exists($classId, $conflictingClassGroups)) { return null; } $conflictingClassGroups[$classId] = true; foreach ($this->getConflictingClassGroupIds($class->classGroupId, $class->hasPostfixModifier) as $group) { $conflictingClassGroups[$class->modifierId.$group] = true; } return $class->originalClassName; }) ->reverse() ->filter() ->join(' '); }); } /** * @return array<array-key, string> */ private function getConflictingClassGroupIds(string $classGroupId, bool $hasPostfixModifier): array { $conflicts = Config::getMergedConfig()['conflictingClassGroups'][$classGroupId] ?? []; if ($hasPostfixModifier && isset(Config::getMergedConfig()['conflictingClassGroupModifiers'][$classGroupId])) { return [...$conflicts, ...Config::getMergedConfig()['conflictingClassGroupModifiers'][$classGroupId]]; } return $conflicts; } private function withCache(string $input, \Closure $callback): string { if (! $this->cache instanceof CacheInterface) { return $callback($input); } $key = hash('xxh3', 'tailwind-merge-'.$input); if ($this->cache->has($key)) { $cachedValue = $this->cache->get($key); if (is_string($cachedValue)) { return $cachedValue; } } $mergedClasses = $callback($input); $this->cache->set($key, $mergedClasses); return $mergedClasses; } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Factory.php
src/Factory.php
<?php namespace TailwindMerge; use Psr\SimpleCache\CacheInterface; use TailwindMerge\Support\Config; final class Factory { /** * @var array<string, mixed> */ private array $additionalConfiguration = []; private ?CacheInterface $cache = null; /** * Override the default configuration. * * @param array<string, mixed> $configuration */ public function withConfiguration(array $configuration): self { $this->additionalConfiguration = $configuration; return $this; } public function withCache(CacheInterface $cache): self { $this->cache = $cache; return $this; } /** * Creates a new TailwindMerge instance. */ public function make(): TailwindMerge { Config::setAdditionalConfig($this->additionalConfiguration); $config = Config::getMergedConfig(); return new TailwindMerge($config, $this->cache); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Support/Collection.php
src/Support/Collection.php
<?php namespace TailwindMerge\Support; /** * @template TKey of array-key * @template TValue * * @internal */ class Collection { /** * @var array<TKey, TValue> */ protected array $items = []; /** * @param self<array-key, TValue>|array<array-key, TValue> $items * @return void */ public function __construct(self|array $items = []) { if ($items instanceof self) { $items = $items->all(); } $this->items = $items; } /** * @template TMakeKey of array-key * @template TMakeValue * * @param array<TMakeKey, TMakeValue> $items * @return self<TMakeKey, TMakeValue> */ public static function make(array $items = []): self { return new self($items); } public function contains(string $key): bool { return in_array($key, $this->items); } /** * @return self<int, mixed> */ public function flatten(int $depth = PHP_INT_MAX): self { return new self(Arr::flatten($this->items, $depth)); } public function join(string $glue): string { return implode($glue, $this->items); } /** * @template TMapWithKeysKey of array-key * @template TMapWithKeysValue * * @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback * @return self<TMapWithKeysKey, TMapWithKeysValue> */ public function mapWithKeys(callable $callback): self { return new self(Arr::mapWithKeys($this->items, $callback)); // @phpstan-ignore-line } /** * @return self<int, TValue> */ public function sort(): self { $items = $this->items; asort($items); return new self($items); } /** * @return self<int, TValue> */ public function values(): self { return new self(array_values($this->items)); } /** * @return array<TKey, mixed> */ public function toArray(): array { return $this->map(fn (mixed $value): mixed => $value instanceof Collection ? $value->toArray() : $value)->all(); } /** * @template TMapValue * * @param callable(TValue, TKey): TMapValue $callback * @return self<TKey, TMapValue> */ public function map(callable $callback): self { return new self(Arr::map($this->items, $callback)); // @phpstan-ignore-line } /** * @return array<TKey, TValue> */ public function all(): array { return $this->items; } /** * @param TValue $item * @return $this */ public function add(mixed $item): self { $this->items[] = $item; return $this; } /** * @param (callable(TValue, TKey): bool)|null $callback * @return ?TValue */ public function first(?callable $callback = null): mixed { return Arr::first($this->items, $callback); // @phpstan-ignore-line } /** * @param array<array-key, TValue>|self<array-key, TValue> $source * @return self<array-key, TValue> */ public function concat(array|self $source): self { $result = new self($this); if ($source instanceof self) { $source = $source->all(); } foreach ($source as $item) { $result->push($item); } return $result; } /** * @param TValue ...$values * @return $this */ public function push(...$values): self { foreach ($values as $value) { $this->items[] = $value; } return $this; } /** * @return self<TKey, TValue> */ public function reverse(): self { return new self(array_reverse($this->items, true)); } /** * @return self<TKey, TValue> */ public function filter(): self { return new self(array_filter($this->items)); } public function dd(): void { dd($this->items); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Support/ClassMap.php
src/Support/ClassMap.php
<?php namespace TailwindMerge\Support; use TailwindMerge\ValueObjects\ClassPartObject; use TailwindMerge\ValueObjects\ClassValidatorObject; use TailwindMerge\ValueObjects\ThemeGetter; class ClassMap { final public const CLASS_PART_SEPARATOR = '-'; /** * @param array{cacheSize: int, prefix: ?string, theme: array<string, mixed>, classGroups: array<string, mixed>,conflictingClassGroups: array<string, array<int, string>>, conflictingClassGroupModifiers: array<string, array<int, string>>} $config */ public static function create(array $config): ClassPartObject { $theme = $config['theme']; $prefix = $config['prefix']; $classMap = new ClassPartObject(); $prefixedClassGroupEntries = self::getPrefixedClassGroupEntries( $config['classGroups'], $prefix, ); foreach ($prefixedClassGroupEntries as $classGroupId => $classGroup) { self::processClassesRecursively($classGroup, $classMap, $classGroupId, $theme); } return $classMap; } /** * @param array<string, mixed> $classGroupEntries * @return array<string, mixed> */ private static function getPrefixedClassGroupEntries(array $classGroupEntries, ?string $prefix): array { if (! $prefix) { return $classGroupEntries; } // @phpstan-ignore-next-line return Collection::make($classGroupEntries)->mapWithKeys(function (array $classGroup, string $classGroupId) use ($prefix): array { $prefixedClassGroup = Collection::make($classGroup)->map(function (string|array $classDefinition) use ($prefix): string|array { if (is_string($classDefinition)) { return $prefix.$classDefinition; } if (is_array($classDefinition)) { return Collection::make($classDefinition)->mapWithKeys(fn (array $value, string $key): array => [$prefix.$key => $value])->all(); } // return $classDefinition; })->all(); return [$classGroupId => $prefixedClassGroup]; })->all(); } public static function processClassesRecursively(array $classGroup, ClassPartObject $classPartObject, string $classGroupId, array $theme): void { foreach ($classGroup as $classDefinition) { if (is_string($classDefinition)) { $classPartObjectToEdit = $classDefinition === '' ? $classPartObject : self::getPart($classPartObject, $classDefinition); $classPartObjectToEdit->classGroupId = $classGroupId; continue; } if (self::isThemeGetter($classDefinition)) { self::processClassesRecursively( $classDefinition->get($theme), $classPartObject, $classGroupId, $theme, ); continue; } if (is_callable($classDefinition)) { $classPartObject->validators[] = new ClassValidatorObject( classGroupId: $classGroupId, validator: $classDefinition, ); continue; } foreach ($classDefinition as $key => $classGroup) { self::processClassesRecursively( $classGroup, self::getPart($classPartObject, $key), $classGroupId, $theme, ); } } } private static function isThemeGetter(ThemeGetter|array|callable $classDefinition): bool { return $classDefinition instanceof ThemeGetter; } private static function getPart(ClassPartObject $classPartObject, string $path): ClassPartObject { $currentClassPartObject = $classPartObject; foreach (explode(self::CLASS_PART_SEPARATOR, $path) as $pathPart) { if (! isset($currentClassPartObject->nextPart[$pathPart])) { $currentClassPartObject->nextPart[$pathPart] = new ClassPartObject(); } $currentClassPartObject = $currentClassPartObject->nextPart[$pathPart]; } return $currentClassPartObject; } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Support/Arr.php
src/Support/Arr.php
<?php namespace TailwindMerge\Support; class Arr { /** * @param array<array-key, mixed> $array * @return array<int, mixed> */ public static function flatten(array $array, int $depth = PHP_INT_MAX): array { $result = []; foreach ($array as $item) { $item = $item instanceof Collection ? $item->all() : $item; if (! is_array($item)) { $result[] = $item; } else { $values = $depth === 1 ? array_values($item) : static::flatten($item, $depth - 1); foreach ($values as $value) { $result[] = $value; } } } return $result; } /** * @template TKey * @template TValue * @template TMapWithKeysKey of array-key * @template TMapWithKeysValue * * @param array<TKey, TValue> $array * @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback * @return array<TMapWithKeysKey, TMapWithKeysValue> */ public static function mapWithKeys(array $array, callable $callback): array { $result = []; foreach ($array as $key => $value) { $assoc = $callback($value, $key); foreach ($assoc as $mapKey => $mapValue) { $result[$mapKey] = $mapValue; } } return $result; } /** * @template TKey * @template TValue * @template TMapValue * * @param array<TKey, TValue> $array * @param callable(TValue, TKey): TMapValue $callback * @return array<TKey, TMapValue> */ public static function map(array $array, callable $callback): array { $keys = array_keys($array); $items = array_map($callback, $array, $keys); return array_combine($keys, $items); } /** * @template TKey * @template TValue * * @param array<TKey, TValue> $array * @param callable(TValue, TKey): bool $callback * @return ?TValue */ public static function first(array $array, callable $callback): mixed { foreach ($array as $key => $value) { if ($callback($value, $key)) { return $value; } } return null; } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Support/TailwindClassParser.php
src/Support/TailwindClassParser.php
<?php namespace TailwindMerge\Support; use TailwindMerge\ValueObjects\ClassPartObject; use TailwindMerge\ValueObjects\ClassValidatorObject; use TailwindMerge\ValueObjects\ParsedClass; class TailwindClassParser { final public const CLASS_PART_SEPARATOR = '-'; final public const ARBITRARY_PROPERTY_REGEX = '/^\[(.+)\]$/'; final public const IMPORTANT_MODIFIER = '!'; private readonly ClassPartObject $classMap; /** * @param array{cacheSize: int, prefix: ?string, theme: array<string, mixed>, classGroups: array<string, mixed>,conflictingClassGroups: array<string, array<int, string>>, conflictingClassGroupModifiers: array<string, array<int, string>>} $config */ public function __construct(array $configuration) { $this->classMap = ClassMap::create($configuration); } /** * @param array<array-key, string> $classParts */ private static function getGroupRecursive(array $classParts, ClassPartObject $classPartObject): ?string { if ($classParts === []) { return $classPartObject->classGroupId; } $currentClassPart = $classParts[0] ?? null; $nextClassPartObject = $classPartObject->nextPart[$currentClassPart] ?? null; $classGroupFromNextClassPart = $nextClassPartObject !== null ? self::getGroupRecursive(array_slice($classParts, 1), $nextClassPartObject) : null; if ($classGroupFromNextClassPart) { return $classGroupFromNextClassPart; } if ($classPartObject->validators === []) { return null; } $classRest = implode(self::CLASS_PART_SEPARATOR, $classParts); return Collection::make($classPartObject->validators)->first(fn (ClassValidatorObject $validator) => ($validator->validator)($classRest))?->classGroupId; } public function parse(string $class): ParsedClass { [ 'modifiers' => $modifiers, 'hasImportantModifier' => $hasImportantModifier, 'baseClassName' => $baseClassName, 'maybePostfixModifierPosition' => $maybePostfixModifierPosition ] = $this->splitModifiers($class); $classGroupId = $this->getClassGroupId($maybePostfixModifierPosition ? Str::substr($baseClassName, 0, $maybePostfixModifierPosition) : $baseClassName); $hasPostfixModifier = $maybePostfixModifierPosition !== null; // TODO // if (!classGroupId) { // if (!maybePostfixModifierPosition) { // return { // isTailwindClass: false as const, // originalClassName, // } // } // // classGroupId = getClassGroupId(baseClassName) // // if (!classGroupId) { // return { // isTailwindClass: false as const, // originalClassName, // } // } // // hasPostfixModifier = false // } $variantModifier = implode(':', $this->sortModifiers($modifiers)); $modifierId = $hasImportantModifier ? $variantModifier.self::IMPORTANT_MODIFIER : $variantModifier; return new ParsedClass( modifiers: $modifiers, hasImportantModifier: $hasImportantModifier, hasPostfixModifier: $hasPostfixModifier, modifierId: $modifierId, classGroupId: $classGroupId, baseClassName: $baseClassName, originalClassName: $class, ); } private function getClassGroupId(string $class): string { $classParts = explode(self::CLASS_PART_SEPARATOR, $class); // Classes like `-inset-1` produce an empty string as first classPart. We assume that classes for negative values are used correctly and remove it from classParts. if ($classParts[0] === '' && count($classParts) !== 1) { array_shift($classParts); } return self::getGroupRecursive($classParts, $this->classMap) ?: $this->getGroupIdForArbitraryProperty($class); } private function getGroupIdForArbitraryProperty(string $className): string { if (Str::match(self::ARBITRARY_PROPERTY_REGEX, $className) !== '' && Str::match(self::ARBITRARY_PROPERTY_REGEX, $className) !== '0') { $arbitraryPropertyClassName = Str::match(self::ARBITRARY_PROPERTY_REGEX, $className); $property = Str::before($arbitraryPropertyClassName, ':'); if ($property !== '' && $property !== '0') { // I use two dots here because one dot is used as prefix for class groups in plugins return 'arbitrary..'.$property; } } // TODO: not sure here return $className; } /** * @return array{modifiers: array<array-key, string>, hasImportantModifier: bool, baseClassName: string, maybePostfixModifierPosition: int|null} */ private function splitModifiers(string $className): array { $separator = isset(Config::getMergedConfig()['separator']) && is_string(Config::getMergedConfig()['separator']) ? Config::getMergedConfig()['separator'] : ':'; $isSeparatorSingleCharacter = strlen($separator) === 1; $firstSeparatorCharacter = $separator[0]; $separatorLength = strlen($separator); $modifiers = []; $bracketDepth = 0; $modifierStart = 0; $postfixModifierPosition = null; for ($index = 0; $index < strlen($className); $index++) { $currentCharacter = $className[$index]; if ($bracketDepth === 0) { if ( $currentCharacter === $firstSeparatorCharacter && ($isSeparatorSingleCharacter || Str::substr($className, $index, $separatorLength) === $separator) ) { $modifiers[] = Str::substr($className, $modifierStart, $index - $modifierStart); $modifierStart = $index + $separatorLength; continue; } if ($currentCharacter === '/') { $postfixModifierPosition = $index; continue; } } if ($currentCharacter === '[') { $bracketDepth++; } elseif ($currentCharacter === ']') { $bracketDepth--; } } $baseClassNameWithImportantModifier = $modifiers === [] ? $className : Str::substr($className, $modifierStart); $hasImportantModifier = Str::startsWith($baseClassNameWithImportantModifier, self::IMPORTANT_MODIFIER); $baseClassName = $hasImportantModifier ? Str::substr($baseClassNameWithImportantModifier, 1) : $baseClassNameWithImportantModifier; $maybePostfixModifierPosition = $postfixModifierPosition && $postfixModifierPosition > $modifierStart ? $postfixModifierPosition - $modifierStart : null; return [ 'modifiers' => $modifiers, 'hasImportantModifier' => $hasImportantModifier, 'baseClassName' => $baseClassName, 'maybePostfixModifierPosition' => $maybePostfixModifierPosition, ]; } /** * @param array<array-key, string> $modifiers * @return array<array-key, string> */ private function sortModifiers(array $modifiers): array { if (count($modifiers) <= 1) { return $modifiers; } /** * @var Collection<array-key, string> $sortedModifiers */ $sortedModifiers = Collection::make(); $unsortedModifiers = Collection::make(); foreach ($modifiers as $modifier) { $isArbitraryVariant = $modifier[0] === '['; if ($isArbitraryVariant) { $sortedModifiers = $sortedModifiers->concat([...$unsortedModifiers->sort()->all(), $modifier]); $unsortedModifiers = Collection::make(); } else { $unsortedModifiers->add($modifier); } } $sortedModifiers = $sortedModifiers->concat($unsortedModifiers->sort()); return $sortedModifiers->all(); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Support/Config.php
src/Support/Config.php
<?php namespace TailwindMerge\Support; use TailwindMerge\Validators\AnyValueValidator; use TailwindMerge\Validators\ArbitraryImageValidator; use TailwindMerge\Validators\ArbitraryLengthValidator; use TailwindMerge\Validators\ArbitraryNumberValidator; use TailwindMerge\Validators\ArbitraryPositionValidator; use TailwindMerge\Validators\ArbitraryShadowValidator; use TailwindMerge\Validators\ArbitrarySizeValidator; use TailwindMerge\Validators\ArbitraryValueValidator; use TailwindMerge\Validators\IntegerValidator; use TailwindMerge\Validators\LengthValidator; use TailwindMerge\Validators\NumberValidator; use TailwindMerge\Validators\PercentValidator; use TailwindMerge\Validators\TshirtSizeValidator; use TailwindMerge\ValueObjects\ThemeGetter; class Config { /** * @var array<string, mixed> */ private static array $additionalConfig = []; /** * @return array<string, mixed> */ public static function getMergedConfig(): array { $config = self::getDefaultConfig(); foreach (self::$additionalConfig as $key => $additionalConfig) { $config[$key] = self::mergePropertyRecursively($config, $key, $additionalConfig); } return $config; } private static function mergePropertyRecursively(array $baseConfig, string $mergeKey, array|bool|float|int|string|null $mergeValue): array|bool|float|int|string|null { if (! array_key_exists($mergeKey, $baseConfig)) { return $mergeValue; } if (is_string($mergeValue)) { return $mergeValue; } if (is_numeric($mergeValue)) { return $mergeValue; } if (is_bool($mergeValue)) { return $mergeValue; } if ($mergeValue === null) { return $mergeValue; } if (is_array($mergeValue) && array_is_list($mergeValue) && is_array($baseConfig[$mergeKey]) && array_is_list($baseConfig[$mergeKey])) { return [...$baseConfig[$mergeKey], ...$mergeValue]; } if (is_array($mergeValue) && ! array_is_list($mergeValue) /* && is_array($baseConfig[$mergeKey]) && array_is_list($baseConfig[$mergeKey]) */) { if ($baseConfig[$mergeKey] === null) { return $mergeValue; } foreach ($mergeValue as $key => $value) { $baseConfig[$mergeKey][$key] = self::mergePropertyRecursively($baseConfig[$mergeKey], $key, $value); } } return $baseConfig[$mergeKey]; } /** * @param array<string, mixed> $config */ public static function setAdditionalConfig(array $config): void { self::$additionalConfig = $config; } /** * @return array{cacheSize: int, prefix: ?string, theme: array<string, mixed>, classGroups: array<string, mixed>,conflictingClassGroups: array<string, array<int, string>>, conflictingClassGroupModifiers: array<string, array<int, string>>} */ public static function getDefaultConfig(): array { $colors = self::fromTheme('colors'); $spacing = self::fromTheme('spacing'); $blur = self::fromTheme('blur'); $brightness = self::fromTheme('brightness'); $borderColor = self::fromTheme('borderColor'); $borderRadius = self::fromTheme('borderRadius'); $borderSpacing = self::fromTheme('borderSpacing'); $borderWidth = self::fromTheme('borderWidth'); $contrast = self::fromTheme('contrast'); $grayscale = self::fromTheme('grayscale'); $hueRotate = self::fromTheme('hueRotate'); $invert = self::fromTheme('invert'); $gap = self::fromTheme('gap'); $gradientColorStops = self::fromTheme('gradientColorStops'); $gradientColorStopPositions = self::fromTheme('gradientColorStopPositions'); $inset = self::fromTheme('inset'); $margin = self::fromTheme('margin'); $opacity = self::fromTheme('opacity'); $padding = self::fromTheme('padding'); $saturate = self::fromTheme('saturate'); $scale = self::fromTheme('scale'); $sepia = self::fromTheme('sepia'); $skew = self::fromTheme('skew'); $space = self::fromTheme('space'); $translate = self::fromTheme('translate'); return [ 'cacheSize' => 500, 'prefix' => null, 'theme' => [ 'colors' => [AnyValueValidator::validate(...)], 'spacing' => [LengthValidator::validate(...), ArbitraryLengthValidator::validate(...)], 'blur' => ['none', '', TshirtSizeValidator::validate(...), ArbitraryValueValidator::validate(...)], 'brightness' => self::getNumber(), 'borderColor' => [$colors], 'borderRadius' => ['none', '', 'full', TshirtSizeValidator::validate(...), ArbitraryValueValidator::validate(...)], 'borderSpacing' => self::getSpacingWithArbitrary($spacing), 'borderWidth' => self::getLengthWithEmptyAndArbitrary(), 'contrast' => self::getNumber(), 'grayscale' => self::getZeroAndEmpty(), 'hueRotate' => self::getNumberAndArbitrary(), 'invert' => self::getZeroAndEmpty(), 'gap' => self::getSpacingWithArbitrary($spacing), 'gradientColorStops' => [$colors], 'gradientColorStopPositions' => [PercentValidator::validate(...), ArbitraryLengthValidator::validate(...)], 'inset' => self::getSpacingWithAutoAndArbitrary($spacing), 'margin' => self::getSpacingWithAutoAndArbitrary($spacing), 'opacity' => self::getNumber(), 'padding' => self::getSpacingWithArbitrary($spacing), 'saturate' => self::getNumber(), 'scale' => self::getNumber(), 'sepia' => self::getZeroAndEmpty(), 'skew' => self::getNumberAndArbitrary(), 'space' => self::getSpacingWithArbitrary($spacing), 'translate' => self::getSpacingWithArbitrary($spacing), ], 'classGroups' => [ // Layout /** * Aspect Ratio * * @see https://tailwindcss.com/docs/aspect-ratio */ 'aspect' => [['aspect' => ['auto', 'square', 'video', ArbitraryValueValidator::validate(...)]]], /** * Container * * @see https://tailwindcss.com/docs/container */ 'container' => ['container'], /** * Columns * * @see https://tailwindcss.com/docs/columns */ 'columns' => [['columns' => [TshirtSizeValidator::validate(...)]]], /** * Break After * * @see https://tailwindcss.com/docs/break-after */ 'break-after' => [['break-after' => self::getBreaks()]], /** * Break Before * * @see https://tailwindcss.com/docs/break-before */ 'break-before' => [['break-before' => self::getBreaks()]], /** * Break Inside * * @see https://tailwindcss.com/docs/break-inside */ 'break-inside' => [['break-inside' => ['auto', 'avoid', 'avoid-page', 'avoid-column']]], /** * Box Decoration Break * * @see https://tailwindcss.com/docs/box-decoration-break */ 'box-decoration' => [['box-decoration' => ['slice', 'clone']]], /** * Box Sizing * * @see https://tailwindcss.com/docs/box-sizing */ 'box' => [['box' => ['border', 'content']]], /** * Display * * @see https://tailwindcss.com/docs/display */ 'display' => [ 'block', 'inline-block', 'inline', 'flex', 'inline-flex', 'table', 'inline-table', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row-group', 'table-row', 'flow-root', 'grid', 'inline-grid', 'contents', 'list-item', 'hidden', ], /** * Floats * * @see https://tailwindcss.com/docs/float */ 'float' => [['float' => ['right', 'left', 'none', 'start', 'end']]], /** * Clear * * @see https://tailwindcss.com/docs/clear */ 'clear' => [['clear' => ['left', 'right', 'both', 'none', 'start', 'end']]], /** * Isolation * * @see https://tailwindcss.com/docs/isolation */ 'isolation' => ['isolate', 'isolation-auto'], /** * Object Fit * * @see https://tailwindcss.com/docs/object-fit */ 'object-fit' => [['object' => ['contain', 'cover', 'fill', 'none', 'scale-down']]], /** * Object Position * * @see https://tailwindcss.com/docs/object-position */ 'object-position' => [['object' => [...self::getPositions(), ArbitraryValueValidator::validate(...)]]], /** * Overflow * * @see https://tailwindcss.com/docs/overflow */ 'overflow' => [['overflow' => self::getOverflow()]], /** * Overflow X * * @see https://tailwindcss.com/docs/overflow */ 'overflow-x' => [['overflow-x' => self::getOverflow()]], /** * Overflow Y * * @see https://tailwindcss.com/docs/overflow */ 'overflow-y' => [['overflow-y' => self::getOverflow()]], /** * Overscroll Behavior * * @see https://tailwindcss.com/docs/overscroll-behavior */ 'overscroll' => [['overscroll' => self::getOverscroll()]], /** * Overscroll Behavior X * * @see https://tailwindcss.com/docs/overscroll-behavior */ 'overscroll-x' => [['overscroll-x' => self::getOverscroll()]], /** * Overscroll Behavior Y * * @see https://tailwindcss.com/docs/overscroll-behavior */ 'overscroll-y' => [['overscroll-y' => self::getOverscroll()]], /** * Position * * @see https://tailwindcss.com/docs/position */ 'position' => ['static', 'fixed', 'absolute', 'relative', 'sticky'], /** * Top / Right / Bottom / Left * * @see https://tailwindcss.com/docs/top-right-bottom-left */ 'inset' => [['inset' => [$inset]]], /** * Right / Left * * @see https://tailwindcss.com/docs/top-right-bottom-left */ 'inset-x' => [['inset-x' => [$inset]]], /** * Top / Bottom * * @see https://tailwindcss.com/docs/top-right-bottom-left */ 'inset-y' => [['inset-y' => [$inset]]], /** * Start * * @see https://tailwindcss.com/docs/top-right-bottom-left */ 'start' => [['start' => [$inset]]], /** * End * * @see https://tailwindcss.com/docs/top-right-bottom-left */ 'end' => [['end' => [$inset]]], /** * Top * * @see https://tailwindcss.com/docs/top-right-bottom-left */ 'top' => [['top' => [$inset]]], /** * Right * * @see https://tailwindcss.com/docs/top-right-bottom-left */ 'right' => [['right' => [$inset]]], /** * Bottom * * @see https://tailwindcss.com/docs/top-right-bottom-left */ 'bottom' => [['bottom' => [$inset]]], /** * Left * * @see https://tailwindcss.com/docs/top-right-bottom-left */ 'left' => [['left' => [$inset]]], /** * Visibility * * @see https://tailwindcss.com/docs/visibility */ 'visibility' => ['visible', 'invisible', 'collapse'], /** * Z-Index * * @see https://tailwindcss.com/docs/z-index */ 'z' => [['z' => ['auto', IntegerValidator::validate(...), ArbitraryValueValidator::validate(...)]]], // Flexbox and Grid /** * Flex Basis * * @see https://tailwindcss.com/docs/flex-basis */ 'basis' => [['basis' => self::getSpacingWithAutoAndArbitrary($space)]], /** * Flex Direction * * @see https://tailwindcss.com/docs/flex-direction */ 'flex-direction' => [['flex' => ['row', 'row-reverse', 'col', 'col-reverse']]], /** * Flex Wrap * * @see https://tailwindcss.com/docs/flex-wrap */ 'flex-wrap' => [['flex' => ['wrap', 'wrap-reverse', 'nowrap']]], /** * Flex * * @see https://tailwindcss.com/docs/flex */ 'flex' => [['flex' => ['1', 'auto', 'initial', 'none', ArbitraryValueValidator::validate(...)]]], /** * Flex Grow * * @see https://tailwindcss.com/docs/flex-grow */ 'grow' => [['grow' => self::getZeroAndEmpty()]], /** * Flex Shrink * * @see https://tailwindcss.com/docs/flex-shrink */ 'shrink' => [['shrink' => self::getZeroAndEmpty()]], /** * Order * * @see https://tailwindcss.com/docs/order */ 'order' => [['order' => ['first', 'last', 'none', IntegerValidator::validate(...), ArbitraryValueValidator::validate(...)]]], /** * Grid Template Columns * * @see https://tailwindcss.com/docs/grid-template-columns */ 'grid-cols' => [['grid-cols' => [AnyValueValidator::validate(...)]]], /** * Grid Column Start / End * * @see https://tailwindcss.com/docs/grid-column */ 'col-start-end' => [['col' => ['auto', ['span' => ['full', IntegerValidator::validate(...), ArbitraryValueValidator::validate(...)]], ArbitraryValueValidator::validate(...)]]], /** * Grid Column Start * * @see https://tailwindcss.com/docs/grid-column */ 'col-start' => [['col-start' => self::getNumberWithAutoAndArbitrary()]], /** * Grid Column End * * @see https://tailwindcss.com/docs/grid-column */ 'col-end' => [['col-end' => self::getNumberWithAutoAndArbitrary()]], /** * Grid Template Rows * * @see https://tailwindcss.com/docs/grid-template-rows */ 'grid-rows' => [['grid-rows' => [AnyValueValidator::validate(...)]]], /** * Grid Row Start / End * * @see https://tailwindcss.com/docs/grid-row */ 'row-start-end' => [['row' => ['auto', ['span' => [IntegerValidator::validate(...), ArbitraryValueValidator::validate(...)]], ArbitraryValueValidator::validate(...)]]], /** * Grid Row Start * * @see https://tailwindcss.com/docs/grid-row */ 'row-start' => [['row-start' => self::getNumberWithAutoAndArbitrary()]], /** * Grid Row End * * @see https://tailwindcss.com/docs/grid-row */ 'row-end' => [['row-end' => self::getNumberWithAutoAndArbitrary()]], /** * Grid Auto Flow * * @see https://tailwindcss.com/docs/grid-auto-flow */ 'grid-flow' => [['grid-flow' => ['row', 'col', 'dense', 'row-dense', 'col-dense']]], /** * Grid Auto Columns * * @see https://tailwindcss.com/docs/grid-auto-columns */ 'auto-cols' => [['auto-cols' => ['auto', 'min', 'max', 'fr', ArbitraryValueValidator::validate(...)]]], /** * Grid Auto Rows * * @see https://tailwindcss.com/docs/grid-auto-rows */ 'auto-rows' => [['auto-rows' => ['auto', 'min', 'max', 'fr', ArbitraryValueValidator::validate(...)]]], /** * Gap * * @see https://tailwindcss.com/docs/gap */ 'gap' => [['gap' => [$gap]]], /** * Gap X * * @see https://tailwindcss.com/docs/gap */ 'gap-x' => [['gap-x' => [$gap]]], /** * Gap Y * * @see https://tailwindcss.com/docs/gap */ 'gap-y' => [['gap-y' => [$gap]]], /** * Justify Content * * @see https://tailwindcss.com/docs/justify-content */ 'justify-content' => [['justify' => ['normal', ...self::getAlign()]]], /** * Justify Items * * @see https://tailwindcss.com/docs/justify-items */ 'justify-items' => [['justify-items' => ['start', 'end', 'center', 'stretch']]], /** * Justify Self * * @see https://tailwindcss.com/docs/justify-self */ 'justify-self' => [['justify-self' => ['auto', 'start', 'end', 'center', 'stretch']]], /** * Align Content * * @see https://tailwindcss.com/docs/align-content */ 'align-content' => [['content' => ['normal', ...self::getAlign(), 'baseline']]], /** * Align Items * * @see https://tailwindcss.com/docs/align-items */ 'align-items' => [['items' => ['start', 'end', 'center', 'baseline', 'stretch']]], /** * Align Self * * @see https://tailwindcss.com/docs/align-self */ 'align-self' => [['self' => ['auto', 'start', 'end', 'center', 'stretch', 'baseline']]], /** * Place Content * * @see https://tailwindcss.com/docs/place-content */ 'place-content' => [['place-content' => [...self::getAlign(), 'baseline']]], /** * Place Items * * @see https://tailwindcss.com/docs/place-items */ 'place-items' => [['place-items' => ['start', 'end', 'center', 'baseline', 'stretch']]], /** * Place Self * * @see https://tailwindcss.com/docs/place-self */ 'place-self' => [['place-self' => ['auto', 'start', 'end', 'center', 'stretch']]], // Spacing /** * Padding * * @see https://tailwindcss.com/docs/padding */ 'p' => [['p' => [$padding]]], /** * Padding X * * @see https://tailwindcss.com/docs/padding */ 'px' => [['px' => [$padding]]], /** * Padding Y * * @see https://tailwindcss.com/docs/padding */ 'py' => [['py' => [$padding]]], /** * Padding Start * * @see https://tailwindcss.com/docs/padding */ 'ps' => [['ps' => [$padding]]], /** * Padding End * * @see https://tailwindcss.com/docs/padding */ 'pe' => [['pe' => [$padding]]], /** * Padding Top * * @see https://tailwindcss.com/docs/padding */ 'pt' => [['pt' => [$padding]]], /** * Padding Right * * @see https://tailwindcss.com/docs/padding */ 'pr' => [['pr' => [$padding]]], /** * Padding Bottom * * @see https://tailwindcss.com/docs/padding */ 'pb' => [['pb' => [$padding]]], /** * Padding Left * * @see https://tailwindcss.com/docs/padding */ 'pl' => [['pl' => [$padding]]], /** * Margin * * @see https://tailwindcss.com/docs/margin */ 'm' => [['m' => [$margin]]], /** * Margin X * * @see https://tailwindcss.com/docs/margin */ 'mx' => [['mx' => [$margin]]], /** * Margin Y * * @see https://tailwindcss.com/docs/margin */ 'my' => [['my' => [$margin]]], /** * Margin Start * * @see https://tailwindcss.com/docs/margin */ 'ms' => [['ms' => [$margin]]], /** * Margin End * * @see https://tailwindcss.com/docs/margin */ 'me' => [['me' => [$margin]]], /** * Margin Top * * @see https://tailwindcss.com/docs/margin */ 'mt' => [['mt' => [$margin]]], /** * Margin Right * * @see https://tailwindcss.com/docs/margin */ 'mr' => [['mr' => [$margin]]], /** * Margin Bottom * * @see https://tailwindcss.com/docs/margin */ 'mb' => [['mb' => [$margin]]], /** * Margin Left * * @see https://tailwindcss.com/docs/margin */ 'ml' => [['ml' => [$margin]]], /** * Space Between X * * @see https://tailwindcss.com/docs/space */ 'space-x' => [['space-x' => [$space]]], /** * Space Between X Reverse * * @see https://tailwindcss.com/docs/space */ 'space-x-reverse' => ['space-x-reverse'], /** * Space Between Y * * @see https://tailwindcss.com/docs/space */ 'space-y' => [['space-y' => [$space]]], /** * Space Between Y Reverse * * @see https://tailwindcss.com/docs/space */ 'space-y-reverse' => ['space-y-reverse'], // Sizing /** * Width * * @see https://tailwindcss.com/docs/width */ 'w' => [ [ 'w' => [ 'auto', 'min', 'max', 'fit', 'svw', 'lvw', 'dvw', ArbitraryValueValidator::validate(...), $spacing, ], ], ], /** * Min-Width * * @see https://tailwindcss.com/docs/min-width */ 'min-w' => [['min-w' => ['min', 'max', 'fit', ArbitraryValueValidator::validate(...), LengthValidator::validate(...)]]], /** * Max-Width * * @see https://tailwindcss.com/docs/max-width */ 'max-w' => [ [ 'max-w' => [ ArbitraryValueValidator::validate(...), $spacing, 'none', 'full', 'min', 'max', 'fit', 'prose', ['screen' => [TshirtSizeValidator::validate(...)]], TshirtSizeValidator::validate(...), ], ], ], /** * Height * * @see https://tailwindcss.com/docs/height */ 'h' => [ [ 'h' => [ ArbitraryValueValidator::validate(...), $spacing, 'auto', 'min', 'max', 'fit', 'svh', 'lvh', 'dvh', ], ], ], /** * Min-Height * * @see https://tailwindcss.com/docs/min-height */ 'min-h' => [ ['min-h' => [ArbitraryValueValidator::validate(...), $spacing, 'min', 'max', 'fit', 'svh', 'lvh', 'dvh']], ], /** * Max-Height * * @see https://tailwindcss.com/docs/max-height */ 'max-h' => [ ['max-h' => [ArbitraryValueValidator::validate(...), $spacing, 'min', 'max', 'fit', 'svh', 'lvh', 'dvh']], ], /** * Size * * @see https://tailwindcss.com/docs/size */ 'size' => [['size' => [ArbitraryValueValidator::validate(...), $spacing, 'auto', 'min', 'max', 'fit']]], // Typography /** * Font Size * * @see https://tailwindcss.com/docs/font-size */ 'font-size' => [['text' => ['base', TshirtSizeValidator::validate(...), ArbitraryLengthValidator::validate(...)]]], /** * Font Smoothing * * @see https://tailwindcss.com/docs/font-smoothing */ 'font-smoothing' => ['antialiased', 'subpixel-antialiased'], /** * Font Style * * @see https://tailwindcss.com/docs/font-style */ 'font-style' => ['italic', 'not-italic'], /** * Font Weight * * @see https://tailwindcss.com/docs/font-weight */ 'font-weight' => [ [ 'font' => [ 'thin', 'extralight', 'light', 'normal', 'medium', 'semibold', 'bold', 'extrabold', 'black', ArbitraryNumberValidator::validate(...), ], ], ], /** * Font Family * * @see https://tailwindcss.com/docs/font-family */ 'font-family' => [['font' => [AnyValueValidator::validate(...)]]], /** * Font Variant Numeric * * @see https://tailwindcss.com/docs/font-variant-numeric */ 'fvn-normal' => ['normal-nums'], /** * Font Variant Numeric * * @see https://tailwindcss.com/docs/font-variant-numeric */ 'fvn-ordinal' => ['ordinal'], /** * Font Variant Numeric * * @see https://tailwindcss.com/docs/font-variant-numeric */ 'fvn-slashed-zero' => ['slashed-zero'], /** * Font Variant Numeric * * @see https://tailwindcss.com/docs/font-variant-numeric */ 'fvn-figure' => ['lining-nums', 'oldstyle-nums'], /** * Font Variant Numeric * * @see https://tailwindcss.com/docs/font-variant-numeric */ 'fvn-spacing' => ['proportional-nums', 'tabular-nums'], /** * Font Variant Numeric * * @see https://tailwindcss.com/docs/font-variant-numeric */
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
true
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Support/Str.php
src/Support/Str.php
<?php namespace TailwindMerge\Support; class Str { public static function hasMatch(string $pattern, string $value): bool { return preg_match($pattern, $value) === 1; } public static function of(string $string): Stringable { return new Stringable($string); } public static function startsWith(string $haystack, string $needle): bool { return str_starts_with($haystack, $needle); } public static function match(string $pattern, string $subject): string { preg_match($pattern, $subject, $matches); if ($matches === []) { return ''; } return $matches[1] ?? $matches[0]; } public static function before(string $subject, string $search): string { if ($search === '') { return $subject; } $result = strstr($subject, $search, true); return $result === false ? $subject : $result; } public static function substr(string $string, int $start, ?int $length = null, string $encoding = 'UTF-8'): string { return mb_substr($string, $start, $length, $encoding); } public static function endsWith(string $haystack, string $needle): bool { return str_ends_with($haystack, $needle); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Support/Stringable.php
src/Support/Stringable.php
<?php namespace TailwindMerge\Support; class Stringable { public function __construct(protected string $value) { } public function trim(string $characters = ' '): self { return new self(trim($this->value, $characters)); } /** * @return Collection<int, string> */ public function split(string $pattern, int $limit = -1, int $flags = 0): Collection { $segments = preg_split($pattern, $this->value, $limit, $flags); return $segments === [] || $segments === false ? Collection::make() : Collection::make($segments); } public function substr(int $start, ?int $length = null, string $encoding = 'UTF-8'): self { return new self(Str::substr($this->value, $start, $length, $encoding)); } public function toString(): string { return $this->value; } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Contracts/TailwindMergeContract.php
src/Contracts/TailwindMergeContract.php
<?php namespace TailwindMerge\Contracts; interface TailwindMergeContract { /** * @param string|array<array-key, string|array<array-key, string>> ...$args */ public function merge(...$args): string; }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Contracts/ValidatorContract.php
src/Contracts/ValidatorContract.php
<?php namespace TailwindMerge\Contracts; /** * @internal */ interface ValidatorContract { public static function validate(string $value): bool; }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/ValueObjects/ParsedClass.php
src/ValueObjects/ParsedClass.php
<?php namespace TailwindMerge\ValueObjects; class ParsedClass { /** * @param array<array-key, string> $modifiers */ public function __construct( public array $modifiers, public bool $hasImportantModifier, public bool $hasPostfixModifier, public string $modifierId, public string $classGroupId, public string $baseClassName, public string $originalClassName, ) { // } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/ValueObjects/ClassValidatorObject.php
src/ValueObjects/ClassValidatorObject.php
<?php namespace TailwindMerge\ValueObjects; use Closure; class ClassValidatorObject { public function __construct( public string $classGroupId, public Closure $validator, ) { } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/ValueObjects/ThemeGetter.php
src/ValueObjects/ThemeGetter.php
<?php namespace TailwindMerge\ValueObjects; class ThemeGetter { public function __construct( public string $key ) { } /** * @param array<string, array<string, mixed>> $theme * @return array<string, mixed> */ public function get(array $theme): array { return $theme[$this->key] ?? []; } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/ValueObjects/ClassPartObject.php
src/ValueObjects/ClassPartObject.php
<?php namespace TailwindMerge\ValueObjects; class ClassPartObject { /** * @param array<array-key, ClassPartObject> $nextPart * @param array<array-key, ClassValidatorObject> $validators */ public function __construct( public array $nextPart = [], public array $validators = [], public ?string $classGroupId = null, ) { } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/ArbitraryShadowValidator.php
src/Validators/ArbitraryShadowValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Support\Str; use TailwindMerge\Validators\Concerns\ValidatesArbitraryValue; /** * @internal */ class ArbitraryShadowValidator implements \TailwindMerge\Contracts\ValidatorContract { use ValidatesArbitraryValue; final public const SHADOW_REGEX = '/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/'; public static function validate(string $value): bool { return self::getIsArbitraryValue($value, '', self::isShadow(...)); } private static function isShadow(string $value): bool { return Str::hasMatch(self::SHADOW_REGEX, $value); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/PercentValidator.php
src/Validators/PercentValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Support\Str; /** * @internal */ class PercentValidator implements \TailwindMerge\Contracts\ValidatorContract { public static function validate(string $value): bool { if (! Str::endsWith($value, '%')) { return false; } return NumberValidator::validate(Str::of($value)->substr(0, -1)->toString()); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/AnyValueValidator.php
src/Validators/AnyValueValidator.php
<?php namespace TailwindMerge\Validators; /** * @internal */ class AnyValueValidator implements \TailwindMerge\Contracts\ValidatorContract { public static function validate(string $value): bool { return true; } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/ArbitraryLengthValidator.php
src/Validators/ArbitraryLengthValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Support\Str; use TailwindMerge\Validators\Concerns\ValidatesArbitraryValue; /** * @internal */ class ArbitraryLengthValidator implements \TailwindMerge\Contracts\ValidatorContract { use ValidatesArbitraryValue; final public const LENGTH_UNIT_REGEX = '/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/'; public static function validate(string $value): bool { return self::getIsArbitraryValue($value, 'length', self::isLengthOnly(...)); } private static function isLengthOnly(string $value): bool { return Str::hasMatch(self::LENGTH_UNIT_REGEX, $value); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/LengthValidator.php
src/Validators/LengthValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Support\Collection; use TailwindMerge\Support\Str; /** * @internal */ class LengthValidator implements \TailwindMerge\Contracts\ValidatorContract { final public const FRACTION_REGEX = '/^\d+\/\d+$/'; public static function validate(string $value): bool { if (NumberValidator::validate($value)) { return true; } if (self::stringLengths()->contains($value)) { return true; } return Str::hasMatch(self::FRACTION_REGEX, $value); } /** * @return Collection<int, string> */ private static function stringLengths(): Collection { return Collection::make(['px', 'full', 'screen']); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/ArbitraryNumberValidator.php
src/Validators/ArbitraryNumberValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Validators\Concerns\ValidatesArbitraryValue; /** * @internal */ class ArbitraryNumberValidator implements \TailwindMerge\Contracts\ValidatorContract { use ValidatesArbitraryValue; public static function validate(string $value): bool { return self::getIsArbitraryValue($value, 'number', NumberValidator::validate(...)); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/TshirtSizeValidator.php
src/Validators/TshirtSizeValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Support\Str; /** * @internal */ class TshirtSizeValidator implements \TailwindMerge\Contracts\ValidatorContract { final public const T_SHIRT_UNIT_REGEX = '/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/'; public static function validate(string $value): bool { return Str::hasMatch(self::T_SHIRT_UNIT_REGEX, $value); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/ArbitraryPositionValidator.php
src/Validators/ArbitraryPositionValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Validators\Concerns\ValidatesArbitraryValue; /** * @internal */ class ArbitraryPositionValidator implements \TailwindMerge\Contracts\ValidatorContract { use ValidatesArbitraryValue; public static function validate(string $value): bool { return self::getIsArbitraryValue($value, 'position', fn (): bool => false); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/NumberValidator.php
src/Validators/NumberValidator.php
<?php namespace TailwindMerge\Validators; /** * @internal */ class NumberValidator implements \TailwindMerge\Contracts\ValidatorContract { public static function validate(string $value): bool { return is_numeric($value); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/ArbitraryValueValidator.php
src/Validators/ArbitraryValueValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Support\Str; /** * @internal */ class ArbitraryValueValidator implements \TailwindMerge\Contracts\ValidatorContract { final public const ARBITRARY_VALUE_REGEX = '/^\[(?:([a-z-]+):)?(.+)\]$/i'; public static function validate(string $value): bool { return Str::hasMatch(self::ARBITRARY_VALUE_REGEX, $value); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/ArbitrarySizeValidator.php
src/Validators/ArbitrarySizeValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Validators\Concerns\ValidatesArbitraryValue; /** * @internal */ class ArbitrarySizeValidator implements \TailwindMerge\Contracts\ValidatorContract { use ValidatesArbitraryValue; public static function validate(string $value): bool { return self::getIsArbitraryValue($value, ['length', 'size', 'percentage'], fn (): bool => false); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/ArbitraryImageValidator.php
src/Validators/ArbitraryImageValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Support\Str; use TailwindMerge\Validators\Concerns\ValidatesArbitraryValue; /** * @internal */ class ArbitraryImageValidator implements \TailwindMerge\Contracts\ValidatorContract { use ValidatesArbitraryValue; final public const IMAGE_REGEX = '/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/'; public static function validate(string $value): bool { return self::getIsArbitraryValue($value, ['image', 'url'], self::isImage(...)); } private static function isImage(string $value): bool { return Str::hasMatch(self::IMAGE_REGEX, $value); } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/IntegerValidator.php
src/Validators/IntegerValidator.php
<?php namespace TailwindMerge\Validators; use TailwindMerge\Validators\Concerns\ValidatesArbitraryValue; /** * @internal */ class IntegerValidator implements \TailwindMerge\Contracts\ValidatorContract { use ValidatesArbitraryValue; public static function validate(string $value): bool { return self::isIntegerOnly($value); } private static function isIntegerOnly(string $value): bool { return (string) (int) $value === $value; } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/src/Validators/Concerns/ValidatesArbitraryValue.php
src/Validators/Concerns/ValidatesArbitraryValue.php
<?php namespace TailwindMerge\Validators\Concerns; /** * @internal */ trait ValidatesArbitraryValue { /** * @param string|array<array-key, string> $labels */ protected static function getIsArbitraryValue(string $value, string|array $labels, callable $isLengthOnly): bool { $labels = is_string($labels) ? [$labels] : $labels; preg_match('/^\[(?:([a-z-]+):)?(.+)\]$/i', $value, $result); if ($result !== []) { if ($result[1] !== '' && $result[1] !== '0') { return in_array($result[1], $labels); } return $isLengthOnly($result[2] ?? null); } return false; } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Pest.php
tests/Pest.php
<?php
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/ClassGroupConflictsTest.php
tests/Feature/ClassGroupConflictsTest.php
<?php use TailwindMerge\TailwindMerge; it('merges classes from same group correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['overflow-x-auto overflow-x-hidden', 'overflow-x-hidden'], ['w-full w-fit', 'w-fit'], ['overflow-x-auto overflow-x-hidden overflow-x-scroll', 'overflow-x-scroll'], ['overflow-x-auto hover:overflow-x-hidden overflow-x-scroll', 'hover:overflow-x-hidden overflow-x-scroll'], ['overflow-x-auto hover:overflow-x-hidden hover:overflow-x-auto overflow-x-scroll', 'hover:overflow-x-auto overflow-x-scroll'], ['col-span-1 col-span-full', 'col-span-full'], ]); it('merges classes from Font Variant Numeric section correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['lining-nums tabular-nums diagonal-fractions', 'lining-nums tabular-nums diagonal-fractions'], ['normal-nums tabular-nums diagonal-fractions', 'tabular-nums diagonal-fractions'], ['tabular-nums diagonal-fractions normal-nums', 'normal-nums'], ['tabular-nums proportional-nums', 'proportional-nums'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/ColorsTest.php
tests/Feature/ColorsTest.php
<?php use TailwindMerge\TailwindMerge; it('handles color conflicts properly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['bg-grey-5 bg-hotpink', 'bg-hotpink'], ['hover:bg-grey-5 hover:bg-hotpink', 'hover:bg-hotpink'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/TailwindCssVersionsTest.php
tests/Feature/TailwindCssVersionsTest.php
<?php use TailwindMerge\TailwindMerge; it('supports Tailwind CSS v3.3 features', function (string|array $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['text-red text-lg/7 text-lg/8', 'text-red text-lg/8'], [[ 'start-0 start-1', 'end-0 end-1', 'ps-0 ps-1 pe-0 pe-1', 'ms-0 ms-1 me-0 me-1', 'rounded-s-sm rounded-s-md rounded-e-sm rounded-e-md', 'rounded-ss-sm rounded-ss-md rounded-ee-sm rounded-ee-md', ], 'start-1 end-1 ps-1 pe-1 ms-1 me-1 rounded-s-md rounded-e-md rounded-ss-md rounded-ee-md'], ['start-0 end-0 inset-0 ps-0 pe-0 p-0 ms-0 me-0 m-0 rounded-ss rounded-es rounded-s', 'inset-0 p-0 m-0 rounded-s'], ['hyphens-auto hyphens-manual', 'hyphens-manual'], ['from-0% from-10% from-[12.5%] via-0% via-10% via-[12.5%] to-0% to-10% to-[12.5%]', 'from-[12.5%] via-[12.5%] to-[12.5%]'], ['from-0% from-red', 'from-0% from-red'], ['list-image-none list-image-[url(./my-image.png)] list-image-[var(--value)]', 'list-image-[var(--value)]'], ['caption-top caption-bottom', 'caption-bottom'], ['line-clamp-2 line-clamp-none line-clamp-[10]', 'line-clamp-[10]'], ['delay-150 delay-0 duration-150 duration-0', 'delay-0 duration-0'], ['justify-normal justify-center justify-stretch', 'justify-stretch'], ['content-normal content-center content-stretch', 'content-stretch'], ['whitespace-nowrap whitespace-break-spaces', 'whitespace-break-spaces'], ]); it('supports Tailwind CSS v3.4 features', function (string|array $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['h-svh h-dvh w-svw w-dvw', 'h-dvh w-dvw'], ['has-[[data-potato]]:p-1 has-[[data-potato]]:p-2 group-has-[:checked]:grid group-has-[:checked]:flex', 'has-[[data-potato]]:p-2 group-has-[:checked]:flex'], ['text-wrap text-pretty', 'text-pretty'], ['w-5 h-3 size-10 w-12', 'size-10 w-12'], ['grid-cols-2 grid-cols-subgrid grid-rows-5 grid-rows-subgrid', 'grid-cols-subgrid grid-rows-subgrid'], ['min-w-0 min-w-50 min-w-px max-w-0 max-w-50 max-w-px', 'min-w-px max-w-px'], ['forced-color-adjust-none forced-color-adjust-auto', 'forced-color-adjust-auto'], ['appearance-none appearance-auto', 'appearance-auto'], ['float-start float-end clear-start clear-end', 'float-end clear-end'], ['*:p-10 *:p-20 hover:*:p-10 hover:*:p-20', '*:p-20 hover:*:p-20'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/CacheTest.php
tests/Feature/CacheTest.php
<?php use Psr\SimpleCache\CacheInterface; use TailwindMerge\TailwindMerge; it('does cache the result', function () { $cache = new FakeCache(); $twMerge = TailwindMerge::factory()->withCache($cache)->make(); expect($twMerge->merge('text-red-500 text-green-500')) ->toBe('text-green-500'); expect($cache) ->hits->toBe(0) ->misses->toBe(1); expect($twMerge->merge('text-red-500 text-green-500')) ->toBe('text-green-500'); expect($cache) ->hits->toBe(1) ->misses->toBe(1); expect($twMerge->merge('text-red-500 text-green-500 h-4')) ->toBe('text-green-500 h-4'); expect($cache) ->hits->toBe(1) ->misses->toBe(2); expect($twMerge->merge('text-red-500 text-green-500 h-4')) ->toBe('text-green-500 h-4'); expect($cache) ->hits->toBe(2) ->misses->toBe(2); }); class FakeCache implements CacheInterface { private array $cache = []; public int $hits = 0; public int $misses = 0; public function get(string $key, mixed $default = null): mixed { if (array_key_exists($key, $this->cache)) { $this->hits++; return $this->cache[$key]; } $this->misses++; return $default; } public function set(string $key, mixed $value, DateInterval|int|null $ttl = null): bool { $this->cache[$key] = $value; return true; } public function delete(string $key): bool { unset($this->cache[$key]); return true; } public function clear(): bool { $this->cache = []; return true; } public function getMultiple(iterable $keys, mixed $default = null): iterable { throw new Exception('Not implemented'); } public function setMultiple(iterable $values, DateInterval|int|null $ttl = null): bool { throw new Exception('Not implemented'); } public function deleteMultiple(iterable $keys): bool { throw new Exception('Not implemented'); } public function has(string $key): bool { $found = array_key_exists($key, $this->cache); if (! $found) { $this->misses++; } return $found; } }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/MergeConfigsTest.php
tests/Feature/MergeConfigsTest.php
<?php it('merge the config correctly', function () { $config = \TailwindMerge\Support\Config::getMergedConfig(); })->todo();
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/NegativeValuesTest.php
tests/Feature/NegativeValuesTest.php
<?php use TailwindMerge\TailwindMerge; it('handles negative value conflicts correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['-m-2 -m-5', '-m-5'], ['-top-12 -top-2000', '-top-2000'], ]); it('handles conflicts between positive and negative values correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['-m-2 m-auto', 'm-auto'], ['top-12 -top-69', '-top-69'], ]); it('handles conflicts across groups with negative values correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['-right-1 inset-x-1', 'inset-x-1'], ['hover:focus:-right-1 focus:hover:inset-x-1', 'focus:hover:inset-x-1'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/ArbitraryValuesTest.php
tests/Feature/ArbitraryValuesTest.php
<?php use TailwindMerge\TailwindMerge; it('handles simple conflicts with arbitrary values correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['m-[2px] m-[10px]', 'm-[10px]'], ['m-[2px] m-[11svmin] m-[12in] m-[13lvi] m-[14vb] m-[15vmax] m-[16mm] m-[17%] m-[18em] m-[19px] m-[10dvh]', 'm-[10dvh]'], ['h-[10px] h-[11cqw] h-[12cqh] h-[13cqi] h-[14cqb] h-[15cqmin] h-[16cqmax]', 'h-[16cqmax]'], ['z-20 z-[99]', 'z-[99]'], ['my-[2px] m-[10rem]', 'm-[10rem]'], ['cursor-pointer cursor-[grab]', 'cursor-[grab]'], ['m-[2px] m-[calc(100%-var(--arbitrary))]', 'm-[calc(100%-var(--arbitrary))]'], ['m-[2px] m-[length:var(--mystery-var)]', 'm-[length:var(--mystery-var)]'], ['opacity-10 opacity-[0.025]', 'opacity-[0.025]'], ['scale-75 scale-[1.7]', 'scale-[1.7]'], ['brightness-90 brightness-[1.75]', 'brightness-[1.75]'], // Handling of value `0` ['min-h-[0.5px] min-h-[0]', 'min-h-[0]'], ['text-[0.5px] text-[color:0]', 'text-[0.5px] text-[color:0]'], ['text-[0.5px] text-[--my-0]', 'text-[0.5px] text-[--my-0]'], ]); it('handles arbitrary length conflicts with labels and modifiers correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['hover:m-[2px] hover:m-[length:var(--c)]', 'hover:m-[length:var(--c)]'], ['hover:focus:m-[2px] focus:hover:m-[length:var(--c)]', 'focus:hover:m-[length:var(--c)]'], ['border-b border-[color:rgb(var(--color-gray-500-rgb)/50%))]', 'border-b border-[color:rgb(var(--color-gray-500-rgb)/50%))]'], ['border-[color:rgb(var(--color-gray-500-rgb)/50%))] border-b', 'border-[color:rgb(var(--color-gray-500-rgb)/50%))] border-b'], ['border-b border-[color:rgb(var(--color-gray-500-rgb)/50%))] border-some-coloooor', 'border-b border-some-coloooor'], ]); it('handles complex arbitrary value conflicts correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['grid-rows-[1fr,auto] grid-rows-2', 'grid-rows-2'], ['grid-rows-[repeat(20,minmax(0,1fr))] grid-rows-3', 'grid-rows-3'], ]); it('handles ambiguous arbitrary values correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['mt-2 mt-[calc(theme(fontSize.4xl)/1.125)]', 'mt-[calc(theme(fontSize.4xl)/1.125)]'], ['p-2 p-[calc(theme(fontSize.4xl)/1.125)_10px]', 'p-[calc(theme(fontSize.4xl)/1.125)_10px]'], ['mt-2 mt-[length:theme(someScale.someValue)]', 'mt-[length:theme(someScale.someValue)]'], ['mt-2 mt-[theme(someScale.someValue)]', 'mt-[theme(someScale.someValue)]'], ['text-2xl text-[length:theme(someScale.someValue)]', 'text-[length:theme(someScale.someValue)]'], ['text-2xl text-[calc(theme(fontSize.4xl)/1.125)]', 'text-[calc(theme(fontSize.4xl)/1.125)]'], ['bg-cover bg-[percentage:30%] bg-[length:200px_100px]', 'bg-[length:200px_100px]'], ['bg-none bg-[url(.)] bg-[image:.] bg-[url:.] bg-[linear-gradient(.)] bg-gradient-to-r', 'bg-gradient-to-r'], ]); it('handles ambiguous non conflicting arbitrary values correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['border-[2px] border-[0.85px] border-[#ff0000] border-[#0000ff]', 'border-[0.85px] border-[#0000ff]'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/ArbitraryVariantsTest.php
tests/Feature/ArbitraryVariantsTest.php
<?php use TailwindMerge\TailwindMerge; it('basic arbitrary variants', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['[&>*]:underline [&>*]:line-through', '[&>*]:line-through'], ['[&>*]:underline [&>*]:line-through [&_div]:line-through', '[&>*]:line-through [&_div]:line-through'], ['supports-[display:grid]:flex supports-[display:grid]:grid', 'supports-[display:grid]:grid'], ]); it('arbitrary variants with modifiers', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['dark:lg:hover:[&>*]:underline dark:lg:hover:[&>*]:line-through', 'dark:lg:hover:[&>*]:line-through'], ['dark:lg:hover:[&>*]:underline dark:hover:lg:[&>*]:line-through', 'dark:hover:lg:[&>*]:line-through'], 'Whether a modifier is before or after arbitrary variant matters' => ['hover:[&>*]:underline [&>*]:hover:line-through', 'hover:[&>*]:underline [&>*]:hover:line-through'], ['hover:dark:[&>*]:underline dark:hover:[&>*]:underline dark:[&>*]:hover:line-through', 'dark:hover:[&>*]:underline dark:[&>*]:hover:line-through'], ]); it('arbitrary variants with complex syntax in them', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['[@media_screen{@media(hover:hover)}]:underline [@media_screen{@media(hover:hover)}]:line-through', '[@media_screen{@media(hover:hover)}]:line-through'], ['hover:[@media_screen{@media(hover:hover)}]:underline hover:[@media_screen{@media(hover:hover)}]:line-through', 'hover:[@media_screen{@media(hover:hover)}]:line-through'], ]); test('arbitrary variants with attribute selectors', function () { expect(TailwindMerge::instance()->merge('[&[data-open]]:underline [&[data-open]]:line-through'))->toBe( '[&[data-open]]:line-through', ); }); test('arbitrary variants with multiple attribute selectors', function () { expect( TailwindMerge::instance()->merge( '[&[data-foo][data-bar]:not([data-baz])]:underline [&[data-foo][data-bar]:not([data-baz])]:line-through', ), )->toBe('[&[data-foo][data-bar]:not([data-baz])]:line-through'); }); it('multiple arbitrary variants', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['[&>*]:[&_div]:underline [&>*]:[&_div]:line-through', '[&>*]:[&_div]:line-through'], ['[&>*]:[&_div]:underline [&_div]:[&>*]:line-through', '[&>*]:[&_div]:underline [&_div]:[&>*]:line-through'], ['hover:dark:[&>*]:focus:disabled:[&_div]:underline dark:hover:[&>*]:disabled:focus:[&_div]:line-through', 'dark:hover:[&>*]:disabled:focus:[&_div]:line-through'], ['hover:dark:[&>*]:focus:[&_div]:disabled:underline dark:hover:[&>*]:disabled:focus:[&_div]:line-through', 'hover:dark:[&>*]:focus:[&_div]:disabled:underline dark:hover:[&>*]:disabled:focus:[&_div]:line-through'], ]); it('arbitrary variants with arbitrary properties', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['[&>*]:[color:red] [&>*]:[color:blue]', '[&>*]:[color:blue]'], ['[&[data-foo][data-bar]:not([data-baz])]:nod:noa:[color:red] [&[data-foo][data-bar]:not([data-baz])]:noa:nod:[color:blue]', '[&[data-foo][data-bar]:not([data-baz])]:noa:nod:[color:blue]'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/StandaloneClassesTest.php
tests/Feature/StandaloneClassesTest.php
<?php use TailwindMerge\TailwindMerge; it('merges standalone classes from same group correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['inline block', 'block'], ['hover:block hover:inline', 'hover:inline'], ['hover:block hover:block', 'hover:block'], ['inline hover:inline focus:inline hover:block hover:focus:block', 'inline focus:inline hover:block hover:focus:block'], ['underline line-through', 'line-through'], ['line-through no-underline', 'no-underline'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/ConflictsAcrossClassGroupsTest.php
tests/Feature/ConflictsAcrossClassGroupsTest.php
<?php use TailwindMerge\TailwindMerge; it('handles conflicts across class groups correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['inset-1 inset-x-1', 'inset-1 inset-x-1'], ['inset-x-1 inset-1', 'inset-1'], ['inset-x-1 left-1 inset-1', 'inset-1'], ['inset-x-1 inset-1 left-1', 'inset-1 left-1'], ['inset-x-1 right-1 inset-1', 'inset-1'], ['inset-x-1 right-1 inset-x-1', 'inset-x-1'], ['inset-x-1 right-1 inset-y-1', 'inset-x-1 right-1 inset-y-1'], ['right-1 inset-x-1 inset-y-1', 'inset-x-1 inset-y-1'], ['inset-x-1 hover:left-1 inset-1', 'hover:left-1 inset-1'], ['pl-4 px-6', 'px-6'], ]); it('ring and shadow classes do not create conflict', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['ring shadow', 'ring shadow'], ['ring-2 shadow-md', 'ring-2 shadow-md'], ['shadow ring', 'shadow ring'], ['shadow-md ring-2', 'shadow-md ring-2'], ]); it('touch classes do create conflicts correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['touch-pan-x touch-pan-right', 'touch-pan-right'], ['touch-none touch-pan-x', 'touch-pan-x'], ['touch-pan-x touch-none', 'touch-none'], ['touch-pan-x touch-pan-y touch-pinch-zoom', 'touch-pan-x touch-pan-y touch-pinch-zoom'], ['touch-manipulation touch-pan-x touch-pan-y touch-pinch-zoom', 'touch-pan-x touch-pan-y touch-pinch-zoom'], ['touch-pan-x touch-pan-y touch-pinch-zoom touch-auto', 'touch-auto'], ]); it('line-clamp classes do create conflicts correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['overflow-auto inline line-clamp-1', 'line-clamp-1'], ['line-clamp-1 overflow-auto inline', 'line-clamp-1 overflow-auto inline'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/PerSideBorderColorsTest.php
tests/Feature/PerSideBorderColorsTest.php
<?php use TailwindMerge\TailwindMerge; it('merges classes with per-side border colors correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['border-t-some-blue border-t-other-blue', 'border-t-other-blue'], ['border-t-some-blue border-some-blue', 'border-some-blue'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/ArbitraryPropertiesTest.php
tests/Feature/ArbitraryPropertiesTest.php
<?php use TailwindMerge\TailwindMerge; it('handles arbitrary property conflicts correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['[paint-order:markers] [paint-order:normal]', '[paint-order:normal]'], ['[paint-order:markers] [--my-var:2rem] [paint-order:normal] [--my-var:4px]', '[paint-order:normal] [--my-var:4px]'], ['[--first-var:1rem] [--second-var:2rem]', '[--first-var:1rem] [--second-var:2rem]'], ]); it('handles arbitrary property conflicts with modifiers correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['[paint-order:markers] hover:[paint-order:normal]', '[paint-order:markers] hover:[paint-order:normal]'], ['hover:[paint-order:markers] hover:[paint-order:normal]', 'hover:[paint-order:normal]'], ['hover:focus:[paint-order:markers] focus:hover:[paint-order:normal]', 'focus:hover:[paint-order:normal]'], ['[paint-order:markers] [paint-order:normal] [--my-var:2rem] lg:[--my-var:4px]', '[paint-order:normal] [--my-var:2rem] lg:[--my-var:4px]'], ]); test('handles complex arbitrary property conflicts correctly', function () { expect(TailwindMerge::instance()->merge('[-unknown-prop:::123:::] [-unknown-prop:url(https://hi.com)]'))->toBe( '[-unknown-prop:url(https://hi.com)]', ); }); it('handles important modifier correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['![some:prop] [some:other]', '![some:prop] [some:other]'], ['![some:prop] [some:other] [some:one] ![some:another]', '[some:one] ![some:another]'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/NonTailwindClasses.php
tests/Feature/NonTailwindClasses.php
<?php use TailwindMerge\TailwindMerge; it('does not alter non-tailwind classes', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['non-tailwind-class inline block', 'non-tailwind-class block'], ['inline block inline-1', 'block inline-1'], ['inline block i-inline', 'block i-inline'], ['focus:inline focus:block focus:inline-1', 'focus:block focus:inline-1'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/PrefixesTest.php
tests/Feature/PrefixesTest.php
<?php use TailwindMerge\TailwindMerge; it('works with a prefix correctly', function (string $input, string $output) { $instance = TailwindMerge::factory() ->withConfiguration([ 'prefix' => 'tw-', ])->make(); expect($instance->merge($input)) ->toBe($output); })->with([ ['tw-block tw-hidden', 'tw-hidden'], ['block hidden', 'block hidden'], ['tw-p-3 tw-p-2', 'tw-p-2'], ['p-3 p-2', 'p-3 p-2'], ['!tw-right-0 !tw-inset-0', '!tw-inset-0'], ['hover:focus:!tw-right-0 focus:hover:!tw-inset-0', 'focus:hover:!tw-inset-0'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/ImportantModifierTest.php
tests/Feature/ImportantModifierTest.php
<?php use TailwindMerge\TailwindMerge; it('merges tailwind classes with important modifier correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['!font-medium !font-bold', '!font-bold'], ['!font-medium !font-bold font-thin', '!font-bold font-thin'], ['!right-2 !-inset-x-px', '!-inset-x-px'], ['focus:!inline focus:!block', 'focus:!block'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/TailwindMergeTest.php
tests/Feature/TailwindMergeTest.php
<?php use TailwindMerge\TailwindMerge; it('does basic merges', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['h-10 w-10', 'h-10 w-10'], ['mix-blend-normal mix-blend-multiply', 'mix-blend-multiply'], ['h-10 h-min', 'h-min'], ['stroke-black stroke-1', 'stroke-black stroke-1'], ['stroke-2 stroke-[3]', 'stroke-[3]'], ['outline-black outline-1', 'outline-black outline-1'], ['grayscale-0 grayscale-[50%]', 'grayscale-[50%]'], ['grow grow-[2]', 'grow-[2]'], ['h-10 lg:h-12 lg:h-20', 'h-10 lg:h-20'], ['text-black dark:text-white dark:text-gray-700', 'text-black dark:text-gray-700'], ]); it('does basic merges with multiple parameters', function () { expect(TailwindMerge::instance()->merge('grow', [null, false, [['grow-[2]']]])) ->toBe('grow-[2]'); });
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/PseudoVariants.php
tests/Feature/PseudoVariants.php
<?php use TailwindMerge\TailwindMerge; it('handles pseudo variants conflicts properly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['empty:p-2 empty:p-3', 'empty:p-3'], ['hover:empty:p-2 hover:empty:p-3', 'hover:empty:p-3'], ['read-only:p-2 read-only:p-3', 'read-only:p-3'], ]); it('handles pseudo variant group conflicts properly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['group-empty:p-2 group-empty:p-3', 'group-empty:p-3'], ['peer-empty:p-2 peer-empty:p-3', 'peer-empty:p-3'], ['group-empty:p-2 peer-empty:p-3', 'group-empty:p-2 peer-empty:p-3'], ['hover:group-empty:p-2 hover:group-empty:p-3', 'hover:group-empty:p-3'], ['group-read-only:p-2 group-read-only:p-3', 'group-read-only:p-3'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/PublicApiTest.php
tests/Feature/PublicApiTest.php
<?php // TODO: not sure if this we need this at all
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/DefaultConfigTest.php
tests/Feature/DefaultConfigTest.php
<?php test('default config has correct types', function () { $defaultConfig = \TailwindMerge\Support\Config::getDefaultConfig(); expect($defaultConfig) ->not->toHaveKey('nonExistent') ->cacheSize->toBe(500) ->classGroups->display->{0}->toBe('block') ->classGroups->overflow->{0}->overflow->{0}->toBe('auto') ->classGroups->overflow->{0}->not->toHaveKey('nonExistent'); });
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/SeparatorsTest.php
tests/Feature/SeparatorsTest.php
<?php use TailwindMerge\TailwindMerge; test('single character separator working correctly', function ($input, $output) { $instance = TailwindMerge::factory() ->withConfiguration([ 'separator' => '_', ]) ->make(); expect($instance->merge($input))->toBe($output); })->with([ ['block hidden', 'hidden'], ['p-3 p-2', 'p-2'], ['!right-0 !inset-0', '!inset-0'], ['hover_focus_!right-0 focus_hover_!inset-0', 'focus_hover_!inset-0'], ['hover:focus:!right-0 focus:hover:!inset-0', 'hover:focus:!right-0 focus:hover:!inset-0'], ]); test('multiple character separator working correctly', function ($input, $output) { $instance = TailwindMerge::factory() ->withConfiguration([ 'separator' => '__', ]) ->make(); expect($instance->merge($input))->toBe($output); })->with([ ['block hidden', 'hidden'], ['p-3 p-2', 'p-2'], ['!right-0 !inset-0', '!inset-0'], ['hover__focus__!right-0 focus__hover__!inset-0', 'focus__hover__!inset-0'], ['hover:focus:!right-0 focus:hover:!inset-0', 'hover:focus:!right-0 focus:hover:!inset-0'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/CreateTailwindMergeTest.php
tests/Feature/CreateTailwindMergeTest.php
<?php use TailwindMerge\TailwindMerge; test('createTailwindMerge works with single config function', function ($input, $output) { $instance = TailwindMerge::factory() ->withConfiguration([ 'cacheSize' => 20, 'theme' => [], 'classGroups' => [ 'fooKey' => [['fooKey' => ['bar', 'baz']]], 'fooKey2' => [['fooKey' => ['qux', 'quux']], 'other-2'], 'otherKey' => ['nother', 'group'], ], 'conflictingClassGroups' => [ 'fooKey' => ['otherKey'], 'otherKey' => ['fooKey', 'fooKey2'], ], ]) ->make(); expect($instance->merge($input))->toBe($output); })->with([ ['', ''], ['my-modifier:fooKey-bar my-modifier:fooKey-baz', 'my-modifier:fooKey-baz'], ['other-modifier:fooKey-bar other-modifier:fooKey-baz', 'other-modifier:fooKey-baz'], ['group fooKey-bar', 'fooKey-bar'], ['fooKey-bar group', 'group'], ['group other-2', 'group other-2'], ['other-2 group', 'group'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/ContentUtilitiesTest.php
tests/Feature/ContentUtilitiesTest.php
<?php use TailwindMerge\TailwindMerge; test('merges content utilities correctly', function () { expect(TailwindMerge::instance()->merge("content-['hello'] content-[attr(data-content)]"))->toBe( 'content-[attr(data-content)]', ); });
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/ThemeTest.php
tests/Feature/ThemeTest.php
<?php use TailwindMerge\Support\Config; use TailwindMerge\TailwindMerge; test('theme scale can be extended', function ($input, $output) { $instance = TailwindMerge::factory() ->withConfiguration([ 'theme' => [ 'spacing' => ['my-space'], 'margin' => ['my-margin'], ], ]) ->make(); expect($instance->merge($input))->toBe($output); })->with([ ['p-3 p-my-space p-my-margin', 'p-my-space p-my-margin'], ['m-3 m-my-space m-my-margin', 'm-my-margin'], ]); test('theme object can be extended', function ($input, $output) { $instance = TailwindMerge::factory() ->withConfiguration([ 'theme' => [ 'my-theme' => ['hallo', 'hello'], ], 'classGroups' => [ 'px' => [['px' => [Config::fromTheme('my-theme')]]], ], ]) ->make(); expect($instance->merge($input))->toBe($output); })->with([ ['p-3 p-hello p-hallo', 'p-3 p-hello p-hallo'], ['px-3 px-hello px-hallo', 'px-hallo'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/ModifiersTest.php
tests/Feature/ModifiersTest.php
<?php use TailwindMerge\TailwindMerge; it('conflicts across prefix modifiers', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['hover:block hover:inline', 'hover:inline'], ['hover:block hover:focus:inline', 'hover:block hover:focus:inline'], ['hover:block hover:focus:inline focus:hover:inline', 'hover:block focus:hover:inline'], ['focus-within:inline focus-within:block', 'focus-within:block'], ]); it('conflicts across postfix modifiers', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['text-lg/7 text-lg/8', 'text-lg/8'], ['text-lg/none leading-9', 'text-lg/none leading-9'], ['leading-9 text-lg/none', 'text-lg/none'], ['w-full w-1/2', 'w-1/2'], ]); test('conflicts across postfix modifiers with custom configuration', function ($input, $output) { $instance = TailwindMerge::factory() ->withConfiguration([ 'cacheSize' => 10, 'theme' => [], 'classGroups' => [ 'foo' => ['foo-1/2', 'foo-2/3'], 'bar' => ['bar-1', 'bar-2'], 'baz' => ['baz-1', 'baz-2'], ], 'conflictingClassGroups' => [], 'conflictingClassGroupModifiers' => [ 'baz' => ['bar'], ], ]) ->make(); expect($instance->merge($input))->toBe($output); })->with([ // ['foo-1/2 foo-2/3', 'foo-2/3'], TODO: this one is failing, because the '/' is considered as possible postfix modifier ['bar-1 bar-2', 'bar-2'], ['bar-1 baz-1', 'bar-1 baz-1'], ['bar-1/2 bar-2', 'bar-2'], ['bar-2 bar-1/2', 'bar-1/2'], ['bar-1 baz-1/2', 'baz-1/2'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Feature/NonConflictingClassses.php
tests/Feature/NonConflictingClassses.php
<?php use TailwindMerge\TailwindMerge; it('merges non-conflicting classes correctly', function (string $input, string $output) { expect(TailwindMerge::instance()->merge($input)) ->toBe($output); })->with([ ['border-t border-white/10', 'border-t border-white/10'], ['border-t border-white', 'border-t border-white'], ['text-3.5xl text-black', 'text-3.5xl text-black'], ]);
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false
gehrisandro/tailwind-merge-php
https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/ClassMapTest.php
tests/Unit/ClassMapTest.php
<?php use TailwindMerge\Support\ClassMap; use TailwindMerge\Support\Collection; use TailwindMerge\Support\Config; use TailwindMerge\ValueObjects\ClassPartObject; test('class map has correct class groups at first part', function () { $classMap = ClassMap::create(Config::getDefaultConfig()); $classGroupsByFirstPart = Collection::make($classMap->nextPart) ->mapWithKeys(function ($value, $key) { return [$key => Collection::make(getClassGroupsInClassPart($value))->sort()->values()]; })->toArray(); expect($classMap->classGroupId)->toBeNull(); expect($classMap->validators)->toBeEmpty(); expect($classGroupsByFirstPart)->toEqual([ 'absolute' => ['position'], 'accent' => ['accent'], 'align' => ['vertical-align'], 'animate' => ['animate'], 'antialiased' => ['font-smoothing'], 'appearance' => ['appearance'], 'aspect' => ['aspect'], 'auto' => ['auto-cols', 'auto-rows'], 'backdrop' => [ 'backdrop-blur', 'backdrop-brightness', 'backdrop-contrast', 'backdrop-filter', 'backdrop-grayscale', 'backdrop-hue-rotate', 'backdrop-invert', 'backdrop-opacity', 'backdrop-saturate', 'backdrop-sepia', ], 'basis' => ['basis'], 'bg' => [ 'bg-attachment', 'bg-blend', 'bg-clip', 'bg-color', 'bg-image', 'bg-opacity', 'bg-origin', 'bg-position', 'bg-repeat', 'bg-size', ], 'block' => ['display'], 'blur' => ['blur'], 'border' => [ 'border-collapse', 'border-color', 'border-color-b', 'border-color-l', 'border-color-r', 'border-color-t', 'border-color-x', 'border-color-y', 'border-opacity', 'border-spacing', 'border-spacing-x', 'border-spacing-y', 'border-style', 'border-w', 'border-w-b', 'border-w-e', 'border-w-l', 'border-w-r', 'border-w-s', 'border-w-t', 'border-w-x', 'border-w-y', ], 'bottom' => ['bottom'], 'box' => ['box', 'box-decoration'], 'break' => ['break', 'break-after', 'break-before', 'break-inside'], 'brightness' => ['brightness'], 'capitalize' => ['text-transform'], 'caption' => ['caption'], 'caret' => ['caret-color'], 'clear' => ['clear'], 'col' => ['col-end', 'col-start', 'col-start-end'], 'collapse' => ['visibility'], 'columns' => ['columns'], 'container' => ['container'], 'content' => ['align-content', 'content'], 'contents' => ['display'], 'contrast' => ['contrast'], 'cursor' => ['cursor'], 'decoration' => ['text-decoration-color', 'text-decoration-style', 'text-decoration-thickness'], 'delay' => ['delay'], 'diagonal' => ['fvn-fraction'], 'divide' => [ 'divide-color', 'divide-opacity', 'divide-style', 'divide-x', 'divide-x-reverse', 'divide-y', 'divide-y-reverse', ], 'drop' => ['drop-shadow'], 'duration' => ['duration'], 'ease' => ['ease'], 'end' => ['end'], 'fill' => ['fill'], 'filter' => ['filter'], 'fixed' => ['position'], 'flex' => ['display', 'flex', 'flex-direction', 'flex-wrap'], 'float' => ['float'], 'flow' => ['display'], 'font' => ['font-family', 'font-weight'], 'forced' => ['forced-color-adjust'], 'from' => ['gradient-from', 'gradient-from-pos'], 'gap' => ['gap', 'gap-x', 'gap-y'], 'grayscale' => ['grayscale'], 'grid' => ['display', 'grid-cols', 'grid-flow', 'grid-rows'], 'grow' => ['grow'], 'h' => ['h'], 'hidden' => ['display'], 'hue' => ['hue-rotate'], 'hyphens' => ['hyphens'], 'indent' => ['indent'], 'inline' => ['display'], 'inset' => ['inset', 'inset-x', 'inset-y'], 'invert' => ['invert'], 'invisible' => ['visibility'], 'isolate' => ['isolation'], 'isolation' => ['isolation'], 'italic' => ['font-style'], 'items' => ['align-items'], 'justify' => ['justify-content', 'justify-items', 'justify-self'], 'leading' => ['leading'], 'left' => ['left'], 'line' => ['line-clamp', 'text-decoration'], 'lining' => ['fvn-figure'], 'list' => ['display', 'list-image', 'list-style-position', 'list-style-type'], 'lowercase' => ['text-transform'], 'm' => ['m'], 'max' => ['max-h', 'max-w'], 'mb' => ['mb'], 'me' => ['me'], 'min' => ['min-h', 'min-w'], 'mix' => ['mix-blend'], 'ml' => ['ml'], 'mr' => ['mr'], 'ms' => ['ms'], 'mt' => ['mt'], 'mx' => ['mx'], 'my' => ['my'], 'no' => ['text-decoration'], 'normal' => ['fvn-normal', 'text-transform'], 'not' => ['font-style', 'sr'], 'object' => ['object-fit', 'object-position'], 'oldstyle' => ['fvn-figure'], 'opacity' => ['opacity'], 'order' => ['order'], 'ordinal' => ['fvn-ordinal'], 'origin' => ['transform-origin'], 'outline' => ['outline-color', 'outline-offset', 'outline-style', 'outline-w'], 'overflow' => ['overflow', 'overflow-x', 'overflow-y'], 'overline' => ['text-decoration'], 'overscroll' => ['overscroll', 'overscroll-x', 'overscroll-y'], 'p' => ['p'], 'pb' => ['pb'], 'pe' => ['pe'], 'pl' => ['pl'], 'place' => ['place-content', 'place-items', 'place-self'], 'placeholder' => ['placeholder-color', 'placeholder-opacity'], 'pointer' => ['pointer-events'], 'pr' => ['pr'], 'proportional' => ['fvn-spacing'], 'ps' => ['ps'], 'pt' => ['pt'], 'px' => ['px'], 'py' => ['py'], 'relative' => ['position'], 'resize' => ['resize'], 'right' => ['right'], 'ring' => [ 'ring-color', 'ring-offset-color', 'ring-offset-w', 'ring-opacity', 'ring-w', 'ring-w-inset', ], 'rotate' => ['rotate'], 'rounded' => [ 'rounded', 'rounded-b', 'rounded-bl', 'rounded-br', 'rounded-e', 'rounded-ee', 'rounded-es', 'rounded-l', 'rounded-r', 'rounded-s', 'rounded-se', 'rounded-ss', 'rounded-t', 'rounded-tl', 'rounded-tr', ], 'row' => ['row-end', 'row-start', 'row-start-end'], 'saturate' => ['saturate'], 'scale' => ['scale', 'scale-x', 'scale-y'], 'scroll' => [ 'scroll-behavior', 'scroll-m', 'scroll-mb', 'scroll-me', 'scroll-ml', 'scroll-mr', 'scroll-ms', 'scroll-mt', 'scroll-mx', 'scroll-my', 'scroll-p', 'scroll-pb', 'scroll-pe', 'scroll-pl', 'scroll-pr', 'scroll-ps', 'scroll-pt', 'scroll-px', 'scroll-py', ], 'select' => ['select'], 'self' => ['align-self'], 'sepia' => ['sepia'], 'shadow' => ['shadow', 'shadow-color'], 'shrink' => ['shrink'], 'size' => ['size'], 'skew' => ['skew-x', 'skew-y'], 'slashed' => ['fvn-slashed-zero'], 'snap' => ['snap-align', 'snap-stop', 'snap-strictness', 'snap-type'], 'space' => ['space-x', 'space-x-reverse', 'space-y', 'space-y-reverse'], 'sr' => ['sr'], 'stacked' => ['fvn-fraction'], 'start' => ['start'], 'static' => ['position'], 'sticky' => ['position'], 'stroke' => ['stroke', 'stroke-w'], 'subpixel' => ['font-smoothing'], 'table' => ['display', 'table-layout'], 'tabular' => ['fvn-spacing'], 'text' => [ 'font-size', 'text-alignment', 'text-color', 'text-opacity', 'text-overflow', 'text-wrap', ], 'to' => ['gradient-to', 'gradient-to-pos'], 'top' => ['top'], 'touch' => ['touch', 'touch-pz', 'touch-x', 'touch-y'], 'tracking' => ['tracking'], 'transform' => ['transform'], 'transition' => ['transition'], 'translate' => ['translate-x', 'translate-y'], 'truncate' => ['text-overflow'], 'underline' => ['text-decoration', 'underline-offset'], 'uppercase' => ['text-transform'], 'via' => ['gradient-via', 'gradient-via-pos'], 'visible' => ['visibility'], 'w' => ['w'], 'whitespace' => ['whitespace'], 'will' => ['will-change'], 'z' => ['z'], ]); }); function getClassGroupsInClassPart(ClassPartObject $classPart): array { $classGroups = []; if ($classPart->classGroupId !== null) { $classGroups[] = $classPart->classGroupId; } foreach ($classPart->validators as $validator) { $classGroups[] = $validator->classGroupId; } foreach ($classPart->nextPart as $nextClassPart) { foreach (getClassGroupsInClassPart($nextClassPart) as $classGroup) { $classGroups[] = $classGroup; } } return array_unique($classGroups); }
php
MIT
dc11b9d4a625dd5be885900e5ef14c3efa260277
2026-01-05T04:59:39.669817Z
false