id int32 0 241k | repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 |
|---|---|---|---|---|---|---|---|---|---|---|---|
40,900 | potievdev/slim-rbac | src/Console/Command/BaseDatabaseCommand.php | BaseDatabaseCommand.getCliPath | private function getCliPath(InputInterface $input)
{
$filePaths = [
__DIR__ . '/../../../config/sr-config.php',
__DIR__ . '/../../../../../../sr-config.php',
__DIR__ . '/../../../../../../config/sr-config.php',
];
if ($input->hasOption('config')) {
$filePaths[] = $input->getOption('config');
}
foreach ($filePaths as $path) {
if (is_file($path)) {
return $path;
}
}
throw new \Exception(
'There is not found config file.' . PHP_EOL .
'You can pass path to file as option: -c FILE_PATH'
);
} | php | private function getCliPath(InputInterface $input)
{
$filePaths = [
__DIR__ . '/../../../config/sr-config.php',
__DIR__ . '/../../../../../../sr-config.php',
__DIR__ . '/../../../../../../config/sr-config.php',
];
if ($input->hasOption('config')) {
$filePaths[] = $input->getOption('config');
}
foreach ($filePaths as $path) {
if (is_file($path)) {
return $path;
}
}
throw new \Exception(
'There is not found config file.' . PHP_EOL .
'You can pass path to file as option: -c FILE_PATH'
);
} | [
"private",
"function",
"getCliPath",
"(",
"InputInterface",
"$",
"input",
")",
"{",
"$",
"filePaths",
"=",
"[",
"__DIR__",
".",
"'/../../../config/sr-config.php'",
",",
"__DIR__",
".",
"'/../../../../../../sr-config.php'",
",",
"__DIR__",
".",
"'/../../../../../../confi... | Returns cli-config file path
@param InputInterface $input
@return string
@throws \Exception | [
"Returns",
"cli",
"-",
"config",
"file",
"path"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Console/Command/BaseDatabaseCommand.php#L37-L60 |
40,901 | potievdev/slim-rbac | src/Component/BaseComponent.php | BaseComponent.saveEntity | protected function saveEntity($entity)
{
try {
$this->entityManager->persist($entity);
$this->entityManager->flush($entity);
return $entity;
} catch (OptimisticLockException $e) {
throw new DatabaseException($e->getMessage());
}
} | php | protected function saveEntity($entity)
{
try {
$this->entityManager->persist($entity);
$this->entityManager->flush($entity);
return $entity;
} catch (OptimisticLockException $e) {
throw new DatabaseException($e->getMessage());
}
} | [
"protected",
"function",
"saveEntity",
"(",
"$",
"entity",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"entityManager",
"->",
"persist",
"(",
"$",
"entity",
")",
";",
"$",
"this",
"->",
"entityManager",
"->",
"flush",
"(",
"$",
"entity",
")",
";",
"return... | Insert or update entity
@param object $entity
@return object
@throws DatabaseException | [
"Insert",
"or",
"update",
"entity"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/BaseComponent.php#L45-L54 |
40,902 | potievdev/slim-rbac | src/Component/BaseComponent.php | BaseComponent.checkAccess | public function checkAccess($userId, $permissionName)
{
if (ValidatorHelper::isInteger($userId) == false) {
throw new InvalidArgumentException('User identifier must be number.');
}
/** @var integer $permissionId */
$permissionId = $this->repositoryRegistry
->getPermissionRepository()
->getPermissionIdByName($permissionName);
if (ValidatorHelper::isInteger($permissionId)) {
/** @var integer[] $rootRoleIds */
$rootRoleIds = $this->repositoryRegistry
->getUserRoleRepository()
->getUserRoleIds($userId);
if (count($rootRoleIds) > 0) {
/** @var integer[] $allRoleIds */
$allRoleIds = $this->repositoryRegistry
->getRoleHierarchyRepository()
->getAllRoleIdsHierarchy($rootRoleIds);
return $this->repositoryRegistry
->getRolePermissionRepository()
->isPermissionAssigned($permissionId, $allRoleIds);
}
}
return false;
} | php | public function checkAccess($userId, $permissionName)
{
if (ValidatorHelper::isInteger($userId) == false) {
throw new InvalidArgumentException('User identifier must be number.');
}
/** @var integer $permissionId */
$permissionId = $this->repositoryRegistry
->getPermissionRepository()
->getPermissionIdByName($permissionName);
if (ValidatorHelper::isInteger($permissionId)) {
/** @var integer[] $rootRoleIds */
$rootRoleIds = $this->repositoryRegistry
->getUserRoleRepository()
->getUserRoleIds($userId);
if (count($rootRoleIds) > 0) {
/** @var integer[] $allRoleIds */
$allRoleIds = $this->repositoryRegistry
->getRoleHierarchyRepository()
->getAllRoleIdsHierarchy($rootRoleIds);
return $this->repositoryRegistry
->getRolePermissionRepository()
->isPermissionAssigned($permissionId, $allRoleIds);
}
}
return false;
} | [
"public",
"function",
"checkAccess",
"(",
"$",
"userId",
",",
"$",
"permissionName",
")",
"{",
"if",
"(",
"ValidatorHelper",
"::",
"isInteger",
"(",
"$",
"userId",
")",
"==",
"false",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'User identifier... | Checks access status
@param integer $userId
@param string $permissionName
@return bool
@throws InvalidArgumentException
@throws \Doctrine\ORM\Query\QueryException | [
"Checks",
"access",
"status"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/BaseComponent.php#L64-L96 |
40,903 | potievdev/slim-rbac | src/Models/Repository/RolePermissionRepository.php | RolePermissionRepository.isPermissionAssigned | public function isPermissionAssigned($permissionId, $roleIds)
{
$qb = $this->createQueryBuilder('rolePermission');
$result = $qb
->select('rolePermission.id')
->where(
$qb->expr()->andX(
$qb->expr()->eq('rolePermission.permissionId', $permissionId),
$qb->expr()->in('rolePermission.roleId', $roleIds)
)
)
->setMaxResults(1)
->getQuery()
->getArrayResult();
return count($result) > 0;
} | php | public function isPermissionAssigned($permissionId, $roleIds)
{
$qb = $this->createQueryBuilder('rolePermission');
$result = $qb
->select('rolePermission.id')
->where(
$qb->expr()->andX(
$qb->expr()->eq('rolePermission.permissionId', $permissionId),
$qb->expr()->in('rolePermission.roleId', $roleIds)
)
)
->setMaxResults(1)
->getQuery()
->getArrayResult();
return count($result) > 0;
} | [
"public",
"function",
"isPermissionAssigned",
"(",
"$",
"permissionId",
",",
"$",
"roleIds",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'rolePermission'",
")",
";",
"$",
"result",
"=",
"$",
"qb",
"->",
"select",
"(",
"'rolePer... | Search RolePermission record. If found return true else false
@param integer $permissionId
@param integer[] $roleIds
@return bool | [
"Search",
"RolePermission",
"record",
".",
"If",
"found",
"return",
"true",
"else",
"false"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Models/Repository/RolePermissionRepository.php#L36-L53 |
40,904 | potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.checkForCyclicHierarchy | private function checkForCyclicHierarchy($parentRoleId, $childRoleId)
{
$result = $this->repositoryRegistry
->getRoleHierarchyRepository()
->hasChildRoleId($parentRoleId, $childRoleId);
if ($result === true) {
throw new CyclicException('There detected cyclic line. Role with id = ' . $parentRoleId . ' has child role whit id =' . $childRoleId);
}
} | php | private function checkForCyclicHierarchy($parentRoleId, $childRoleId)
{
$result = $this->repositoryRegistry
->getRoleHierarchyRepository()
->hasChildRoleId($parentRoleId, $childRoleId);
if ($result === true) {
throw new CyclicException('There detected cyclic line. Role with id = ' . $parentRoleId . ' has child role whit id =' . $childRoleId);
}
} | [
"private",
"function",
"checkForCyclicHierarchy",
"(",
"$",
"parentRoleId",
",",
"$",
"childRoleId",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"repositoryRegistry",
"->",
"getRoleHierarchyRepository",
"(",
")",
"->",
"hasChildRoleId",
"(",
"$",
"parentRoleI... | Checking hierarchy cyclic line
@param integer $parentRoleId
@param integer $childRoleId
@throws CyclicException
@throws \Doctrine\ORM\Query\QueryException | [
"Checking",
"hierarchy",
"cyclic",
"line"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L29-L38 |
40,905 | potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.removeAll | public function removeAll()
{
$pdo = $this->entityManager->getConnection()->getWrappedConnection();
$pdo->beginTransaction();
try {
$pdo->exec('SET FOREIGN_KEY_CHECKS=0');
$pdo->exec('TRUNCATE role_permission');
$pdo->exec('TRUNCATE role_hierarchy');
$pdo->exec('TRUNCATE role');
$pdo->exec('TRUNCATE permission');
$pdo->exec('TRUNCATE user_role');
$pdo->exec('SET FOREIGN_KEY_CHECKS=1');
$pdo->commit();
} catch (\Exception $e) {
$pdo->rollBack();
throw new DatabaseException($e->getMessage());
}
} | php | public function removeAll()
{
$pdo = $this->entityManager->getConnection()->getWrappedConnection();
$pdo->beginTransaction();
try {
$pdo->exec('SET FOREIGN_KEY_CHECKS=0');
$pdo->exec('TRUNCATE role_permission');
$pdo->exec('TRUNCATE role_hierarchy');
$pdo->exec('TRUNCATE role');
$pdo->exec('TRUNCATE permission');
$pdo->exec('TRUNCATE user_role');
$pdo->exec('SET FOREIGN_KEY_CHECKS=1');
$pdo->commit();
} catch (\Exception $e) {
$pdo->rollBack();
throw new DatabaseException($e->getMessage());
}
} | [
"public",
"function",
"removeAll",
"(",
")",
"{",
"$",
"pdo",
"=",
"$",
"this",
"->",
"entityManager",
"->",
"getConnection",
"(",
")",
"->",
"getWrappedConnection",
"(",
")",
";",
"$",
"pdo",
"->",
"beginTransaction",
"(",
")",
";",
"try",
"{",
"$",
"... | Truncates all tables
@throws DatabaseException | [
"Truncates",
"all",
"tables"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L44-L65 |
40,906 | potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.addPermission | public function addPermission(Permission $permission)
{
try {
$this->saveEntity($permission);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Permission with name ' . $permission->getName() . ' already created');
}
} | php | public function addPermission(Permission $permission)
{
try {
$this->saveEntity($permission);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Permission with name ' . $permission->getName() . ' already created');
}
} | [
"public",
"function",
"addPermission",
"(",
"Permission",
"$",
"permission",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"saveEntity",
"(",
"$",
"permission",
")",
";",
"}",
"catch",
"(",
"UniqueConstraintViolationException",
"$",
"e",
")",
"{",
"throw",
"new",... | Save permission in database
@param Permission $permission
@throws NotUniqueException
@throws DatabaseException | [
"Save",
"permission",
"in",
"database"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L99-L106 |
40,907 | potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.addRole | public function addRole(Role $role)
{
try {
$this->saveEntity($role);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Role with name ' . $role->getName() . ' already created');
}
} | php | public function addRole(Role $role)
{
try {
$this->saveEntity($role);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Role with name ' . $role->getName() . ' already created');
}
} | [
"public",
"function",
"addRole",
"(",
"Role",
"$",
"role",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"saveEntity",
"(",
"$",
"role",
")",
";",
"}",
"catch",
"(",
"UniqueConstraintViolationException",
"$",
"e",
")",
"{",
"throw",
"new",
"NotUniqueException",... | Save role in database
@param Role $role
@throws NotUniqueException
@throws DatabaseException | [
"Save",
"role",
"in",
"database"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L114-L121 |
40,908 | potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.addChildPermission | public function addChildPermission(Role $role, Permission $permission)
{
$rolePermission = new RolePermission();
$rolePermission->setPermission($permission);
$rolePermission->setRole($role);
try {
$this->saveEntity($rolePermission);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Permission ' . $permission->getName() . ' is already assigned to role ' . $role->getName());
}
} | php | public function addChildPermission(Role $role, Permission $permission)
{
$rolePermission = new RolePermission();
$rolePermission->setPermission($permission);
$rolePermission->setRole($role);
try {
$this->saveEntity($rolePermission);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Permission ' . $permission->getName() . ' is already assigned to role ' . $role->getName());
}
} | [
"public",
"function",
"addChildPermission",
"(",
"Role",
"$",
"role",
",",
"Permission",
"$",
"permission",
")",
"{",
"$",
"rolePermission",
"=",
"new",
"RolePermission",
"(",
")",
";",
"$",
"rolePermission",
"->",
"setPermission",
"(",
"$",
"permission",
")",... | Add permission to role
@param Role $role
@param Permission $permission
@throws DatabaseException
@throws NotUniqueException | [
"Add",
"permission",
"to",
"role"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L130-L142 |
40,909 | potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.addChildRole | public function addChildRole(Role $parentRole, Role $childRole)
{
$roleHierarchy = new RoleHierarchy();
$roleHierarchy->setParentRole($parentRole);
$roleHierarchy->setChildRole($childRole);
$this->checkForCyclicHierarchy($childRole->getId(), $parentRole->getId());
try {
$this->saveEntity($roleHierarchy);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Child role ' . $childRole->getName() . ' is already has parent role ' . $parentRole->getName());
}
} | php | public function addChildRole(Role $parentRole, Role $childRole)
{
$roleHierarchy = new RoleHierarchy();
$roleHierarchy->setParentRole($parentRole);
$roleHierarchy->setChildRole($childRole);
$this->checkForCyclicHierarchy($childRole->getId(), $parentRole->getId());
try {
$this->saveEntity($roleHierarchy);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Child role ' . $childRole->getName() . ' is already has parent role ' . $parentRole->getName());
}
} | [
"public",
"function",
"addChildRole",
"(",
"Role",
"$",
"parentRole",
",",
"Role",
"$",
"childRole",
")",
"{",
"$",
"roleHierarchy",
"=",
"new",
"RoleHierarchy",
"(",
")",
";",
"$",
"roleHierarchy",
"->",
"setParentRole",
"(",
"$",
"parentRole",
")",
";",
... | Add child role to role
@param Role $parentRole
@param Role $childRole
@throws CyclicException
@throws DatabaseException
@throws NotUniqueException
@throws \Doctrine\ORM\Query\QueryException | [
"Add",
"child",
"role",
"to",
"role"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L153-L167 |
40,910 | potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.assign | public function assign(Role $role, $userId)
{
$userRole = new UserRole();
$userRole->setUserId($userId);
$userRole->setRole($role);
try {
$this->saveEntity($userRole);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Role ' . $role->getName() . 'is already assigned to user with identifier ' . $userId);
}
} | php | public function assign(Role $role, $userId)
{
$userRole = new UserRole();
$userRole->setUserId($userId);
$userRole->setRole($role);
try {
$this->saveEntity($userRole);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Role ' . $role->getName() . 'is already assigned to user with identifier ' . $userId);
}
} | [
"public",
"function",
"assign",
"(",
"Role",
"$",
"role",
",",
"$",
"userId",
")",
"{",
"$",
"userRole",
"=",
"new",
"UserRole",
"(",
")",
";",
"$",
"userRole",
"->",
"setUserId",
"(",
"$",
"userId",
")",
";",
"$",
"userRole",
"->",
"setRole",
"(",
... | Assign role to user
@param Role $role
@param integer $userId
@throws NotUniqueException
@throws DatabaseException | [
"Assign",
"role",
"to",
"user"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L176-L188 |
40,911 | potievdev/slim-rbac | src/Models/Repository/PermissionRepository.php | PermissionRepository.getPermissionIdByName | public function getPermissionIdByName($permissionName)
{
$qb = $this->createQueryBuilder('permission');
$result = $qb->select('permission.id')
->where($qb->expr()->eq('permission.name', $qb->expr()->literal($permissionName)))
->setMaxResults(1)
->getQuery()
->getArrayResult();
if (count($result) > 0) {
return $result[0]['id'];
}
return null;
} | php | public function getPermissionIdByName($permissionName)
{
$qb = $this->createQueryBuilder('permission');
$result = $qb->select('permission.id')
->where($qb->expr()->eq('permission.name', $qb->expr()->literal($permissionName)))
->setMaxResults(1)
->getQuery()
->getArrayResult();
if (count($result) > 0) {
return $result[0]['id'];
}
return null;
} | [
"public",
"function",
"getPermissionIdByName",
"(",
"$",
"permissionName",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'permission'",
")",
";",
"$",
"result",
"=",
"$",
"qb",
"->",
"select",
"(",
"'permission.id'",
")",
"->",
"... | Finds permission by name. If it founded returns permission id
@param string $permissionName
@return integer | [
"Finds",
"permission",
"by",
"name",
".",
"If",
"it",
"founded",
"returns",
"permission",
"id"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Models/Repository/PermissionRepository.php#L20-L35 |
40,912 | potievdev/slim-rbac | src/migrations/20171210104049_create_role_permission.php | CreateRolePermission.change | public function change()
{
$rolePermissionTable = $this->table('role_permission', ['signed' => false]);
$rolePermissionTable->addColumn('role_id', 'integer', ['signed' => false])
->addColumn('permission_id', 'integer', ['signed' => false])
->addColumn('created_at', 'datetime')
->addIndex(['role_id', 'permission_id'], ['name' => 'idx_role_permission_unique', 'unique' => true])
->addForeignKey('role_id', 'role', 'id', ['delete' => 'RESTRICT', 'constraint' => 'fk_role_permission_role'])
->addForeignKey('permission_id', 'permission', 'id', ['delete' => 'RESTRICT', 'constraint' => 'fk_role_permission_permission'])
->create();
} | php | public function change()
{
$rolePermissionTable = $this->table('role_permission', ['signed' => false]);
$rolePermissionTable->addColumn('role_id', 'integer', ['signed' => false])
->addColumn('permission_id', 'integer', ['signed' => false])
->addColumn('created_at', 'datetime')
->addIndex(['role_id', 'permission_id'], ['name' => 'idx_role_permission_unique', 'unique' => true])
->addForeignKey('role_id', 'role', 'id', ['delete' => 'RESTRICT', 'constraint' => 'fk_role_permission_role'])
->addForeignKey('permission_id', 'permission', 'id', ['delete' => 'RESTRICT', 'constraint' => 'fk_role_permission_permission'])
->create();
} | [
"public",
"function",
"change",
"(",
")",
"{",
"$",
"rolePermissionTable",
"=",
"$",
"this",
"->",
"table",
"(",
"'role_permission'",
",",
"[",
"'signed'",
"=>",
"false",
"]",
")",
";",
"$",
"rolePermissionTable",
"->",
"addColumn",
"(",
"'role_id'",
",",
... | Create 'role_permission' table in database.
'role_id' with 'permission_id' creates unique index. | [
"Create",
"role_permission",
"table",
"in",
"database",
".",
"role_id",
"with",
"permission_id",
"creates",
"unique",
"index",
"."
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/migrations/20171210104049_create_role_permission.php#L14-L25 |
40,913 | azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.getRecipientVarsForNotificationsEmail | protected function getRecipientVarsForNotificationsEmail(RecipientInterface $recipient)
{
$recipientParams = array();
$recipientParams['recipient'] = $recipient;
$recipientParams['mode'] = $recipient->getNotificationMode();
return $recipientParams;
} | php | protected function getRecipientVarsForNotificationsEmail(RecipientInterface $recipient)
{
$recipientParams = array();
$recipientParams['recipient'] = $recipient;
$recipientParams['mode'] = $recipient->getNotificationMode();
return $recipientParams;
} | [
"protected",
"function",
"getRecipientVarsForNotificationsEmail",
"(",
"RecipientInterface",
"$",
"recipient",
")",
"{",
"$",
"recipientParams",
"=",
"array",
"(",
")",
";",
"$",
"recipientParams",
"[",
"'recipient'",
"]",
"=",
"$",
"recipient",
";",
"$",
"recipie... | Override this function to fill in any recipient-specific parameters that are required to
render the notifications-template or one of the notification-item-templates that
are rendered into the notifications-template.
@param RecipientInterface $recipient
@return array | [
"Override",
"this",
"function",
"to",
"fill",
"in",
"any",
"recipient",
"-",
"specific",
"parameters",
"that",
"are",
"required",
"to",
"render",
"the",
"notifications",
"-",
"template",
"or",
"one",
"of",
"the",
"notification",
"-",
"item",
"-",
"templates",
... | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L43-L50 |
40,914 | azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.getRecipientSpecificNotificationsSubject | public function getRecipientSpecificNotificationsSubject($contentItems, RecipientInterface $recipient)
{
$count = sizeof($contentItems);
if (1 == $count) {
// get the content-item out of the boxed associative array => array(array('templateId' => contentItem))
$onlyItem = current(current($contentItems));
// get the title out of the notification in the contentItem
return $onlyItem['notification']->getTitle();
}
return $this->translatorService->transChoice('_az.email.notifications.subject.%count%', $count, array('%count%' => $count));
} | php | public function getRecipientSpecificNotificationsSubject($contentItems, RecipientInterface $recipient)
{
$count = sizeof($contentItems);
if (1 == $count) {
// get the content-item out of the boxed associative array => array(array('templateId' => contentItem))
$onlyItem = current(current($contentItems));
// get the title out of the notification in the contentItem
return $onlyItem['notification']->getTitle();
}
return $this->translatorService->transChoice('_az.email.notifications.subject.%count%', $count, array('%count%' => $count));
} | [
"public",
"function",
"getRecipientSpecificNotificationsSubject",
"(",
"$",
"contentItems",
",",
"RecipientInterface",
"$",
"recipient",
")",
"{",
"$",
"count",
"=",
"sizeof",
"(",
"$",
"contentItems",
")",
";",
"if",
"(",
"1",
"==",
"$",
"count",
")",
"{",
... | Get the subject for the notifications-email to send. Override this function to implement your custom subject-lines.
@param array of array $contentItems
@param RecipientInterface $recipient
@return string | [
"Get",
"the",
"subject",
"for",
"the",
"notifications",
"-",
"email",
"to",
"send",
".",
"Override",
"this",
"function",
"to",
"implement",
"your",
"custom",
"subject",
"-",
"lines",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L60-L72 |
40,915 | azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.sendNotificationsFor | public function sendNotificationsFor($recipientId, $wrapperTemplateName, $params)
{
// get the recipient
$recipient = $this->recipientProvider->getRecipient($recipientId);
// get all Notification-Items for the recipient from the database
$notifications = $this->getNotificationsFor($recipient);
if (0 == sizeof($notifications)) {
return null;
}
// get the recipient specific parameters for the twig-templates
$recipientParams = $this->getRecipientVarsForNotificationsEmail($recipient);
$params = array_merge($recipientParams, $params);
// prepare the arrays with template and template-variables for each notification
$contentItems = array();
foreach ($notifications as $notification) {
// decode the $params from the json in the notification-entity
$itemVars = $notification->getVariables();
$itemVars = array_merge($params, $itemVars);
$itemVars['notification'] = $notification;
$itemVars['recipient'] = $recipient;
$itemTemplateName = $notification->getTemplate();
$contentItems[] = array($itemTemplateName => $itemVars);
}
// add the notifications to the params array so they will be rendered later
$params[self::CONTENT_ITEMS] = $contentItems;
$params['recipient'] = $recipient;
$params['_locale'] = $recipient->getPreferredLocale();
$subject = $this->getRecipientSpecificNotificationsSubject($contentItems, $recipient);
// send the email with the right wrapper-template
$sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $params, $wrapperTemplateName.'.txt.twig', $recipient->getPreferredLocale());
if ($sent) {
// save the updated notifications
$this->setNotificationsAsSent($notifications);
return null;
}
return $recipient->getEmail();
} | php | public function sendNotificationsFor($recipientId, $wrapperTemplateName, $params)
{
// get the recipient
$recipient = $this->recipientProvider->getRecipient($recipientId);
// get all Notification-Items for the recipient from the database
$notifications = $this->getNotificationsFor($recipient);
if (0 == sizeof($notifications)) {
return null;
}
// get the recipient specific parameters for the twig-templates
$recipientParams = $this->getRecipientVarsForNotificationsEmail($recipient);
$params = array_merge($recipientParams, $params);
// prepare the arrays with template and template-variables for each notification
$contentItems = array();
foreach ($notifications as $notification) {
// decode the $params from the json in the notification-entity
$itemVars = $notification->getVariables();
$itemVars = array_merge($params, $itemVars);
$itemVars['notification'] = $notification;
$itemVars['recipient'] = $recipient;
$itemTemplateName = $notification->getTemplate();
$contentItems[] = array($itemTemplateName => $itemVars);
}
// add the notifications to the params array so they will be rendered later
$params[self::CONTENT_ITEMS] = $contentItems;
$params['recipient'] = $recipient;
$params['_locale'] = $recipient->getPreferredLocale();
$subject = $this->getRecipientSpecificNotificationsSubject($contentItems, $recipient);
// send the email with the right wrapper-template
$sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $params, $wrapperTemplateName.'.txt.twig', $recipient->getPreferredLocale());
if ($sent) {
// save the updated notifications
$this->setNotificationsAsSent($notifications);
return null;
}
return $recipient->getEmail();
} | [
"public",
"function",
"sendNotificationsFor",
"(",
"$",
"recipientId",
",",
"$",
"wrapperTemplateName",
",",
"$",
"params",
")",
"{",
"// get the recipient",
"$",
"recipient",
"=",
"$",
"this",
"->",
"recipientProvider",
"->",
"getRecipient",
"(",
"$",
"recipientI... | Send the notifications-email for one recipient.
@param int $recipientId
@param string $wrapperTemplateName
@param array $params array of parameters for this recipient
@return string|null or the failed email addressess | [
"Send",
"the",
"notifications",
"-",
"email",
"for",
"one",
"recipient",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L315-L362 |
40,916 | azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.sendNewsletterFor | public function sendNewsletterFor($recipientId, array $params, $wrapperTemplate)
{
$recipient = $this->recipientProvider->getRecipient($recipientId);
// create new array for each recipient.
$recipientParams = array_merge($params, $this->getRecipientSpecificNewsletterParams($recipient));
// get the recipient-specific contentItems of the newsletter
$recipientContentItems = $this->getRecipientSpecificNewsletterContentItems($recipient);
// merge the recipient-specific and the general content items. recipient-specific first/at the top!
$recipientParams[self::CONTENT_ITEMS] = $this->orderContentItems(array_merge($recipientContentItems, $params[self::CONTENT_ITEMS]));
$recipientParams['_locale'] = $recipient->getPreferredLocale();
if (0 == sizeof($recipientParams[self::CONTENT_ITEMS])) {
return $recipient->getEmail();
}
$subject = $this->getRecipientSpecificNewsletterSubject($params[self::CONTENT_ITEMS], $recipientContentItems, $params, $recipient, $recipient->getPreferredLocale());
// render and send the email with the right wrapper-template
$sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $recipientParams, $wrapperTemplate.'.txt.twig', $recipient->getPreferredLocale());
if ($sent) {
// save that this recipient has recieved the newsletter
return null;
}
return $recipient->getEmail();
} | php | public function sendNewsletterFor($recipientId, array $params, $wrapperTemplate)
{
$recipient = $this->recipientProvider->getRecipient($recipientId);
// create new array for each recipient.
$recipientParams = array_merge($params, $this->getRecipientSpecificNewsletterParams($recipient));
// get the recipient-specific contentItems of the newsletter
$recipientContentItems = $this->getRecipientSpecificNewsletterContentItems($recipient);
// merge the recipient-specific and the general content items. recipient-specific first/at the top!
$recipientParams[self::CONTENT_ITEMS] = $this->orderContentItems(array_merge($recipientContentItems, $params[self::CONTENT_ITEMS]));
$recipientParams['_locale'] = $recipient->getPreferredLocale();
if (0 == sizeof($recipientParams[self::CONTENT_ITEMS])) {
return $recipient->getEmail();
}
$subject = $this->getRecipientSpecificNewsletterSubject($params[self::CONTENT_ITEMS], $recipientContentItems, $params, $recipient, $recipient->getPreferredLocale());
// render and send the email with the right wrapper-template
$sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $recipientParams, $wrapperTemplate.'.txt.twig', $recipient->getPreferredLocale());
if ($sent) {
// save that this recipient has recieved the newsletter
return null;
}
return $recipient->getEmail();
} | [
"public",
"function",
"sendNewsletterFor",
"(",
"$",
"recipientId",
",",
"array",
"$",
"params",
",",
"$",
"wrapperTemplate",
")",
"{",
"$",
"recipient",
"=",
"$",
"this",
"->",
"recipientProvider",
"->",
"getRecipient",
"(",
"$",
"recipientId",
")",
";",
"/... | Send the newsletter for one recipient.
@param int $recipientId
@param array $params params and contentItems that are the same for all recipients
@param string $wrapperTemplate
@return string|null or the failed email addressess | [
"Send",
"the",
"newsletter",
"for",
"one",
"recipient",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L405-L434 |
40,917 | azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.getNotificationsFor | protected function getNotificationsFor(RecipientInterface $recipient)
{
// get the notification mode
$notificationMode = $recipient->getNotificationMode();
// get the date/time of the last notification
$lastNotificationDate = $this->getNotificationRepository()->getLastNotificationDate($recipient->getId());
$sendNotifications = false;
$timeDelta = time() - $lastNotificationDate->getTimestamp();
if (RecipientInterface::NOTIFICATION_MODE_IMMEDIATELY == $notificationMode) {
$sendNotifications = true;
} elseif (RecipientInterface::NOTIFICATION_MODE_HOURLY == $notificationMode) {
$sendNotifications = ($timeDelta > $this->getHourInterval());
} elseif (RecipientInterface::NOTIFICATION_MODE_DAYLY == $notificationMode) {
$sendNotifications = ($timeDelta > $this->getDayInterval());
} elseif (RecipientInterface::NOTIFICATION_MODE_NEVER == $notificationMode) {
$this->markAllNotificationsAsSentFarInThePast($recipient);
return array();
}
// regularly sent notifications now
if ($sendNotifications) {
$notifications = $this->getNotificationRepository()->getNotificationsToSend($recipient->getId());
// if notifications exist, that should be sent immediately, then send those now disregarding the users mailing-preferences.
} else {
$notifications = $this->getNotificationRepository()->getNotificationsToSendImmediately($recipient->getId());
}
return $notifications;
} | php | protected function getNotificationsFor(RecipientInterface $recipient)
{
// get the notification mode
$notificationMode = $recipient->getNotificationMode();
// get the date/time of the last notification
$lastNotificationDate = $this->getNotificationRepository()->getLastNotificationDate($recipient->getId());
$sendNotifications = false;
$timeDelta = time() - $lastNotificationDate->getTimestamp();
if (RecipientInterface::NOTIFICATION_MODE_IMMEDIATELY == $notificationMode) {
$sendNotifications = true;
} elseif (RecipientInterface::NOTIFICATION_MODE_HOURLY == $notificationMode) {
$sendNotifications = ($timeDelta > $this->getHourInterval());
} elseif (RecipientInterface::NOTIFICATION_MODE_DAYLY == $notificationMode) {
$sendNotifications = ($timeDelta > $this->getDayInterval());
} elseif (RecipientInterface::NOTIFICATION_MODE_NEVER == $notificationMode) {
$this->markAllNotificationsAsSentFarInThePast($recipient);
return array();
}
// regularly sent notifications now
if ($sendNotifications) {
$notifications = $this->getNotificationRepository()->getNotificationsToSend($recipient->getId());
// if notifications exist, that should be sent immediately, then send those now disregarding the users mailing-preferences.
} else {
$notifications = $this->getNotificationRepository()->getNotificationsToSendImmediately($recipient->getId());
}
return $notifications;
} | [
"protected",
"function",
"getNotificationsFor",
"(",
"RecipientInterface",
"$",
"recipient",
")",
"{",
"// get the notification mode",
"$",
"notificationMode",
"=",
"$",
"recipient",
"->",
"getNotificationMode",
"(",
")",
";",
"// get the date/time of the last notification",
... | Get the Notifications that have not yet been sent yet.
Ordered by "template" and "title".
@param RecipientInterface $recipient
@return array of Notification | [
"Get",
"the",
"Notifications",
"that",
"have",
"not",
"yet",
"been",
"sent",
"yet",
".",
"Ordered",
"by",
"template",
"and",
"title",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L444-L477 |
40,918 | azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.addNotification | public function addNotification($recipientId, $title, $content, $template, $templateVars, $importance, $sendImmediately)
{
$notification = new Notification();
$notification->setRecipientId($recipientId);
$notification->setTitle($title);
$notification->setContent($content);
$notification->setTemplate($template);
$notification->setImportance($importance);
$notification->setSendImmediately($sendImmediately);
$notification->setVariables($templateVars);
$this->managerRegistry->getManager()->persist($notification);
$this->managerRegistry->getManager()->flush($notification);
return $notification;
} | php | public function addNotification($recipientId, $title, $content, $template, $templateVars, $importance, $sendImmediately)
{
$notification = new Notification();
$notification->setRecipientId($recipientId);
$notification->setTitle($title);
$notification->setContent($content);
$notification->setTemplate($template);
$notification->setImportance($importance);
$notification->setSendImmediately($sendImmediately);
$notification->setVariables($templateVars);
$this->managerRegistry->getManager()->persist($notification);
$this->managerRegistry->getManager()->flush($notification);
return $notification;
} | [
"public",
"function",
"addNotification",
"(",
"$",
"recipientId",
",",
"$",
"title",
",",
"$",
"content",
",",
"$",
"template",
",",
"$",
"templateVars",
",",
"$",
"importance",
",",
"$",
"sendImmediately",
")",
"{",
"$",
"notification",
"=",
"new",
"Notif... | Convenience-function to add and save a Notification-entity.
@param int $recipientId the ID of the recipient of this notification => see RecipientProvider.getRecipient($id)
@param string $title the title of the notification. depending on the recipients settings, multiple notifications are sent in one email.
@param string $content the content of the notification
@param string $template the twig-template to render the notification with
@param array $templateVars the parameters used in the twig-template, 'notification' => Notification and 'recipient' => RecipientInterface will be added to this array when rendering the twig-template
@param int $importance important messages are at the top of the notification-emails, un-important at the bottom
@param bool $sendImmediately whether or not to ignore the recipients mailing-preference and send the notification a.s.a.p.
@return Notification | [
"Convenience",
"-",
"function",
"to",
"add",
"and",
"save",
"a",
"Notification",
"-",
"entity",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L564-L578 |
40,919 | azine/email-bundle | Entity/Repositories/SentEmailRepository.php | SentEmailRepository.search | public function search($searchParams = array())
{
$queryBuilder = $this->createQueryBuilder('e');
if (!empty($searchParams)) {
$searchAttributes = array(
'recipients',
'template',
'sent',
'variables',
'token',
);
foreach ($searchAttributes as $attribute) {
if (empty($searchParams[$attribute])) {
continue;
}
$attributeValue = $searchParams[$attribute];
$queryBuilder->andWhere('e.'.$attribute.' LIKE :'.$attribute)
->setParameter($attribute, '%'.$attributeValue.'%');
}
}
return $queryBuilder->getQuery();
} | php | public function search($searchParams = array())
{
$queryBuilder = $this->createQueryBuilder('e');
if (!empty($searchParams)) {
$searchAttributes = array(
'recipients',
'template',
'sent',
'variables',
'token',
);
foreach ($searchAttributes as $attribute) {
if (empty($searchParams[$attribute])) {
continue;
}
$attributeValue = $searchParams[$attribute];
$queryBuilder->andWhere('e.'.$attribute.' LIKE :'.$attribute)
->setParameter($attribute, '%'.$attributeValue.'%');
}
}
return $queryBuilder->getQuery();
} | [
"public",
"function",
"search",
"(",
"$",
"searchParams",
"=",
"array",
"(",
")",
")",
"{",
"$",
"queryBuilder",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'e'",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"searchParams",
")",
")",
"{",
"$"... | Search SentEmails by search params.
@param $searchParams
@return Query | [
"Search",
"SentEmails",
"by",
"search",
"params",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Entity/Repositories/SentEmailRepository.php#L23-L49 |
40,920 | azine/email-bundle | Services/AzineTemplateProvider.php | AzineTemplateProvider.makeImagePathsWebRelative | public function makeImagePathsWebRelative(array $emailVars, $locale)
{
foreach ($emailVars as $key => $value) {
if (is_string($value) && is_file($value)) {
// check if the file is in an allowed_images_folder
$folderKey = $this->isFileAllowed($value);
if (false !== $folderKey) {
// replace the fs-path with the web-path
$fsPathToReplace = $this->getFolderFrom($folderKey);
$filename = substr($value, strlen($fsPathToReplace));
$newValue = $this->getRouter()->generate('azine_email_serve_template_image', array('folderKey' => $folderKey, 'filename' => urlencode($filename), '_locale' => $locale));
$emailVars[$key] = $newValue;
}
} elseif (is_array($value)) {
$emailVars[$key] = $this->makeImagePathsWebRelative($value, $locale);
}
}
return $emailVars;
} | php | public function makeImagePathsWebRelative(array $emailVars, $locale)
{
foreach ($emailVars as $key => $value) {
if (is_string($value) && is_file($value)) {
// check if the file is in an allowed_images_folder
$folderKey = $this->isFileAllowed($value);
if (false !== $folderKey) {
// replace the fs-path with the web-path
$fsPathToReplace = $this->getFolderFrom($folderKey);
$filename = substr($value, strlen($fsPathToReplace));
$newValue = $this->getRouter()->generate('azine_email_serve_template_image', array('folderKey' => $folderKey, 'filename' => urlencode($filename), '_locale' => $locale));
$emailVars[$key] = $newValue;
}
} elseif (is_array($value)) {
$emailVars[$key] = $this->makeImagePathsWebRelative($value, $locale);
}
}
return $emailVars;
} | [
"public",
"function",
"makeImagePathsWebRelative",
"(",
"array",
"$",
"emailVars",
",",
"$",
"locale",
")",
"{",
"foreach",
"(",
"$",
"emailVars",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
"&&",
"is... | Recursively replace all absolute image-file-paths with relative web-paths.
@param array $emailVars
@param string $locale
@return array | [
"Recursively",
"replace",
"all",
"absolute",
"image",
"-",
"file",
"-",
"paths",
"with",
"relative",
"web",
"-",
"paths",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTemplateProvider.php#L491-L510 |
40,921 | azine/email-bundle | Services/AzineEmailTwigExtension.php | AzineEmailTwigExtension.addCampaignParamsToAllUrls | public function addCampaignParamsToAllUrls($html, $campaignParams)
{
$urlPattern = '/(href=[\'|"])(http[s]?\:\/\/\S*)([\'|"])/';
$filteredHtml = preg_replace_callback($urlPattern, function ($matches) use ($campaignParams) {
$start = $matches[1];
$url = $matches[2];
$end = $matches[3];
$domain = parse_url($url, PHP_URL_HOST);
// if the url is not in the list of domains to track then
if (false === array_search($domain, $this->domainsToTrack)) {
// don't append tracking parameters to the url
return $start.$url.$end;
}
// avoid duplicate params and don't replace existing params
$params = array();
foreach ($campaignParams as $nextKey => $nextValue) {
if (false === strpos($url, $nextKey)) {
$params[$nextKey] = $nextValue;
}
}
$urlParams = http_build_query($params);
if (false === strpos($url, '?')) {
$urlParams = '?'.$urlParams;
} else {
$urlParams = '&'.$urlParams;
}
$replacement = $start.$url.$urlParams.$end;
return $replacement;
}, $html);
return $filteredHtml;
} | php | public function addCampaignParamsToAllUrls($html, $campaignParams)
{
$urlPattern = '/(href=[\'|"])(http[s]?\:\/\/\S*)([\'|"])/';
$filteredHtml = preg_replace_callback($urlPattern, function ($matches) use ($campaignParams) {
$start = $matches[1];
$url = $matches[2];
$end = $matches[3];
$domain = parse_url($url, PHP_URL_HOST);
// if the url is not in the list of domains to track then
if (false === array_search($domain, $this->domainsToTrack)) {
// don't append tracking parameters to the url
return $start.$url.$end;
}
// avoid duplicate params and don't replace existing params
$params = array();
foreach ($campaignParams as $nextKey => $nextValue) {
if (false === strpos($url, $nextKey)) {
$params[$nextKey] = $nextValue;
}
}
$urlParams = http_build_query($params);
if (false === strpos($url, '?')) {
$urlParams = '?'.$urlParams;
} else {
$urlParams = '&'.$urlParams;
}
$replacement = $start.$url.$urlParams.$end;
return $replacement;
}, $html);
return $filteredHtml;
} | [
"public",
"function",
"addCampaignParamsToAllUrls",
"(",
"$",
"html",
",",
"$",
"campaignParams",
")",
"{",
"$",
"urlPattern",
"=",
"'/(href=[\\'|\"])(http[s]?\\:\\/\\/\\S*)([\\'|\"])/'",
";",
"$",
"filteredHtml",
"=",
"preg_replace_callback",
"(",
"$",
"urlPattern",
",... | Add the campaign-parameters to all URLs in the html.
@param string $html
@param array $campaignParams
@return string | [
"Add",
"the",
"campaign",
"-",
"parameters",
"to",
"all",
"URLs",
"in",
"the",
"html",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineEmailTwigExtension.php#L112-L150 |
40,922 | azine/email-bundle | Entity/Repositories/NotificationRepository.php | NotificationRepository.getNotificationsToSend | public function getNotificationsToSend($recipientId)
{
$qb = $this->createQueryBuilder('n')
->andWhere('n.sent is null')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId)
->orderBy('n.importance', 'desc')
->orderBy('n.template', 'asc')
->orderBy('n.title', 'asc');
$notifications = $qb->getQuery()->execute();
return $notifications;
} | php | public function getNotificationsToSend($recipientId)
{
$qb = $this->createQueryBuilder('n')
->andWhere('n.sent is null')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId)
->orderBy('n.importance', 'desc')
->orderBy('n.template', 'asc')
->orderBy('n.title', 'asc');
$notifications = $qb->getQuery()->execute();
return $notifications;
} | [
"public",
"function",
"getNotificationsToSend",
"(",
"$",
"recipientId",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'n'",
")",
"->",
"andWhere",
"(",
"'n.sent is null'",
")",
"->",
"andWhere",
"(",
"'n.recipient_id = :recipientId'",
... | Get all notifications that should be sent.
@param $recipientId
@return array of Notification | [
"Get",
"all",
"notifications",
"that",
"should",
"be",
"sent",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Entity/Repositories/NotificationRepository.php#L22-L34 |
40,923 | azine/email-bundle | Entity/Repositories/NotificationRepository.php | NotificationRepository.getNotificationRecipientIds | public function getNotificationRecipientIds()
{
$qb = $this->getEntityManager()->createQueryBuilder()
->select('n.recipient_id')
->distinct()
->from("Azine\EmailBundle\Entity\Notification", 'n')
->andWhere('n.sent is null');
$results = $qb->getQuery()->execute();
$ids = array();
foreach ($results as $next) {
$ids[] = $next['recipient_id'];
}
return $ids;
} | php | public function getNotificationRecipientIds()
{
$qb = $this->getEntityManager()->createQueryBuilder()
->select('n.recipient_id')
->distinct()
->from("Azine\EmailBundle\Entity\Notification", 'n')
->andWhere('n.sent is null');
$results = $qb->getQuery()->execute();
$ids = array();
foreach ($results as $next) {
$ids[] = $next['recipient_id'];
}
return $ids;
} | [
"public",
"function",
"getNotificationRecipientIds",
"(",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"createQueryBuilder",
"(",
")",
"->",
"select",
"(",
"'n.recipient_id'",
")",
"->",
"distinct",
"(",
")",
"->",
"from",... | Get all recipients with unsent Notifications.
@return array | [
"Get",
"all",
"recipients",
"with",
"unsent",
"Notifications",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Entity/Repositories/NotificationRepository.php#L63-L78 |
40,924 | azine/email-bundle | Entity/Repositories/NotificationRepository.php | NotificationRepository.markAllNotificationsAsSentFarInThePast | public function markAllNotificationsAsSentFarInThePast($recipientId)
{
$qb = $this->getEntityManager()->createQueryBuilder()
->update("Azine\EmailBundle\Entity\Notification", 'n')
->set('n.sent', ':farInThePast')
->andWhere('n.sent is null')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId)
->setParameter('farInThePast', new \DateTime('1900-01-01'));
$qb->getQuery()->execute();
} | php | public function markAllNotificationsAsSentFarInThePast($recipientId)
{
$qb = $this->getEntityManager()->createQueryBuilder()
->update("Azine\EmailBundle\Entity\Notification", 'n')
->set('n.sent', ':farInThePast')
->andWhere('n.sent is null')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId)
->setParameter('farInThePast', new \DateTime('1900-01-01'));
$qb->getQuery()->execute();
} | [
"public",
"function",
"markAllNotificationsAsSentFarInThePast",
"(",
"$",
"recipientId",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"createQueryBuilder",
"(",
")",
"->",
"update",
"(",
"\"Azine\\EmailBundle\\Entity\\Notification\"... | Mark all notifications as sent "far in the past". This is used for users that don't want to receive any notifications.
@param $recipientId | [
"Mark",
"all",
"notifications",
"as",
"sent",
"far",
"in",
"the",
"past",
".",
"This",
"is",
"used",
"for",
"users",
"that",
"don",
"t",
"want",
"to",
"receive",
"any",
"notifications",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Entity/Repositories/NotificationRepository.php#L85-L95 |
40,925 | azine/email-bundle | Entity/Repositories/NotificationRepository.php | NotificationRepository.getLastNotificationDate | public function getLastNotificationDate($recipientId)
{
$qb = $this->getEntityManager()->createQueryBuilder()
->select('max(n.sent)')
->from("Azine\EmailBundle\Entity\Notification", 'n')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId);
$results = $qb->getQuery()->execute();
if (null === $results[0][1]) {
// the user has not received any notifications yet ever
$lastNotification = new \DateTime('@0');
} else {
$lastNotification = new \DateTime($results[0][1]);
}
return $lastNotification;
} | php | public function getLastNotificationDate($recipientId)
{
$qb = $this->getEntityManager()->createQueryBuilder()
->select('max(n.sent)')
->from("Azine\EmailBundle\Entity\Notification", 'n')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId);
$results = $qb->getQuery()->execute();
if (null === $results[0][1]) {
// the user has not received any notifications yet ever
$lastNotification = new \DateTime('@0');
} else {
$lastNotification = new \DateTime($results[0][1]);
}
return $lastNotification;
} | [
"public",
"function",
"getLastNotificationDate",
"(",
"$",
"recipientId",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"createQueryBuilder",
"(",
")",
"->",
"select",
"(",
"'max(n.sent)'",
")",
"->",
"from",
"(",
"\"Azine\... | Get the \DateTime of the last Notification that has been sent.
@param $recipientId
@return \DateTime | [
"Get",
"the",
"\\",
"DateTime",
"of",
"the",
"last",
"Notification",
"that",
"has",
"been",
"sent",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Entity/Repositories/NotificationRepository.php#L104-L120 |
40,926 | azine/email-bundle | Services/AzineEmailOpenTrackingCodeBuilder.php | AzineEmailOpenTrackingCodeBuilder.merge | protected function merge($to, $cc, $bcc)
{
if ($to && !is_array($to)) {
$to = array($to);
}
if (!is_array($cc)) {
$cc = array($cc);
}
if (!is_array($bcc)) {
$bcc = array($bcc);
}
$all = array_merge($to, $cc, $bcc);
return implode(';', $all);
} | php | protected function merge($to, $cc, $bcc)
{
if ($to && !is_array($to)) {
$to = array($to);
}
if (!is_array($cc)) {
$cc = array($cc);
}
if (!is_array($bcc)) {
$bcc = array($bcc);
}
$all = array_merge($to, $cc, $bcc);
return implode(';', $all);
} | [
"protected",
"function",
"merge",
"(",
"$",
"to",
",",
"$",
"cc",
",",
"$",
"bcc",
")",
"{",
"if",
"(",
"$",
"to",
"&&",
"!",
"is_array",
"(",
"$",
"to",
")",
")",
"{",
"$",
"to",
"=",
"array",
"(",
"$",
"to",
")",
";",
"}",
"if",
"(",
"!... | concatenate all recipients into an array and implode with ';' to a string.
@param string|array $to
@param string|array $cc
@param string|array $bcc
@return string | [
"concatenate",
"all",
"recipients",
"into",
"an",
"array",
"and",
"implode",
"with",
";",
"to",
"a",
"string",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineEmailOpenTrackingCodeBuilder.php#L107-L121 |
40,927 | azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.indexAction | public function indexAction(Request $request)
{
$customEmail = $request->get('customEmail', 'custom@email.com');
$templates = $this->get('azine_email_web_view_service')->getTemplatesForWebPreView();
$emails = $this->get('azine_email_web_view_service')->getTestMailAccounts();
return $this->get('templating')
->renderResponse('AzineEmailBundle:Webview:index.html.twig',
array(
'customEmail' => $customEmail,
'templates' => $templates,
'emails' => $emails,
));
} | php | public function indexAction(Request $request)
{
$customEmail = $request->get('customEmail', 'custom@email.com');
$templates = $this->get('azine_email_web_view_service')->getTemplatesForWebPreView();
$emails = $this->get('azine_email_web_view_service')->getTestMailAccounts();
return $this->get('templating')
->renderResponse('AzineEmailBundle:Webview:index.html.twig',
array(
'customEmail' => $customEmail,
'templates' => $templates,
'emails' => $emails,
));
} | [
"public",
"function",
"indexAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"customEmail",
"=",
"$",
"request",
"->",
"get",
"(",
"'customEmail'",
",",
"'custom@email.com'",
")",
";",
"$",
"templates",
"=",
"$",
"this",
"->",
"get",
"(",
"'azine_em... | Show a set of options to view html- and text-versions of email in the browser and send them as emails to test-accounts. | [
"Show",
"a",
"set",
"of",
"options",
"to",
"view",
"html",
"-",
"and",
"text",
"-",
"versions",
"of",
"email",
"in",
"the",
"browser",
"and",
"send",
"them",
"as",
"emails",
"to",
"test",
"-",
"accounts",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L35-L48 |
40,928 | azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.webPreViewAction | public function webPreViewAction(Request $request, $template, $format = null)
{
if ('txt' !== $format) {
$format = 'html';
}
$template = urldecode($template);
$locale = $request->getLocale();
// merge request vars with dummyVars, but make sure request vars remain as they are.
$emailVars = array_merge(array(), $request->query->all());
$emailVars = $this->get('azine_email_web_view_service')->getDummyVarsFor($template, $locale, $emailVars);
$emailVars = array_merge($emailVars, $request->query->all());
// add the styles
$emailVars = $this->getTemplateProviderService()->addTemplateVariablesFor($template, $emailVars);
// add the from-email for the footer-text
if (!array_key_exists('fromEmail', $emailVars)) {
$noReply = $this->getParameter('azine_email_no_reply');
$emailVars['fromEmail'] = $noReply['email'];
$emailVars['fromName'] = $noReply['name'];
}
// set the emailLocale for the templates
$emailVars['emailLocale'] = $locale;
// replace absolute image-paths with relative ones.
$emailVars = $this->getTemplateProviderService()->makeImagePathsWebRelative($emailVars, $locale);
// add code-snippets
$emailVars = $this->getTemplateProviderService()->addTemplateSnippetsWithImagesFor($template, $emailVars, $locale);
// render & return email
$response = $this->renderResponse("$template.$format.twig", $emailVars);
// add campaign tracking params
$campaignParams = $this->getTemplateProviderService()->getCampaignParamsFor($template, $emailVars);
$campaignParams['utm_medium'] = 'webPreview';
if (sizeof($campaignParams) > 0) {
$htmlBody = $response->getContent();
$htmlBody = $this->get('azine.email.bundle.twig.filters')->addCampaignParamsToAllUrls($htmlBody, $campaignParams);
$emailOpenTrackingCodeBuilder = $this->get('azine_email_email_open_tracking_code_builder');
if ($emailOpenTrackingCodeBuilder) {
// add an image at the end of the html tag with the tracking-params to track email-opens
$imgTrackingCode = $emailOpenTrackingCodeBuilder->getTrackingImgCode($template, $campaignParams, $emailVars, 'dummy', 'dummy@from.email.com', null, null);
if ($imgTrackingCode && strlen($imgTrackingCode) > 0) {
// replace the tracking url, so no request is made to the real tracking system.
$imgTrackingCode = str_replace('://', '://webview-dummy-domain.', $imgTrackingCode);
$htmlCloseTagPosition = strpos($htmlBody, '</html>');
$htmlBody = substr_replace($htmlBody, $imgTrackingCode, $htmlCloseTagPosition, 0);
}
}
$response->setContent($htmlBody);
}
// if the requested format is txt, remove the html-part
if ('txt' == $format) {
// set the correct content-type
$response->headers->set('Content-Type', 'text/plain');
// cut away the html-part
$content = $response->getContent();
$textEnd = stripos($content, '<!doctype');
$response->setContent(substr($content, 0, $textEnd));
}
return $response;
} | php | public function webPreViewAction(Request $request, $template, $format = null)
{
if ('txt' !== $format) {
$format = 'html';
}
$template = urldecode($template);
$locale = $request->getLocale();
// merge request vars with dummyVars, but make sure request vars remain as they are.
$emailVars = array_merge(array(), $request->query->all());
$emailVars = $this->get('azine_email_web_view_service')->getDummyVarsFor($template, $locale, $emailVars);
$emailVars = array_merge($emailVars, $request->query->all());
// add the styles
$emailVars = $this->getTemplateProviderService()->addTemplateVariablesFor($template, $emailVars);
// add the from-email for the footer-text
if (!array_key_exists('fromEmail', $emailVars)) {
$noReply = $this->getParameter('azine_email_no_reply');
$emailVars['fromEmail'] = $noReply['email'];
$emailVars['fromName'] = $noReply['name'];
}
// set the emailLocale for the templates
$emailVars['emailLocale'] = $locale;
// replace absolute image-paths with relative ones.
$emailVars = $this->getTemplateProviderService()->makeImagePathsWebRelative($emailVars, $locale);
// add code-snippets
$emailVars = $this->getTemplateProviderService()->addTemplateSnippetsWithImagesFor($template, $emailVars, $locale);
// render & return email
$response = $this->renderResponse("$template.$format.twig", $emailVars);
// add campaign tracking params
$campaignParams = $this->getTemplateProviderService()->getCampaignParamsFor($template, $emailVars);
$campaignParams['utm_medium'] = 'webPreview';
if (sizeof($campaignParams) > 0) {
$htmlBody = $response->getContent();
$htmlBody = $this->get('azine.email.bundle.twig.filters')->addCampaignParamsToAllUrls($htmlBody, $campaignParams);
$emailOpenTrackingCodeBuilder = $this->get('azine_email_email_open_tracking_code_builder');
if ($emailOpenTrackingCodeBuilder) {
// add an image at the end of the html tag with the tracking-params to track email-opens
$imgTrackingCode = $emailOpenTrackingCodeBuilder->getTrackingImgCode($template, $campaignParams, $emailVars, 'dummy', 'dummy@from.email.com', null, null);
if ($imgTrackingCode && strlen($imgTrackingCode) > 0) {
// replace the tracking url, so no request is made to the real tracking system.
$imgTrackingCode = str_replace('://', '://webview-dummy-domain.', $imgTrackingCode);
$htmlCloseTagPosition = strpos($htmlBody, '</html>');
$htmlBody = substr_replace($htmlBody, $imgTrackingCode, $htmlCloseTagPosition, 0);
}
}
$response->setContent($htmlBody);
}
// if the requested format is txt, remove the html-part
if ('txt' == $format) {
// set the correct content-type
$response->headers->set('Content-Type', 'text/plain');
// cut away the html-part
$content = $response->getContent();
$textEnd = stripos($content, '<!doctype');
$response->setContent(substr($content, 0, $textEnd));
}
return $response;
} | [
"public",
"function",
"webPreViewAction",
"(",
"Request",
"$",
"request",
",",
"$",
"template",
",",
"$",
"format",
"=",
"null",
")",
"{",
"if",
"(",
"'txt'",
"!==",
"$",
"format",
")",
"{",
"$",
"format",
"=",
"'html'",
";",
"}",
"$",
"template",
"=... | Show a web-preview-version of an email-template, filled with dummy-content.
@param string $format
@return Response | [
"Show",
"a",
"web",
"-",
"preview",
"-",
"version",
"of",
"an",
"email",
"-",
"template",
"filled",
"with",
"dummy",
"-",
"content",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L57-L127 |
40,929 | azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.webViewAction | public function webViewAction(Request $request, $token)
{
// find email recipients, template & params
$sentEmail = $this->getSentEmailForToken($token);
// check if the sent email is available
if (null !== $sentEmail) {
// check if the current user is allowed to see the email
if ($this->userIsAllowedToSeeThisMail($sentEmail)) {
$template = $sentEmail->getTemplate();
$emailVars = $sentEmail->getVariables();
// re-attach all entities to the EntityManager.
$this->reAttachAllEntities($emailVars);
// remove the web-view-token from the param-array
$templateProvider = $this->getTemplateProviderService();
unset($emailVars[$templateProvider->getWebViewTokenId()]);
// render & return email
$response = $this->renderResponse("$template.html.twig", $emailVars);
$campaignParams = $templateProvider->getCampaignParamsFor($template, $emailVars);
if (null != $campaignParams && sizeof($campaignParams) > 0) {
$response->setContent($this->get('azine.email.bundle.twig.filters')->addCampaignParamsToAllUrls($response->getContent(), $campaignParams));
}
return $response;
// if the user is not allowed to see this mail
}
$msg = $this->get('translator')->trans('web.pre.view.test.mail.access.denied');
throw new AccessDeniedException($msg);
}
// the parameters-array is null => the email is not available in webView
$days = $this->getParameter('azine_email_web_view_retention');
$response = $this->renderResponse('AzineEmailBundle:Webview:mail.not.available.html.twig', array('days' => $days));
$response->setStatusCode(404);
return $response;
} | php | public function webViewAction(Request $request, $token)
{
// find email recipients, template & params
$sentEmail = $this->getSentEmailForToken($token);
// check if the sent email is available
if (null !== $sentEmail) {
// check if the current user is allowed to see the email
if ($this->userIsAllowedToSeeThisMail($sentEmail)) {
$template = $sentEmail->getTemplate();
$emailVars = $sentEmail->getVariables();
// re-attach all entities to the EntityManager.
$this->reAttachAllEntities($emailVars);
// remove the web-view-token from the param-array
$templateProvider = $this->getTemplateProviderService();
unset($emailVars[$templateProvider->getWebViewTokenId()]);
// render & return email
$response = $this->renderResponse("$template.html.twig", $emailVars);
$campaignParams = $templateProvider->getCampaignParamsFor($template, $emailVars);
if (null != $campaignParams && sizeof($campaignParams) > 0) {
$response->setContent($this->get('azine.email.bundle.twig.filters')->addCampaignParamsToAllUrls($response->getContent(), $campaignParams));
}
return $response;
// if the user is not allowed to see this mail
}
$msg = $this->get('translator')->trans('web.pre.view.test.mail.access.denied');
throw new AccessDeniedException($msg);
}
// the parameters-array is null => the email is not available in webView
$days = $this->getParameter('azine_email_web_view_retention');
$response = $this->renderResponse('AzineEmailBundle:Webview:mail.not.available.html.twig', array('days' => $days));
$response->setStatusCode(404);
return $response;
} | [
"public",
"function",
"webViewAction",
"(",
"Request",
"$",
"request",
",",
"$",
"token",
")",
"{",
"// find email recipients, template & params",
"$",
"sentEmail",
"=",
"$",
"this",
"->",
"getSentEmailForToken",
"(",
"$",
"token",
")",
";",
"// check if the sent em... | Show a web-version of an email that has been sent to recipients and has been stored in the database.
@param Request $request
@param string $token
@return Response | [
"Show",
"a",
"web",
"-",
"version",
"of",
"an",
"email",
"that",
"has",
"been",
"sent",
"to",
"recipients",
"and",
"has",
"been",
"stored",
"in",
"the",
"database",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L137-L179 |
40,930 | azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.userIsAllowedToSeeThisMail | private function userIsAllowedToSeeThisMail(SentEmail $mail)
{
$recipients = $mail->getRecipients();
// it is a public email
if (null === $recipients) {
return true;
}
// get the current user
$currentUser = null;
if (!$this->has('security.token_storage')) {
// @codeCoverageIgnoreStart
throw new \LogicException('The SecurityBundle is not registered in your application.');
// @codeCoverageIgnoreEnd
}
$token = $this->get('security.token_storage')->getToken();
// check if the token is not null and the user in the token an object
if ($token instanceof TokenInterface && is_object($token->getUser())) {
$currentUser = $token->getUser();
}
// it is not a public email, and a user is logged in
if (null !== $currentUser) {
// the user is among the recipients
if (false !== array_search($currentUser->getEmail(), $recipients)) {
return true;
}
// the user is admin
if ($currentUser->hasRole('ROLE_ADMIN')) {
return true;
}
}
// not public email, but
// - there is no user, or
// - the user is not among the recipients and
// - the user not an admin-user either
return false;
} | php | private function userIsAllowedToSeeThisMail(SentEmail $mail)
{
$recipients = $mail->getRecipients();
// it is a public email
if (null === $recipients) {
return true;
}
// get the current user
$currentUser = null;
if (!$this->has('security.token_storage')) {
// @codeCoverageIgnoreStart
throw new \LogicException('The SecurityBundle is not registered in your application.');
// @codeCoverageIgnoreEnd
}
$token = $this->get('security.token_storage')->getToken();
// check if the token is not null and the user in the token an object
if ($token instanceof TokenInterface && is_object($token->getUser())) {
$currentUser = $token->getUser();
}
// it is not a public email, and a user is logged in
if (null !== $currentUser) {
// the user is among the recipients
if (false !== array_search($currentUser->getEmail(), $recipients)) {
return true;
}
// the user is admin
if ($currentUser->hasRole('ROLE_ADMIN')) {
return true;
}
}
// not public email, but
// - there is no user, or
// - the user is not among the recipients and
// - the user not an admin-user either
return false;
} | [
"private",
"function",
"userIsAllowedToSeeThisMail",
"(",
"SentEmail",
"$",
"mail",
")",
"{",
"$",
"recipients",
"=",
"$",
"mail",
"->",
"getRecipients",
"(",
")",
";",
"// it is a public email",
"if",
"(",
"null",
"===",
"$",
"recipients",
")",
"{",
"return",... | Check if the user is allowed to see the email.
=> the mail is public or the user is among the recipients or the user is an admin.
@param SentEmail $mail
@return bool | [
"Check",
"if",
"the",
"user",
"is",
"allowed",
"to",
"see",
"the",
"email",
".",
"=",
">",
"the",
"mail",
"is",
"public",
"or",
"the",
"user",
"is",
"among",
"the",
"recipients",
"or",
"the",
"user",
"is",
"an",
"admin",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L189-L230 |
40,931 | azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.serveImageAction | public function serveImageAction(Request $request, $folderKey, $filename)
{
$folder = $this->getTemplateProviderService()->getFolderFrom($folderKey);
if (false !== $folder) {
$fullPath = $folder.urldecode($filename);
$response = BinaryFileResponse::create($fullPath);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
$response->headers->set('Content-Type', 'image');
return $response;
}
throw new FileNotFoundException($filename);
} | php | public function serveImageAction(Request $request, $folderKey, $filename)
{
$folder = $this->getTemplateProviderService()->getFolderFrom($folderKey);
if (false !== $folder) {
$fullPath = $folder.urldecode($filename);
$response = BinaryFileResponse::create($fullPath);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
$response->headers->set('Content-Type', 'image');
return $response;
}
throw new FileNotFoundException($filename);
} | [
"public",
"function",
"serveImageAction",
"(",
"Request",
"$",
"request",
",",
"$",
"folderKey",
",",
"$",
"filename",
")",
"{",
"$",
"folder",
"=",
"$",
"this",
"->",
"getTemplateProviderService",
"(",
")",
"->",
"getFolderFrom",
"(",
"$",
"folderKey",
")",... | Serve the image from the templates-folder.
@param Request $request
@param string $folderKey
@param string $filename
@return BinaryFileResponse | [
"Serve",
"the",
"image",
"from",
"the",
"templates",
"-",
"folder",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L273-L286 |
40,932 | azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.checkSpamScoreOfSentEmailAction | public function checkSpamScoreOfSentEmailAction(Request $request)
{
$msgString = $request->get('emailSource');
$spamReport = $this->getSpamIndexReport($msgString);
$spamInfo = '';
if (is_array($spamReport)) {
if (array_key_exists('curlHttpCode', $spamReport) && 200 == $spamReport['curlHttpCode'] && $spamReport['success'] && array_key_exists('score', $spamReport)) {
$spamScore = $spamReport['score'];
$spamInfo = "SpamScore: $spamScore! \n".$spamReport['report'];
//@codeCoverageIgnoreStart
// this only happens if the spam-check-server has a problem / is not responding
} else {
if (array_key_exists('curlHttpCode', $spamReport) && array_key_exists('curlError', $spamReport) && array_key_exists('message', $spamReport)) {
$spamInfo = 'Getting the spam-info failed.
HttpCode: '.$spamReport['curlHttpCode'].'
cURL-Error: '.$spamReport['curlError'].'
SpamReportMsg: '.$spamReport['message'];
} elseif (null !== $spamReport && is_array($spamReport)) {
$spamInfo = 'Getting the spam-info failed. This was returned:
---Start----------------------------------------------
'.implode(";\n", $spamReport).'
---End------------------------------------------------';
}
//@codeCoverageIgnoreEnd
}
}
return new JsonResponse(array('result' => $spamInfo));
} | php | public function checkSpamScoreOfSentEmailAction(Request $request)
{
$msgString = $request->get('emailSource');
$spamReport = $this->getSpamIndexReport($msgString);
$spamInfo = '';
if (is_array($spamReport)) {
if (array_key_exists('curlHttpCode', $spamReport) && 200 == $spamReport['curlHttpCode'] && $spamReport['success'] && array_key_exists('score', $spamReport)) {
$spamScore = $spamReport['score'];
$spamInfo = "SpamScore: $spamScore! \n".$spamReport['report'];
//@codeCoverageIgnoreStart
// this only happens if the spam-check-server has a problem / is not responding
} else {
if (array_key_exists('curlHttpCode', $spamReport) && array_key_exists('curlError', $spamReport) && array_key_exists('message', $spamReport)) {
$spamInfo = 'Getting the spam-info failed.
HttpCode: '.$spamReport['curlHttpCode'].'
cURL-Error: '.$spamReport['curlError'].'
SpamReportMsg: '.$spamReport['message'];
} elseif (null !== $spamReport && is_array($spamReport)) {
$spamInfo = 'Getting the spam-info failed. This was returned:
---Start----------------------------------------------
'.implode(";\n", $spamReport).'
---End------------------------------------------------';
}
//@codeCoverageIgnoreEnd
}
}
return new JsonResponse(array('result' => $spamInfo));
} | [
"public",
"function",
"checkSpamScoreOfSentEmailAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"msgString",
"=",
"$",
"request",
"->",
"get",
"(",
"'emailSource'",
")",
";",
"$",
"spamReport",
"=",
"$",
"this",
"->",
"getSpamIndexReport",
"(",
"$",
... | Ajax action to check the spam-score for the pasted email-source. | [
"Ajax",
"action",
"to",
"check",
"the",
"spam",
"-",
"score",
"for",
"the",
"pasted",
"email",
"-",
"source",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L455-L483 |
40,933 | azine/email-bundle | Controller/AzineEmailController.php | AzineEmailController.emailsDashboardAction | public function emailsDashboardAction(Request $request)
{
$form = $this->createForm(SentEmailType::class);
$form->handleRequest($request);
$searchParams = $form->getData();
/** @var SentEmailRepository $repository */
$repository = $this->getDoctrine()->getManager()->getRepository(SentEmail::class);
$query = $repository->search($searchParams);
$pagination = $this->get('knp_paginator')->paginate($query, $request->query->getInt('page', 1));
return $this->render('AzineEmailBundle::emailsDashboard.html.twig',
array('form' => $form->createView(), 'pagination' => $pagination));
} | php | public function emailsDashboardAction(Request $request)
{
$form = $this->createForm(SentEmailType::class);
$form->handleRequest($request);
$searchParams = $form->getData();
/** @var SentEmailRepository $repository */
$repository = $this->getDoctrine()->getManager()->getRepository(SentEmail::class);
$query = $repository->search($searchParams);
$pagination = $this->get('knp_paginator')->paginate($query, $request->query->getInt('page', 1));
return $this->render('AzineEmailBundle::emailsDashboard.html.twig',
array('form' => $form->createView(), 'pagination' => $pagination));
} | [
"public",
"function",
"emailsDashboardAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"form",
"=",
"$",
"this",
"->",
"createForm",
"(",
"SentEmailType",
"::",
"class",
")",
";",
"$",
"form",
"->",
"handleRequest",
"(",
"$",
"request",
")",
";",
... | Displays an Emails-Dashboard with filters for each property of SentEmails entity and links to
emailDetailsByToken & webView actions for each email.
@param Request $request
@return Response | [
"Displays",
"an",
"Emails",
"-",
"Dashboard",
"with",
"filters",
"for",
"each",
"property",
"of",
"SentEmails",
"entity",
"and",
"links",
"to",
"emailDetailsByToken",
"&",
"webView",
"actions",
"for",
"each",
"email",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailController.php#L25-L37 |
40,934 | azine/email-bundle | Controller/AzineEmailController.php | AzineEmailController.emailDetailsByTokenAction | public function emailDetailsByTokenAction(Request $request, $token)
{
$email = $this->getDoctrine()->getManager()->getRepository(SentEmail::class)
->findOneByToken($token);
if ($email instanceof SentEmail) {
$recipients = implode(', ', $email->getRecipients());
$variables = implode(', ', array_keys($email->getVariables()));
return $this->render('AzineEmailBundle::sentEmailDetails.html.twig',
array('email' => $email, 'recipients' => $recipients, 'variables' => $variables));
}
// the parameters-array is null => the email is not available in webView
$days = $this->getParameter('azine_email_web_view_retention');
$response = $this->render('AzineEmailBundle:Webview:mail.not.available.html.twig', array('days' => $days));
$response->setStatusCode(404);
return $response;
} | php | public function emailDetailsByTokenAction(Request $request, $token)
{
$email = $this->getDoctrine()->getManager()->getRepository(SentEmail::class)
->findOneByToken($token);
if ($email instanceof SentEmail) {
$recipients = implode(', ', $email->getRecipients());
$variables = implode(', ', array_keys($email->getVariables()));
return $this->render('AzineEmailBundle::sentEmailDetails.html.twig',
array('email' => $email, 'recipients' => $recipients, 'variables' => $variables));
}
// the parameters-array is null => the email is not available in webView
$days = $this->getParameter('azine_email_web_view_retention');
$response = $this->render('AzineEmailBundle:Webview:mail.not.available.html.twig', array('days' => $days));
$response->setStatusCode(404);
return $response;
} | [
"public",
"function",
"emailDetailsByTokenAction",
"(",
"Request",
"$",
"request",
",",
"$",
"token",
")",
"{",
"$",
"email",
"=",
"$",
"this",
"->",
"getDoctrine",
"(",
")",
"->",
"getManager",
"(",
")",
"->",
"getRepository",
"(",
"SentEmail",
"::",
"cla... | Displays an extended view of SentEmail entity searched by a token property.
@param string $token
@return Response | [
"Displays",
"an",
"extended",
"view",
"of",
"SentEmail",
"entity",
"searched",
"by",
"a",
"token",
"property",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailController.php#L46-L65 |
40,935 | azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.removeUnreferecedEmbededItemsFromMessage | private function removeUnreferecedEmbededItemsFromMessage(\Swift_Message $message, $params, $htmlBody)
{
foreach ($params as $key => $value) {
// remove unreferenced attachments from contentItems too.
if ('contentItems' === $key) {
foreach ($value as $contentItemParams) {
$message = $this->removeUnreferecedEmbededItemsFromMessage($message, $contentItemParams, $htmlBody);
}
} else {
// check if the embeded items are referenced in the templates
$isEmbededItem = is_string($value) && 1 == preg_match($this->encodedItemIdPattern, $value);
if ($isEmbededItem && false === stripos($htmlBody, $value)) {
// remove unreferenced items
$children = array();
foreach ($message->getChildren() as $attachment) {
if ('cid:'.$attachment->getId() != $value) {
$children[] = $attachment;
}
}
$message->setChildren($children);
}
}
}
return $message;
} | php | private function removeUnreferecedEmbededItemsFromMessage(\Swift_Message $message, $params, $htmlBody)
{
foreach ($params as $key => $value) {
// remove unreferenced attachments from contentItems too.
if ('contentItems' === $key) {
foreach ($value as $contentItemParams) {
$message = $this->removeUnreferecedEmbededItemsFromMessage($message, $contentItemParams, $htmlBody);
}
} else {
// check if the embeded items are referenced in the templates
$isEmbededItem = is_string($value) && 1 == preg_match($this->encodedItemIdPattern, $value);
if ($isEmbededItem && false === stripos($htmlBody, $value)) {
// remove unreferenced items
$children = array();
foreach ($message->getChildren() as $attachment) {
if ('cid:'.$attachment->getId() != $value) {
$children[] = $attachment;
}
}
$message->setChildren($children);
}
}
}
return $message;
} | [
"private",
"function",
"removeUnreferecedEmbededItemsFromMessage",
"(",
"\\",
"Swift_Message",
"$",
"message",
",",
"$",
"params",
",",
"$",
"htmlBody",
")",
"{",
"foreach",
"(",
"$",
"params",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"// remove unrefer... | Remove all Embeded Attachments that are not referenced in the html-body from the message
to avoid using unneccary bandwidth.
@param \Swift_Message $message
@param array $params the parameters used to render the html
@param string $htmlBody
@return \Swift_Message | [
"Remove",
"all",
"Embeded",
"Attachments",
"that",
"are",
"not",
"referenced",
"in",
"the",
"html",
"-",
"body",
"from",
"the",
"message",
"to",
"avoid",
"using",
"unneccary",
"bandwidth",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L327-L355 |
40,936 | azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.loadTemplate | private function loadTemplate($template)
{
if (!array_key_exists($template, $this->templateCache)) {
$this->templateCache[$template] = $this->twig->loadTemplate($template);
}
return $this->templateCache[$template];
} | php | private function loadTemplate($template)
{
if (!array_key_exists($template, $this->templateCache)) {
$this->templateCache[$template] = $this->twig->loadTemplate($template);
}
return $this->templateCache[$template];
} | [
"private",
"function",
"loadTemplate",
"(",
"$",
"template",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"template",
",",
"$",
"this",
"->",
"templateCache",
")",
")",
"{",
"$",
"this",
"->",
"templateCache",
"[",
"$",
"template",
"]",
"=",
... | Get the template from the cache if it was loaded already.
@param string $template
@return \Twig_Template | [
"Get",
"the",
"template",
"from",
"the",
"cache",
"if",
"it",
"was",
"loaded",
"already",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L364-L371 |
40,937 | azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.embedImages | private function embedImages(&$message, &$params)
{
// loop through the array
foreach ($params as $key => $value) {
// if the current value is an array
if (is_array($value)) {
// search for more images deeper in the arrays
$value = $this->embedImages($message, $value);
$params[$key] = $value;
// if the current value is an existing file from the image-folder, embed it
} elseif (is_string($value)) {
if (is_file($value)) {
// check if the file is from an allowed folder
if (false !== $this->templateProvider->isFileAllowed($value)) {
$encodedImage = $this->cachedEmbedImage($value);
if (null !== $encodedImage) {
$id = $message->embed($encodedImage);
$params[$key] = $id;
}
}
// the $filePath isn't a regular file
} else {
// add a null-value to the cache for this path, so we don't try again.
$this->imageCache[$value] = null;
}
//if the current value is a generated image
} elseif (is_resource($value) && 0 == stripos(get_resource_type($value), 'gd')) {
// get the image-data as string
ob_start();
imagepng($value);
$imageData = ob_get_clean();
// encode the image
$encodedImage = new \Swift_Image($imageData, 'generatedImage'.md5($imageData));
$id = $message->embed($encodedImage);
$params[$key] = $id;
}
// don't do anything
}
// remove duplicate-attachments
$message->setChildren(array_unique($message->getChildren()));
return $params;
} | php | private function embedImages(&$message, &$params)
{
// loop through the array
foreach ($params as $key => $value) {
// if the current value is an array
if (is_array($value)) {
// search for more images deeper in the arrays
$value = $this->embedImages($message, $value);
$params[$key] = $value;
// if the current value is an existing file from the image-folder, embed it
} elseif (is_string($value)) {
if (is_file($value)) {
// check if the file is from an allowed folder
if (false !== $this->templateProvider->isFileAllowed($value)) {
$encodedImage = $this->cachedEmbedImage($value);
if (null !== $encodedImage) {
$id = $message->embed($encodedImage);
$params[$key] = $id;
}
}
// the $filePath isn't a regular file
} else {
// add a null-value to the cache for this path, so we don't try again.
$this->imageCache[$value] = null;
}
//if the current value is a generated image
} elseif (is_resource($value) && 0 == stripos(get_resource_type($value), 'gd')) {
// get the image-data as string
ob_start();
imagepng($value);
$imageData = ob_get_clean();
// encode the image
$encodedImage = new \Swift_Image($imageData, 'generatedImage'.md5($imageData));
$id = $message->embed($encodedImage);
$params[$key] = $id;
}
// don't do anything
}
// remove duplicate-attachments
$message->setChildren(array_unique($message->getChildren()));
return $params;
} | [
"private",
"function",
"embedImages",
"(",
"&",
"$",
"message",
",",
"&",
"$",
"params",
")",
"{",
"// loop through the array",
"foreach",
"(",
"$",
"params",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"// if the current value is an array",
"if",
"(",
"... | Recursively embed all images in the array into the message.
@param \Swift_Message $message
@param array $params
@return array $params | [
"Recursively",
"embed",
"all",
"images",
"in",
"the",
"array",
"into",
"the",
"message",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L381-L428 |
40,938 | azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.cachedEmbedImage | private function cachedEmbedImage($filePath)
{
$filePath = realpath($filePath);
if (!array_key_exists($filePath, $this->imageCache)) {
if (is_file($filePath)) {
$image = \Swift_Image::fromPath($filePath);
$id = $image->getId();
// $id and $value must not be the same => this happens if the file cannot be found/read
if ($id == $filePath) {
// @codeCoverageIgnoreStart
// add a null-value to the cache for this path, so we don't try again.
$this->imageCache[$filePath] = null;
} else {
// @codeCoverageIgnoreEnd
// add the image to the cache
$this->imageCache[$filePath] = $image;
}
}
}
return $this->imageCache[$filePath];
} | php | private function cachedEmbedImage($filePath)
{
$filePath = realpath($filePath);
if (!array_key_exists($filePath, $this->imageCache)) {
if (is_file($filePath)) {
$image = \Swift_Image::fromPath($filePath);
$id = $image->getId();
// $id and $value must not be the same => this happens if the file cannot be found/read
if ($id == $filePath) {
// @codeCoverageIgnoreStart
// add a null-value to the cache for this path, so we don't try again.
$this->imageCache[$filePath] = null;
} else {
// @codeCoverageIgnoreEnd
// add the image to the cache
$this->imageCache[$filePath] = $image;
}
}
}
return $this->imageCache[$filePath];
} | [
"private",
"function",
"cachedEmbedImage",
"(",
"$",
"filePath",
")",
"{",
"$",
"filePath",
"=",
"realpath",
"(",
"$",
"filePath",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"filePath",
",",
"$",
"this",
"->",
"imageCache",
")",
")",
"{",
... | Get the Swift_Image for the file.
@param string $filePath
@return \Swift_Image|null | [
"Get",
"the",
"Swift_Image",
"for",
"the",
"file",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L437-L459 |
40,939 | azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.sendMessage | protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
{
// get the subject from the template
// => make sure the subject block exists in your fos-templates (FOSUserBundle:Registration:email.txt.twig & FOSUserBundle:Resetting:email.txt.twig)
$twigTemplate = $this->loadTemplate($templateName);
$subject = $twigTemplate->renderBlock('subject', $context);
return $this->sendSingleEmail($toEmail, null, $subject, $context, $templateName, $this->translator->getLocale(), $fromEmail);
} | php | protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
{
// get the subject from the template
// => make sure the subject block exists in your fos-templates (FOSUserBundle:Registration:email.txt.twig & FOSUserBundle:Resetting:email.txt.twig)
$twigTemplate = $this->loadTemplate($templateName);
$subject = $twigTemplate->renderBlock('subject', $context);
return $this->sendSingleEmail($toEmail, null, $subject, $context, $templateName, $this->translator->getLocale(), $fromEmail);
} | [
"protected",
"function",
"sendMessage",
"(",
"$",
"templateName",
",",
"$",
"context",
",",
"$",
"fromEmail",
",",
"$",
"toEmail",
")",
"{",
"// get the subject from the template",
"// => make sure the subject block exists in your fos-templates (FOSUserBundle:Registration:email.t... | Override the fosuserbundles original sendMessage, to embed template variables etc. into html-emails.
@param string $templateName
@param array $context
@param string $fromEmail
@param string $toEmail
@return bool true if the mail was sent successfully, else false | [
"Override",
"the",
"fosuserbundles",
"original",
"sendMessage",
"to",
"embed",
"template",
"variables",
"etc",
".",
"into",
"html",
"-",
"emails",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L496-L504 |
40,940 | azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.sendUpdateEmailConfirmation | public function sendUpdateEmailConfirmation(UserInterface $user, $confirmationUrl, $toEmail)
{
$template = $this->parameters['template']['email_updating'];
$fromEmail = $this->parameters['from_email']['confirmation'];
$context = array(
'user' => $user,
'confirmationUrl' => $confirmationUrl,
);
$this->sendMessage($template, $context, $fromEmail, $toEmail);
} | php | public function sendUpdateEmailConfirmation(UserInterface $user, $confirmationUrl, $toEmail)
{
$template = $this->parameters['template']['email_updating'];
$fromEmail = $this->parameters['from_email']['confirmation'];
$context = array(
'user' => $user,
'confirmationUrl' => $confirmationUrl,
);
$this->sendMessage($template, $context, $fromEmail, $toEmail);
} | [
"public",
"function",
"sendUpdateEmailConfirmation",
"(",
"UserInterface",
"$",
"user",
",",
"$",
"confirmationUrl",
",",
"$",
"toEmail",
")",
"{",
"$",
"template",
"=",
"$",
"this",
"->",
"parameters",
"[",
"'template'",
"]",
"[",
"'email_updating'",
"]",
";"... | Send confirmation link to specified new user email.
@param UserInterface $user
@param $confirmationUrl
@param $toEmail
@return bool | [
"Send",
"confirmation",
"link",
"to",
"specified",
"new",
"user",
"email",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L535-L545 |
40,941 | laravel-notification-channels/gcm | src/Packet.php | Packet.toJson | public function toJson()
{
$json = [];
if (! empty($this->registrationIds)) {
$json['registration_ids'] = $this->registrationIds;
}
if ($this->collapseKey) {
$json['collapse_key'] = $this->collapseKey;
}
if (! empty($this->data)) {
$json['data'] = $this->data;
}
if (! empty($this->notification)) {
$json['notification'] = $this->notification;
}
if ($this->delayWhileIdle) {
$json['delay_while_idle'] = $this->delayWhileIdle;
}
if ($this->timeToLive != 2419200) {
$json['time_to_live'] = $this->timeToLive;
}
if ($this->restrictedPackageName) {
$json['restricted_package_name'] = $this->restrictedPackageName;
}
if ($this->dryRun) {
$json['dry_run'] = $this->dryRun;
}
return Json::encode($json);
} | php | public function toJson()
{
$json = [];
if (! empty($this->registrationIds)) {
$json['registration_ids'] = $this->registrationIds;
}
if ($this->collapseKey) {
$json['collapse_key'] = $this->collapseKey;
}
if (! empty($this->data)) {
$json['data'] = $this->data;
}
if (! empty($this->notification)) {
$json['notification'] = $this->notification;
}
if ($this->delayWhileIdle) {
$json['delay_while_idle'] = $this->delayWhileIdle;
}
if ($this->timeToLive != 2419200) {
$json['time_to_live'] = $this->timeToLive;
}
if ($this->restrictedPackageName) {
$json['restricted_package_name'] = $this->restrictedPackageName;
}
if ($this->dryRun) {
$json['dry_run'] = $this->dryRun;
}
return Json::encode($json);
} | [
"public",
"function",
"toJson",
"(",
")",
"{",
"$",
"json",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"registrationIds",
")",
")",
"{",
"$",
"json",
"[",
"'registration_ids'",
"]",
"=",
"$",
"this",
"->",
"registrationIds",... | To JSON
Utility method to put the JSON into the
GCM proper format for sending the message.
@return string | [
"To",
"JSON",
"Utility",
"method",
"to",
"put",
"the",
"JSON",
"into",
"the",
"GCM",
"proper",
"format",
"for",
"sending",
"the",
"message",
"."
] | f2b20d6b4232eaccb674571ef90223bf402f086b | https://github.com/laravel-notification-channels/gcm/blob/f2b20d6b4232eaccb674571ef90223bf402f086b/src/Packet.php#L35-L72 |
40,942 | laravel-notification-channels/gcm | src/GcmChannel.php | GcmChannel.send | public function send($notifiable, Notification $notification)
{
$tokens = (array) $notifiable->routeNotificationFor('gcm', $notification);
if (empty($tokens)) {
return;
}
$message = $notification->toGcm($notifiable);
if (! $message) {
return;
}
$packet = $this->getPacket($tokens, $message);
try {
$response = $this->client->send($packet);
} catch (Exception $exception) {
throw SendingFailed::create($exception);
}
if (! $response->getFailureCount() == 0) {
$this->handleFailedNotifications($notifiable, $notification, $response);
}
} | php | public function send($notifiable, Notification $notification)
{
$tokens = (array) $notifiable->routeNotificationFor('gcm', $notification);
if (empty($tokens)) {
return;
}
$message = $notification->toGcm($notifiable);
if (! $message) {
return;
}
$packet = $this->getPacket($tokens, $message);
try {
$response = $this->client->send($packet);
} catch (Exception $exception) {
throw SendingFailed::create($exception);
}
if (! $response->getFailureCount() == 0) {
$this->handleFailedNotifications($notifiable, $notification, $response);
}
} | [
"public",
"function",
"send",
"(",
"$",
"notifiable",
",",
"Notification",
"$",
"notification",
")",
"{",
"$",
"tokens",
"=",
"(",
"array",
")",
"$",
"notifiable",
"->",
"routeNotificationFor",
"(",
"'gcm'",
",",
"$",
"notification",
")",
";",
"if",
"(",
... | Send the notification to Google Cloud Messaging.
@param mixed $notifiable
@param Notification $notification
@return void
@throws Exceptions\SendingFailed | [
"Send",
"the",
"notification",
"to",
"Google",
"Cloud",
"Messaging",
"."
] | f2b20d6b4232eaccb674571ef90223bf402f086b | https://github.com/laravel-notification-channels/gcm/blob/f2b20d6b4232eaccb674571ef90223bf402f086b/src/GcmChannel.php#L48-L71 |
40,943 | laravel-notification-channels/gcm | src/GcmChannel.php | GcmChannel.handleFailedNotifications | protected function handleFailedNotifications($notifiable, Notification $notification, $response)
{
$results = $response->getResults();
foreach ($results as $token => $result) {
if (! isset($result['error'])) {
continue;
}
$this->events->dispatch(
new NotificationFailed($notifiable, $notification, get_class($this), [
'token' => $token,
'error' => $result['error'],
])
);
}
} | php | protected function handleFailedNotifications($notifiable, Notification $notification, $response)
{
$results = $response->getResults();
foreach ($results as $token => $result) {
if (! isset($result['error'])) {
continue;
}
$this->events->dispatch(
new NotificationFailed($notifiable, $notification, get_class($this), [
'token' => $token,
'error' => $result['error'],
])
);
}
} | [
"protected",
"function",
"handleFailedNotifications",
"(",
"$",
"notifiable",
",",
"Notification",
"$",
"notification",
",",
"$",
"response",
")",
"{",
"$",
"results",
"=",
"$",
"response",
"->",
"getResults",
"(",
")",
";",
"foreach",
"(",
"$",
"results",
"... | Handle a failed notification.
@param mixed $notifiable
@param \Illuminate\Notifications\Notification $notification
@param $response | [
"Handle",
"a",
"failed",
"notification",
"."
] | f2b20d6b4232eaccb674571ef90223bf402f086b | https://github.com/laravel-notification-channels/gcm/blob/f2b20d6b4232eaccb674571ef90223bf402f086b/src/GcmChannel.php#L104-L120 |
40,944 | gerbenjacobs/HabboAPI | src/Entities/Habbo.php | Habbo.parse | public function parse($data)
{
// These attributes are shared between Habbo and Friends
$this->setId($data['uniqueId']);
$this->setHabboName($data['name']);
$this->setMotto($data['motto']);
if (isset($data['figureString'])) {
$this->setFigureString($data['figureString']);
} elseif (isset($data['habboFigure'])) {
$this->setFigureString($data['habboFigure']);
}
// These could be missing..
if (isset($data['memberSince'])) {
$this->setMemberSince($data['memberSince']);
}
if (isset($data['profileVisible'])) {
$this->setProfileVisible($data['profileVisible']);
}
if (isset($data['selectedBadges'])) {
foreach ($data['selectedBadges'] as $badge) {
$selectedBadge = new Badge();
$selectedBadge->parse($badge);
$this->addSelectedBadge($selectedBadge);
}
}
} | php | public function parse($data)
{
// These attributes are shared between Habbo and Friends
$this->setId($data['uniqueId']);
$this->setHabboName($data['name']);
$this->setMotto($data['motto']);
if (isset($data['figureString'])) {
$this->setFigureString($data['figureString']);
} elseif (isset($data['habboFigure'])) {
$this->setFigureString($data['habboFigure']);
}
// These could be missing..
if (isset($data['memberSince'])) {
$this->setMemberSince($data['memberSince']);
}
if (isset($data['profileVisible'])) {
$this->setProfileVisible($data['profileVisible']);
}
if (isset($data['selectedBadges'])) {
foreach ($data['selectedBadges'] as $badge) {
$selectedBadge = new Badge();
$selectedBadge->parse($badge);
$this->addSelectedBadge($selectedBadge);
}
}
} | [
"public",
"function",
"parse",
"(",
"$",
"data",
")",
"{",
"// These attributes are shared between Habbo and Friends",
"$",
"this",
"->",
"setId",
"(",
"$",
"data",
"[",
"'uniqueId'",
"]",
")",
";",
"$",
"this",
"->",
"setHabboName",
"(",
"$",
"data",
"[",
"... | Parses habbo info array to \Entities\Habbo object
@param array $data | [
"Parses",
"habbo",
"info",
"array",
"to",
"\\",
"Entities",
"\\",
"Habbo",
"object"
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/Entities/Habbo.php#L31-L59 |
40,945 | gerbenjacobs/HabboAPI | src/Entities/Room.php | Room.parse | public function parse($room)
{
$this->setId($room['id']);
$this->setUniqueId($room['uniqueId']);
$this->setName($room['name']);
$this->setDescription($room['description']);
$this->setMaximumVisitors($room['maximumVisitors']);
$this->setTags($room['tags']);
$this->setShowOwnerName($room['showOwnerName']);
$this->setOwnerName($room['ownerName']);
$this->setOwnerUniqueId($room['ownerUniqueId']);
$this->setCategories($room['categories']);
$this->setThumbnailUrl($room['thumbnailUrl']);
$this->setImageUrl($room['imageUrl']);
$this->setRating($room['rating']);
if (isset($room['creationTime'])) {
$this->setCreationTime($room['creationTime']);
}
if (isset($room['habboGroupId'])) {
$this->setGroupId($room['habboGroupId']);
}
} | php | public function parse($room)
{
$this->setId($room['id']);
$this->setUniqueId($room['uniqueId']);
$this->setName($room['name']);
$this->setDescription($room['description']);
$this->setMaximumVisitors($room['maximumVisitors']);
$this->setTags($room['tags']);
$this->setShowOwnerName($room['showOwnerName']);
$this->setOwnerName($room['ownerName']);
$this->setOwnerUniqueId($room['ownerUniqueId']);
$this->setCategories($room['categories']);
$this->setThumbnailUrl($room['thumbnailUrl']);
$this->setImageUrl($room['imageUrl']);
$this->setRating($room['rating']);
if (isset($room['creationTime'])) {
$this->setCreationTime($room['creationTime']);
}
if (isset($room['habboGroupId'])) {
$this->setGroupId($room['habboGroupId']);
}
} | [
"public",
"function",
"parse",
"(",
"$",
"room",
")",
"{",
"$",
"this",
"->",
"setId",
"(",
"$",
"room",
"[",
"'id'",
"]",
")",
";",
"$",
"this",
"->",
"setUniqueId",
"(",
"$",
"room",
"[",
"'uniqueId'",
"]",
")",
";",
"$",
"this",
"->",
"setName... | Parses room info array to \Entities\Room object
@param array $room | [
"Parses",
"room",
"info",
"array",
"to",
"\\",
"Entities",
"\\",
"Room",
"object"
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/Entities/Room.php#L38-L61 |
40,946 | gerbenjacobs/HabboAPI | src/HabboParser.php | HabboParser.parseHabbo | public function parseHabbo($identifier, $useUniqueId = false)
{
if ($useUniqueId) {
$url = '/api/public/users/' . $identifier;
} else {
$url = '/api/public/users?name=' . $identifier;
}
list($data) = $this->_callUrl($this->api_base . $url, true);
$habbo = new Habbo();
$habbo->parse($data);
return $habbo;
} | php | public function parseHabbo($identifier, $useUniqueId = false)
{
if ($useUniqueId) {
$url = '/api/public/users/' . $identifier;
} else {
$url = '/api/public/users?name=' . $identifier;
}
list($data) = $this->_callUrl($this->api_base . $url, true);
$habbo = new Habbo();
$habbo->parse($data);
return $habbo;
} | [
"public",
"function",
"parseHabbo",
"(",
"$",
"identifier",
",",
"$",
"useUniqueId",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"useUniqueId",
")",
"{",
"$",
"url",
"=",
"'/api/public/users/'",
".",
"$",
"identifier",
";",
"}",
"else",
"{",
"$",
"url",
"=... | Parses the Habbo user endpoint
@param $identifier
@param bool $useUniqueId
@return Habbo
@throws Exception | [
"Parses",
"the",
"Habbo",
"user",
"endpoint"
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/HabboParser.php#L57-L70 |
40,947 | gerbenjacobs/HabboAPI | src/HabboParser.php | HabboParser.parseProfile | public function parseProfile($id)
{
// Collect JSON
list($data) = $this->_callUrl($this->api_base . '/api/public/users/' . $id . '/profile', true);
// Create Profile entity
$profile = new Profile();
// Habbo
$habbo = new Habbo();
$habbo->parse($data['user']);
$profile->setHabbo($habbo);
// Friends
foreach ($data['friends'] as $friend) {
$temp_friend = new Habbo();
$temp_friend->parse($friend);
$profile->addFriend($temp_friend);
}
// Groups
foreach ($data['groups'] as $group) {
$temp_group = new Group();
$temp_group->parse($group);
$profile->addGroup($temp_group);
}
// Rooms
foreach ($data['rooms'] as $room) {
$temp_room = new Room();
$temp_room->parse($room);
$profile->addRoom($temp_room);
}
// Badges
foreach ($data['badges'] as $badge) {
$temp_badge = new Badge();
$temp_badge->parse($badge);
$profile->addBadge($temp_badge);
}
// Return the Profile
return $profile;
} | php | public function parseProfile($id)
{
// Collect JSON
list($data) = $this->_callUrl($this->api_base . '/api/public/users/' . $id . '/profile', true);
// Create Profile entity
$profile = new Profile();
// Habbo
$habbo = new Habbo();
$habbo->parse($data['user']);
$profile->setHabbo($habbo);
// Friends
foreach ($data['friends'] as $friend) {
$temp_friend = new Habbo();
$temp_friend->parse($friend);
$profile->addFriend($temp_friend);
}
// Groups
foreach ($data['groups'] as $group) {
$temp_group = new Group();
$temp_group->parse($group);
$profile->addGroup($temp_group);
}
// Rooms
foreach ($data['rooms'] as $room) {
$temp_room = new Room();
$temp_room->parse($room);
$profile->addRoom($temp_room);
}
// Badges
foreach ($data['badges'] as $badge) {
$temp_badge = new Badge();
$temp_badge->parse($badge);
$profile->addBadge($temp_badge);
}
// Return the Profile
return $profile;
} | [
"public",
"function",
"parseProfile",
"(",
"$",
"id",
")",
"{",
"// Collect JSON",
"list",
"(",
"$",
"data",
")",
"=",
"$",
"this",
"->",
"_callUrl",
"(",
"$",
"this",
"->",
"api_base",
".",
"'/api/public/users/'",
".",
"$",
"id",
".",
"'/profile'",
",",... | Parses the Habbo Profile endpoints
Return a Profile object including a Habbo entity and 4 arrays with Group, Friend, Room, Badge entities
@param string $id
@return Profile
@throws Exception | [
"Parses",
"the",
"Habbo",
"Profile",
"endpoints"
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/HabboParser.php#L81-L124 |
40,948 | gerbenjacobs/HabboAPI | src/HabboParser.php | HabboParser.parseGroup | public function parseGroup($group_id)
{
list($data) = $this->_callUrl($this->api_base . '/api/public/groups/' . $group_id, true);
$group = new Group();
$group->parse($data);
try {
list($member_data) = $this->_callUrl($this->api_base . '/api/public/groups/' . $group_id . '/members', true);
} catch (Exception $e) {
// Can't collect member data
$member_data = false;
}
if ($member_data) {
/** @var Habbo[] $members */
$members = array();
foreach ($member_data as $member) {
$temp_habbo = new Habbo();
$temp_habbo->parse($member);
$members[] = $temp_habbo;
}
$group->setMembers($members);
}
return $group;
} | php | public function parseGroup($group_id)
{
list($data) = $this->_callUrl($this->api_base . '/api/public/groups/' . $group_id, true);
$group = new Group();
$group->parse($data);
try {
list($member_data) = $this->_callUrl($this->api_base . '/api/public/groups/' . $group_id . '/members', true);
} catch (Exception $e) {
// Can't collect member data
$member_data = false;
}
if ($member_data) {
/** @var Habbo[] $members */
$members = array();
foreach ($member_data as $member) {
$temp_habbo = new Habbo();
$temp_habbo->parse($member);
$members[] = $temp_habbo;
}
$group->setMembers($members);
}
return $group;
} | [
"public",
"function",
"parseGroup",
"(",
"$",
"group_id",
")",
"{",
"list",
"(",
"$",
"data",
")",
"=",
"$",
"this",
"->",
"_callUrl",
"(",
"$",
"this",
"->",
"api_base",
".",
"'/api/public/groups/'",
".",
"$",
"group_id",
",",
"true",
")",
";",
"$",
... | parseGroup will return a Group object based on a group ID.
It will also contain the members, as an array of Habbo objects.
@param $group_id
@return Group
@throws Exception | [
"parseGroup",
"will",
"return",
"a",
"Group",
"object",
"based",
"on",
"a",
"group",
"ID",
".",
"It",
"will",
"also",
"contain",
"the",
"members",
"as",
"an",
"array",
"of",
"Habbo",
"objects",
"."
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/HabboParser.php#L161-L187 |
40,949 | gerbenjacobs/HabboAPI | src/HabboParser.php | HabboParser.parseAchievements | public function parseAchievements($id)
{
$achievements = array();
list($data) = $this->_callUrl($this->api_base . '/api/public/achievements/' . $id, true);
if ($data) {
foreach ($data as $ach) {
$tmp_ach = new Achievement();
$tmp_ach->parse($ach);
$achievements[] = $tmp_ach;
unset($tmp_ach);
}
}
return $achievements;
} | php | public function parseAchievements($id)
{
$achievements = array();
list($data) = $this->_callUrl($this->api_base . '/api/public/achievements/' . $id, true);
if ($data) {
foreach ($data as $ach) {
$tmp_ach = new Achievement();
$tmp_ach->parse($ach);
$achievements[] = $tmp_ach;
unset($tmp_ach);
}
}
return $achievements;
} | [
"public",
"function",
"parseAchievements",
"(",
"$",
"id",
")",
"{",
"$",
"achievements",
"=",
"array",
"(",
")",
";",
"list",
"(",
"$",
"data",
")",
"=",
"$",
"this",
"->",
"_callUrl",
"(",
"$",
"this",
"->",
"api_base",
".",
"'/api/public/achievements/... | parseAchievements will return a list of achievements belonging to a Habbo
@param $id
@return Achievement[]
@throws Exception | [
"parseAchievements",
"will",
"return",
"a",
"list",
"of",
"achievements",
"belonging",
"to",
"a",
"Habbo"
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/HabboParser.php#L195-L211 |
40,950 | gerbenjacobs/HabboAPI | src/HabboParser.php | HabboParser.throwHabboAPIException | public static function throwHabboAPIException($data)
{
// Do we find 'maintenance' anywhere?
if (strstr($data, 'maintenance')) {
throw new MaintenanceException("Hotel API is down for maintenance");
}
// Check if data is JSON
if ($data[0] == "{") { // Quick 'hack' to see if this could be JSON
$json = json_decode($data, true);
if (isset($json['errors'])) {
if ($json['errors'][0]['msg'] == "user.invalid_name") {
throw new UserInvalidException("The name you supplied appears to be invalid");
}
$defaultMessage = $json['errors'][0]['msg'];
} else if (isset($json['error'])) {
if (preg_match('#not-found#', $json['error'])) {
throw new HabboNotFoundException("We can not find the Habbo you're looking for");
}
$defaultMessage = $json['error'];
} else {
$defaultMessage = $json;
}
} else {
$defaultMessage = "An unknown HTML page was returned";
}
throw new Exception("Unknown HabboAPI exception occurred: " . $defaultMessage);
} | php | public static function throwHabboAPIException($data)
{
// Do we find 'maintenance' anywhere?
if (strstr($data, 'maintenance')) {
throw new MaintenanceException("Hotel API is down for maintenance");
}
// Check if data is JSON
if ($data[0] == "{") { // Quick 'hack' to see if this could be JSON
$json = json_decode($data, true);
if (isset($json['errors'])) {
if ($json['errors'][0]['msg'] == "user.invalid_name") {
throw new UserInvalidException("The name you supplied appears to be invalid");
}
$defaultMessage = $json['errors'][0]['msg'];
} else if (isset($json['error'])) {
if (preg_match('#not-found#', $json['error'])) {
throw new HabboNotFoundException("We can not find the Habbo you're looking for");
}
$defaultMessage = $json['error'];
} else {
$defaultMessage = $json;
}
} else {
$defaultMessage = "An unknown HTML page was returned";
}
throw new Exception("Unknown HabboAPI exception occurred: " . $defaultMessage);
} | [
"public",
"static",
"function",
"throwHabboAPIException",
"(",
"$",
"data",
")",
"{",
"// Do we find 'maintenance' anywhere?",
"if",
"(",
"strstr",
"(",
"$",
"data",
",",
"'maintenance'",
")",
")",
"{",
"throw",
"new",
"MaintenanceException",
"(",
"\"Hotel API is do... | deciphers data returned from Habbo and tries to throw the correct exception
@param $data
@throws Exception
@throws HabboNotFoundException
@throws MaintenanceException
@throws UserInvalidException | [
"deciphers",
"data",
"returned",
"from",
"Habbo",
"and",
"tries",
"to",
"throw",
"the",
"correct",
"exception"
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/HabboParser.php#L254-L282 |
40,951 | gerbenjacobs/HabboAPI | src/Entities/Group.php | Group.parse | public function parse($group)
{
$this->setId($group['id']);
$this->setName($group['name']);
$this->setDescription($group['description']);
$this->setType($group['type']);
if (isset($group['primaryColour'])) {
$this->setPrimaryColour($group['primaryColour']);
}
if (isset($group['secondaryColour'])) {
$this->setSecondaryColour($group['secondaryColour']);
}
if (isset($group['badgeCode'])) {
$this->setBadgeCode($group['badgeCode']);
}
if (isset($group['roomId'])) {
$this->setRoomId($group['roomId']);
}
if (isset($group['isAdmin'])) {
$this->setIsAdmin($group['isAdmin']);
}
} | php | public function parse($group)
{
$this->setId($group['id']);
$this->setName($group['name']);
$this->setDescription($group['description']);
$this->setType($group['type']);
if (isset($group['primaryColour'])) {
$this->setPrimaryColour($group['primaryColour']);
}
if (isset($group['secondaryColour'])) {
$this->setSecondaryColour($group['secondaryColour']);
}
if (isset($group['badgeCode'])) {
$this->setBadgeCode($group['badgeCode']);
}
if (isset($group['roomId'])) {
$this->setRoomId($group['roomId']);
}
if (isset($group['isAdmin'])) {
$this->setIsAdmin($group['isAdmin']);
}
} | [
"public",
"function",
"parse",
"(",
"$",
"group",
")",
"{",
"$",
"this",
"->",
"setId",
"(",
"$",
"group",
"[",
"'id'",
"]",
")",
";",
"$",
"this",
"->",
"setName",
"(",
"$",
"group",
"[",
"'name'",
"]",
")",
";",
"$",
"this",
"->",
"setDescripti... | Parses group info array to \Entities\Group object
@param array $group | [
"Parses",
"group",
"info",
"array",
"to",
"\\",
"Entities",
"\\",
"Group",
"object"
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/Entities/Group.php#L21-L42 |
40,952 | gerbenjacobs/HabboAPI | src/Entities/Badge.php | Badge.parse | public function parse($badge)
{
if (isset($badge['badgeIndex'])) {
$this->setBadgeIndex($badge['badgeIndex']);
}
$this->setCode($badge['code']);
$this->setName($badge['name']);
$this->setDescription($badge['description']);
} | php | public function parse($badge)
{
if (isset($badge['badgeIndex'])) {
$this->setBadgeIndex($badge['badgeIndex']);
}
$this->setCode($badge['code']);
$this->setName($badge['name']);
$this->setDescription($badge['description']);
} | [
"public",
"function",
"parse",
"(",
"$",
"badge",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"badge",
"[",
"'badgeIndex'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"setBadgeIndex",
"(",
"$",
"badge",
"[",
"'badgeIndex'",
"]",
")",
";",
"}",
"$",
"this",... | Parses badge info array to Badge object
@param array $badge | [
"Parses",
"badge",
"info",
"array",
"to",
"Badge",
"object"
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/Entities/Badge.php#L23-L31 |
40,953 | gerbenjacobs/HabboAPI | src/Entities/Profile.php | Profile.getCounts | public function getCounts()
{
return array(
'habbo' => count($this->habbo),
'badges' => count($this->badges),
'friends' => count($this->friends),
'groups' => count($this->groups),
'rooms' => count($this->rooms),
);
} | php | public function getCounts()
{
return array(
'habbo' => count($this->habbo),
'badges' => count($this->badges),
'friends' => count($this->friends),
'groups' => count($this->groups),
'rooms' => count($this->rooms),
);
} | [
"public",
"function",
"getCounts",
"(",
")",
"{",
"return",
"array",
"(",
"'habbo'",
"=>",
"count",
"(",
"$",
"this",
"->",
"habbo",
")",
",",
"'badges'",
"=>",
"count",
"(",
"$",
"this",
"->",
"badges",
")",
",",
"'friends'",
"=>",
"count",
"(",
"$"... | getCounts is a small helper function to give you
an array of each entity in the profile and its count
@return array | [
"getCounts",
"is",
"a",
"small",
"helper",
"function",
"to",
"give",
"you",
"an",
"array",
"of",
"each",
"entity",
"in",
"the",
"profile",
"and",
"its",
"count"
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/Entities/Profile.php#L133-L142 |
40,954 | gerbenjacobs/HabboAPI | src/Entities/Achievement.php | Achievement.parse | public function parse($achievement)
{
// add default fields
$this->id = $achievement['achievement']['id'];
$this->name = $achievement['achievement']['name'];
$this->category = $achievement['achievement']['category'];
// add requirements if available
if (isset($achievement['requirements'])) {
$this->requirements = $achievement['requirements'];
}
// add user state if available
if (isset($achievement['level'])) {
$this->level = $achievement['level'];
}
if (isset($achievement['score'])) {
$this->score = $achievement['score'];
}
} | php | public function parse($achievement)
{
// add default fields
$this->id = $achievement['achievement']['id'];
$this->name = $achievement['achievement']['name'];
$this->category = $achievement['achievement']['category'];
// add requirements if available
if (isset($achievement['requirements'])) {
$this->requirements = $achievement['requirements'];
}
// add user state if available
if (isset($achievement['level'])) {
$this->level = $achievement['level'];
}
if (isset($achievement['score'])) {
$this->score = $achievement['score'];
}
} | [
"public",
"function",
"parse",
"(",
"$",
"achievement",
")",
"{",
"// add default fields",
"$",
"this",
"->",
"id",
"=",
"$",
"achievement",
"[",
"'achievement'",
"]",
"[",
"'id'",
"]",
";",
"$",
"this",
"->",
"name",
"=",
"$",
"achievement",
"[",
"'achi... | Parses achievement info array to Achievement object
@param $achievement | [
"Parses",
"achievement",
"info",
"array",
"to",
"Achievement",
"object"
] | f7d81d50194ff0618dfeb3b72db9a8b90f6613b3 | https://github.com/gerbenjacobs/HabboAPI/blob/f7d81d50194ff0618dfeb3b72db9a8b90f6613b3/src/Entities/Achievement.php#L22-L41 |
40,955 | delight-im/PHP-Str | src/Str.php | Str.fromArray | public static function fromArray($rawArray, $charset = null) {
$output = array();
foreach ($rawArray as $rawEntry) {
$output[] = new static($rawEntry, $charset);
}
return $output;
} | php | public static function fromArray($rawArray, $charset = null) {
$output = array();
foreach ($rawArray as $rawEntry) {
$output[] = new static($rawEntry, $charset);
}
return $output;
} | [
"public",
"static",
"function",
"fromArray",
"(",
"$",
"rawArray",
",",
"$",
"charset",
"=",
"null",
")",
"{",
"$",
"output",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"rawArray",
"as",
"$",
"rawEntry",
")",
"{",
"$",
"output",
"[",
"]",
"=... | Variant of the static "constructor" that operates on arrays
@param string[] $rawArray the array of strings to create instances from
@param string|null $charset the charset to use (one of the values listed by `mb_list_encodings`) (optional)
@return static[] the new instances of this class | [
"Variant",
"of",
"the",
"static",
"constructor",
"that",
"operates",
"on",
"arrays"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L51-L59 |
40,956 | delight-im/PHP-Str | src/Str.php | Str.first | public function first($length = null) {
if ($length === null) {
$length = 1;
}
$rawString = mb_substr($this->rawString, 0, $length, $this->charset);
return new static($rawString, $this->charset);
} | php | public function first($length = null) {
if ($length === null) {
$length = 1;
}
$rawString = mb_substr($this->rawString, 0, $length, $this->charset);
return new static($rawString, $this->charset);
} | [
"public",
"function",
"first",
"(",
"$",
"length",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"length",
"===",
"null",
")",
"{",
"$",
"length",
"=",
"1",
";",
"}",
"$",
"rawString",
"=",
"mb_substr",
"(",
"$",
"this",
"->",
"rawString",
",",
"0",
","... | Returns the first character or the specified number of characters from the start of this string
@param int|null $length the number of characters to return from the start (optional)
@return static a new instance of this class | [
"Returns",
"the",
"first",
"character",
"or",
"the",
"specified",
"number",
"of",
"characters",
"from",
"the",
"start",
"of",
"this",
"string"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L187-L195 |
40,957 | delight-im/PHP-Str | src/Str.php | Str.last | public function last($length = null) {
if ($length === null) {
$length = 1;
}
$offset = $this->length() - $length;
$rawString = mb_substr($this->rawString, $offset, null, $this->charset);
return new static($rawString, $this->charset);
} | php | public function last($length = null) {
if ($length === null) {
$length = 1;
}
$offset = $this->length() - $length;
$rawString = mb_substr($this->rawString, $offset, null, $this->charset);
return new static($rawString, $this->charset);
} | [
"public",
"function",
"last",
"(",
"$",
"length",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"length",
"===",
"null",
")",
"{",
"$",
"length",
"=",
"1",
";",
"}",
"$",
"offset",
"=",
"$",
"this",
"->",
"length",
"(",
")",
"-",
"$",
"length",
";",
... | Returns the last character or the specified number of characters from the end of this string
@param int|null $length the number of characters to return from the end (optional)
@return static a new instance of this class | [
"Returns",
"the",
"last",
"character",
"or",
"the",
"specified",
"number",
"of",
"characters",
"from",
"the",
"end",
"of",
"this",
"string"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L214-L224 |
40,958 | delight-im/PHP-Str | src/Str.php | Str.toLowerCase | public function toLowerCase() {
$rawString = mb_strtolower($this->rawString, $this->charset);
return new static($rawString, $this->charset);
} | php | public function toLowerCase() {
$rawString = mb_strtolower($this->rawString, $this->charset);
return new static($rawString, $this->charset);
} | [
"public",
"function",
"toLowerCase",
"(",
")",
"{",
"$",
"rawString",
"=",
"mb_strtolower",
"(",
"$",
"this",
"->",
"rawString",
",",
"$",
"this",
"->",
"charset",
")",
";",
"return",
"new",
"static",
"(",
"$",
"rawString",
",",
"$",
"this",
"->",
"cha... | Converts this string to lowercase
@return static a new instance of this class | [
"Converts",
"this",
"string",
"to",
"lowercase"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L231-L235 |
40,959 | delight-im/PHP-Str | src/Str.php | Str.toUpperCase | public function toUpperCase() {
$rawString = mb_strtoupper($this->rawString, $this->charset);
return new static($rawString, $this->charset);
} | php | public function toUpperCase() {
$rawString = mb_strtoupper($this->rawString, $this->charset);
return new static($rawString, $this->charset);
} | [
"public",
"function",
"toUpperCase",
"(",
")",
"{",
"$",
"rawString",
"=",
"mb_strtoupper",
"(",
"$",
"this",
"->",
"rawString",
",",
"$",
"this",
"->",
"charset",
")",
";",
"return",
"new",
"static",
"(",
"$",
"rawString",
",",
"$",
"this",
"->",
"cha... | Converts this string to uppercase
@return static a new instance of this class | [
"Converts",
"this",
"string",
"to",
"uppercase"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L251-L255 |
40,960 | delight-im/PHP-Str | src/Str.php | Str.count | public function count($substring = null) {
if ($substring === null) {
return mb_strlen($this->rawString, $this->charset);
}
else {
return mb_substr_count($this->rawString, $substring, $this->charset);
}
} | php | public function count($substring = null) {
if ($substring === null) {
return mb_strlen($this->rawString, $this->charset);
}
else {
return mb_substr_count($this->rawString, $substring, $this->charset);
}
} | [
"public",
"function",
"count",
"(",
"$",
"substring",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"substring",
"===",
"null",
")",
"{",
"return",
"mb_strlen",
"(",
"$",
"this",
"->",
"rawString",
",",
"$",
"this",
"->",
"charset",
")",
";",
"}",
"else",
... | Counts the occurrences of the specified substring in this string
@param string $substring the substring whose occurrences to count
@return int the number of occurrences | [
"Counts",
"the",
"occurrences",
"of",
"the",
"specified",
"substring",
"in",
"this",
"string"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L305-L312 |
40,961 | delight-im/PHP-Str | src/Str.php | Str.cutStart | public function cutStart($length) {
$rawString = mb_substr($this->rawString, $length, null, $this->charset);
return new static($rawString, $this->charset);
} | php | public function cutStart($length) {
$rawString = mb_substr($this->rawString, $length, null, $this->charset);
return new static($rawString, $this->charset);
} | [
"public",
"function",
"cutStart",
"(",
"$",
"length",
")",
"{",
"$",
"rawString",
"=",
"mb_substr",
"(",
"$",
"this",
"->",
"rawString",
",",
"$",
"length",
",",
"null",
",",
"$",
"this",
"->",
"charset",
")",
";",
"return",
"new",
"static",
"(",
"$"... | Removes the specified number of characters from the start of this string
@param int $length the number of characters to remove
@return static a new instance of this class | [
"Removes",
"the",
"specified",
"number",
"of",
"characters",
"from",
"the",
"start",
"of",
"this",
"string"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L329-L333 |
40,962 | delight-im/PHP-Str | src/Str.php | Str.cutEnd | public function cutEnd($length) {
$rawString = mb_substr($this->rawString, 0, $this->length() - $length, $this->charset);
return new static($rawString, $this->charset);
} | php | public function cutEnd($length) {
$rawString = mb_substr($this->rawString, 0, $this->length() - $length, $this->charset);
return new static($rawString, $this->charset);
} | [
"public",
"function",
"cutEnd",
"(",
"$",
"length",
")",
"{",
"$",
"rawString",
"=",
"mb_substr",
"(",
"$",
"this",
"->",
"rawString",
",",
"0",
",",
"$",
"this",
"->",
"length",
"(",
")",
"-",
"$",
"length",
",",
"$",
"this",
"->",
"charset",
")",... | Removes the specified number of characters from the end of this string
@param int $length the number of characters to remove
@return static a new instance of this class | [
"Removes",
"the",
"specified",
"number",
"of",
"characters",
"from",
"the",
"end",
"of",
"this",
"string"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L341-L345 |
40,963 | delight-im/PHP-Str | src/Str.php | Str.replacePrefix | public function replacePrefix($searchFor, $replaceWith = null) {
if ($this->startsWith($searchFor)) {
return $this->replaceFirst($searchFor, $replaceWith);
}
else {
return $this;
}
} | php | public function replacePrefix($searchFor, $replaceWith = null) {
if ($this->startsWith($searchFor)) {
return $this->replaceFirst($searchFor, $replaceWith);
}
else {
return $this;
}
} | [
"public",
"function",
"replacePrefix",
"(",
"$",
"searchFor",
",",
"$",
"replaceWith",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"startsWith",
"(",
"$",
"searchFor",
")",
")",
"{",
"return",
"$",
"this",
"->",
"replaceFirst",
"(",
"$",
"sear... | Replaces the specified part in this string only if it starts with that part
@param string $searchFor the string to search for
@param string $replaceWith the string to use as the replacement (optional)
@return static a new instance of this class | [
"Replaces",
"the",
"specified",
"part",
"in",
"this",
"string",
"only",
"if",
"it",
"starts",
"with",
"that",
"part"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L402-L409 |
40,964 | delight-im/PHP-Str | src/Str.php | Str.replaceSuffix | public function replaceSuffix($searchFor, $replaceWith = null) {
if ($this->endsWith($searchFor)) {
return $this->replaceLast($searchFor, $replaceWith);
}
else {
return $this;
}
} | php | public function replaceSuffix($searchFor, $replaceWith = null) {
if ($this->endsWith($searchFor)) {
return $this->replaceLast($searchFor, $replaceWith);
}
else {
return $this;
}
} | [
"public",
"function",
"replaceSuffix",
"(",
"$",
"searchFor",
",",
"$",
"replaceWith",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"endsWith",
"(",
"$",
"searchFor",
")",
")",
"{",
"return",
"$",
"this",
"->",
"replaceLast",
"(",
"$",
"searchF... | Replaces the specified part in this string only if it ends with that part
@param string $searchFor the string to search for
@param string $replaceWith the string to use as the replacement (optional)
@return static a new instance of this class | [
"Replaces",
"the",
"specified",
"part",
"in",
"this",
"string",
"only",
"if",
"it",
"ends",
"with",
"that",
"part"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L442-L449 |
40,965 | delight-im/PHP-Str | src/Str.php | Str.split | public function split($delimiter, $limit = null) {
if ($limit === null) {
$limit = PHP_INT_MAX;
}
return self::fromArray(explode($delimiter, $this->rawString, $limit));
} | php | public function split($delimiter, $limit = null) {
if ($limit === null) {
$limit = PHP_INT_MAX;
}
return self::fromArray(explode($delimiter, $this->rawString, $limit));
} | [
"public",
"function",
"split",
"(",
"$",
"delimiter",
",",
"$",
"limit",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"limit",
"===",
"null",
")",
"{",
"$",
"limit",
"=",
"PHP_INT_MAX",
";",
"}",
"return",
"self",
"::",
"fromArray",
"(",
"explode",
"(",
... | Splits this string into an array of substrings at the specified delimiter
@param string $delimiter the delimiter to split the string at
@param int|null $limit the maximum number of substrings to return (optional)
@return static[] the new instances of this class | [
"Splits",
"this",
"string",
"into",
"an",
"array",
"of",
"substrings",
"at",
"the",
"specified",
"delimiter"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L458-L464 |
40,966 | delight-im/PHP-Str | src/Str.php | Str.splitByRegex | public function splitByRegex($delimiterPattern, $limit = null, $flags = null) {
if ($limit === null) {
$limit = -1;
}
if ($flags === null) {
$flags = 0;
}
return self::fromArray(preg_split($delimiterPattern, $this->rawString, $limit, $flags));
} | php | public function splitByRegex($delimiterPattern, $limit = null, $flags = null) {
if ($limit === null) {
$limit = -1;
}
if ($flags === null) {
$flags = 0;
}
return self::fromArray(preg_split($delimiterPattern, $this->rawString, $limit, $flags));
} | [
"public",
"function",
"splitByRegex",
"(",
"$",
"delimiterPattern",
",",
"$",
"limit",
"=",
"null",
",",
"$",
"flags",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"limit",
"===",
"null",
")",
"{",
"$",
"limit",
"=",
"-",
"1",
";",
"}",
"if",
"(",
"$",... | Splits this string into an array of substrings at the specified delimiter pattern
@param string $delimiterPattern the regular expression (PCRE) to split the string at
@param int|null $limit the maximum number of substrings to return (optional)
@param int|null $flags any combination (bit-wise ORed) of PHP's `PREG_SPLIT_*` flags
@return static[] the new instances of this class | [
"Splits",
"this",
"string",
"into",
"an",
"array",
"of",
"substrings",
"at",
"the",
"specified",
"delimiter",
"pattern"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L474-L484 |
40,967 | delight-im/PHP-Str | src/Str.php | Str.words | public function words($limit = null) {
// if a limit has been specified
if ($limit !== null) {
// get one entry more than requested
$limit += 1;
}
// split the string into words
$words = $this->splitByRegex('/[^\\w\']+/u', $limit, PREG_SPLIT_NO_EMPTY);
// if a limit has been specified
if ($limit !== null) {
// discard the last entry (which contains the remainder of the string)
array_pop($words);
}
// return the words
return $words;
} | php | public function words($limit = null) {
// if a limit has been specified
if ($limit !== null) {
// get one entry more than requested
$limit += 1;
}
// split the string into words
$words = $this->splitByRegex('/[^\\w\']+/u', $limit, PREG_SPLIT_NO_EMPTY);
// if a limit has been specified
if ($limit !== null) {
// discard the last entry (which contains the remainder of the string)
array_pop($words);
}
// return the words
return $words;
} | [
"public",
"function",
"words",
"(",
"$",
"limit",
"=",
"null",
")",
"{",
"// if a limit has been specified",
"if",
"(",
"$",
"limit",
"!==",
"null",
")",
"{",
"// get one entry more than requested",
"$",
"limit",
"+=",
"1",
";",
"}",
"// split the string into word... | Splits this string into its single words
@param int|null the maximum number of words to return from the start (optional)
@return static[] the new instances of this class | [
"Splits",
"this",
"string",
"into",
"its",
"single",
"words"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L492-L510 |
40,968 | delight-im/PHP-Str | src/Str.php | Str.between | public function between($start, $end) {
$beforeStart = mb_strpos($this->rawString, $start, 0, $this->charset);
$rawString = '';
if ($beforeStart !== false) {
$afterStart = $beforeStart + mb_strlen($start, $this->charset);
$beforeEnd = mb_strrpos($this->rawString, $end, $afterStart, $this->charset);
if ($beforeEnd !== false) {
$rawString = mb_substr($this->rawString, $afterStart, $beforeEnd - $afterStart, $this->charset);
}
}
return new static($rawString, $this->charset);
} | php | public function between($start, $end) {
$beforeStart = mb_strpos($this->rawString, $start, 0, $this->charset);
$rawString = '';
if ($beforeStart !== false) {
$afterStart = $beforeStart + mb_strlen($start, $this->charset);
$beforeEnd = mb_strrpos($this->rawString, $end, $afterStart, $this->charset);
if ($beforeEnd !== false) {
$rawString = mb_substr($this->rawString, $afterStart, $beforeEnd - $afterStart, $this->charset);
}
}
return new static($rawString, $this->charset);
} | [
"public",
"function",
"between",
"(",
"$",
"start",
",",
"$",
"end",
")",
"{",
"$",
"beforeStart",
"=",
"mb_strpos",
"(",
"$",
"this",
"->",
"rawString",
",",
"$",
"start",
",",
"0",
",",
"$",
"this",
"->",
"charset",
")",
";",
"$",
"rawString",
"=... | Returns the part of this string between the two specified substrings
If there are multiple occurrences, the part with the maximum length will be returned
@param string $start the substring whose first occurrence should delimit the start
@param string $end the substring whose last occurrence should delimit the end
@return static a new instance of this class | [
"Returns",
"the",
"part",
"of",
"this",
"string",
"between",
"the",
"two",
"specified",
"substrings"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L541-L556 |
40,969 | delight-im/PHP-Str | src/Str.php | Str.escapeForHtml | public function escapeForHtml() {
$rawString = htmlspecialchars($this->rawString, ENT_QUOTES, $this->charset);
return new static($rawString, $this->charset);
} | php | public function escapeForHtml() {
$rawString = htmlspecialchars($this->rawString, ENT_QUOTES, $this->charset);
return new static($rawString, $this->charset);
} | [
"public",
"function",
"escapeForHtml",
"(",
")",
"{",
"$",
"rawString",
"=",
"htmlspecialchars",
"(",
"$",
"this",
"->",
"rawString",
",",
"ENT_QUOTES",
",",
"$",
"this",
"->",
"charset",
")",
";",
"return",
"new",
"static",
"(",
"$",
"rawString",
",",
"... | Escapes this string for safe use in HTML
@return static a new instance of this class | [
"Escapes",
"this",
"string",
"for",
"safe",
"use",
"in",
"HTML"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L657-L661 |
40,970 | delight-im/PHP-Str | src/Str.php | Str.reverse | public function reverse() {
if (preg_match_all('/./us', $this->rawString, $matches)) {
$rawString = join('', array_reverse($matches[0]));
return new static($rawString, $this->charset);
}
else {
return $this;
}
} | php | public function reverse() {
if (preg_match_all('/./us', $this->rawString, $matches)) {
$rawString = join('', array_reverse($matches[0]));
return new static($rawString, $this->charset);
}
else {
return $this;
}
} | [
"public",
"function",
"reverse",
"(",
")",
"{",
"if",
"(",
"preg_match_all",
"(",
"'/./us'",
",",
"$",
"this",
"->",
"rawString",
",",
"$",
"matches",
")",
")",
"{",
"$",
"rawString",
"=",
"join",
"(",
"''",
",",
"array_reverse",
"(",
"$",
"matches",
... | Reverses this string
@return static a new instance of this class | [
"Reverses",
"this",
"string"
] | 606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9 | https://github.com/delight-im/PHP-Str/blob/606e36c9c5297eb01ad04b8a57e3dcbdfb0d98a9/src/Str.php#L684-L693 |
40,971 | thephpleague/tactician-doctrine | src/ORM/TransactionMiddleware.php | TransactionMiddleware.rollbackTransaction | protected function rollbackTransaction()
{
$this->entityManager->rollback();
$connection = $this->entityManager->getConnection();
if (!$connection->isTransactionActive() || $connection->isRollbackOnly()) {
$this->entityManager->close();
}
} | php | protected function rollbackTransaction()
{
$this->entityManager->rollback();
$connection = $this->entityManager->getConnection();
if (!$connection->isTransactionActive() || $connection->isRollbackOnly()) {
$this->entityManager->close();
}
} | [
"protected",
"function",
"rollbackTransaction",
"(",
")",
"{",
"$",
"this",
"->",
"entityManager",
"->",
"rollback",
"(",
")",
";",
"$",
"connection",
"=",
"$",
"this",
"->",
"entityManager",
"->",
"getConnection",
"(",
")",
";",
"if",
"(",
"!",
"$",
"co... | Rollback the current transaction and close the entity manager when possible. | [
"Rollback",
"the",
"current",
"transaction",
"and",
"close",
"the",
"entity",
"manager",
"when",
"possible",
"."
] | c318a16c0f0461bc3a277753788af5b930d6359e | https://github.com/thephpleague/tactician-doctrine/blob/c318a16c0f0461bc3a277753788af5b930d6359e/src/ORM/TransactionMiddleware.php#L61-L69 |
40,972 | delight-im/PHP-FileUpload | src/DataUriUpload.php | DataUriUpload.getAllowedMimeTypesAsHumanString | public function getAllowedMimeTypesAsHumanString($lastSeparator = null) {
$separator = ', ';
$str = \implode($separator, $this->getAllowedMimeTypesAsArray());
if ($lastSeparator !== null) {
$lastSeparatorPosition = \strrpos($str, $separator);
if ($lastSeparatorPosition !== false) {
$str = \substr_replace($str, $lastSeparator, $lastSeparatorPosition, \strlen($separator));
}
}
return $str;
} | php | public function getAllowedMimeTypesAsHumanString($lastSeparator = null) {
$separator = ', ';
$str = \implode($separator, $this->getAllowedMimeTypesAsArray());
if ($lastSeparator !== null) {
$lastSeparatorPosition = \strrpos($str, $separator);
if ($lastSeparatorPosition !== false) {
$str = \substr_replace($str, $lastSeparator, $lastSeparatorPosition, \strlen($separator));
}
}
return $str;
} | [
"public",
"function",
"getAllowedMimeTypesAsHumanString",
"(",
"$",
"lastSeparator",
"=",
"null",
")",
"{",
"$",
"separator",
"=",
"', '",
";",
"$",
"str",
"=",
"\\",
"implode",
"(",
"$",
"separator",
",",
"$",
"this",
"->",
"getAllowedMimeTypesAsArray",
"(",
... | Returns the list of permitted MIME types as a human-readable string
@param string|null $lastSeparator (optional) the last separator as an alternative to the comma, e.g. ` or `
@return string | [
"Returns",
"the",
"list",
"of",
"permitted",
"MIME",
"types",
"as",
"a",
"human",
"-",
"readable",
"string"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/DataUriUpload.php#L130-L144 |
40,973 | delight-im/PHP-FileUpload | src/Directory.php | Directory.deleteRecursively | public function deleteRecursively() {
if ($this->exists()) {
$entries = @\scandir($this->path);
foreach ($entries as $entry) {
if ($entry !== '.' && $entry !== '..') {
$entryPath = $this->path . '/' . $entry;
if (@\is_dir($entryPath)) {
$this->deleteRecursively($entryPath);
}
else {
@\unlink($entryPath);
}
}
}
@\rmdir($this->path);
}
} | php | public function deleteRecursively() {
if ($this->exists()) {
$entries = @\scandir($this->path);
foreach ($entries as $entry) {
if ($entry !== '.' && $entry !== '..') {
$entryPath = $this->path . '/' . $entry;
if (@\is_dir($entryPath)) {
$this->deleteRecursively($entryPath);
}
else {
@\unlink($entryPath);
}
}
}
@\rmdir($this->path);
}
} | [
"public",
"function",
"deleteRecursively",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"exists",
"(",
")",
")",
"{",
"$",
"entries",
"=",
"@",
"\\",
"scandir",
"(",
"$",
"this",
"->",
"path",
")",
";",
"foreach",
"(",
"$",
"entries",
"as",
"$",
... | Attempts to delete the directory including any contents recursively | [
"Attempts",
"to",
"delete",
"the",
"directory",
"including",
"any",
"contents",
"recursively"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/Directory.php#L87-L106 |
40,974 | delight-im/PHP-FileUpload | src/Directory.php | Directory.createInternal | private function createInternal($recursive, $mode = null) {
if ($mode === null) {
$mode = 0755;
}
return @mkdir($this->path, $mode, $recursive);
} | php | private function createInternal($recursive, $mode = null) {
if ($mode === null) {
$mode = 0755;
}
return @mkdir($this->path, $mode, $recursive);
} | [
"private",
"function",
"createInternal",
"(",
"$",
"recursive",
",",
"$",
"mode",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"mode",
"===",
"null",
")",
"{",
"$",
"mode",
"=",
"0755",
";",
"}",
"return",
"@",
"mkdir",
"(",
"$",
"this",
"->",
"path",
... | Attempts to create the directory
@param bool $recursive whether missing parent directories (if any) should be created recursively
@param int|null $mode (optional) the file mode (permissions) as used with the `chmod` method
@return bool whether the directory has successfully been created | [
"Attempts",
"to",
"create",
"the",
"directory"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/Directory.php#L119-L125 |
40,975 | delight-im/PHP-FileUpload | src/File.php | File.getFilenameWithExtension | public function getFilenameWithExtension() {
if ($this->extension === null) {
return $this->filename;
}
else {
return $this->filename . '.' . $this->extension;
}
} | php | public function getFilenameWithExtension() {
if ($this->extension === null) {
return $this->filename;
}
else {
return $this->filename . '.' . $this->extension;
}
} | [
"public",
"function",
"getFilenameWithExtension",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"extension",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"filename",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"filename",
".",
"'.'",
".... | Returns the name of the file including its extension
@return string | [
"Returns",
"the",
"name",
"of",
"the",
"file",
"including",
"its",
"extension"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/File.php#L70-L77 |
40,976 | delight-im/PHP-FileUpload | src/FileUpload.php | FileUpload.from | public function from($inputName) {
$this->sourceInputName = (string) $inputName;
// remove leading and trailing whitespace
$this->sourceInputName = \trim($this->sourceInputName);
return $this;
} | php | public function from($inputName) {
$this->sourceInputName = (string) $inputName;
// remove leading and trailing whitespace
$this->sourceInputName = \trim($this->sourceInputName);
return $this;
} | [
"public",
"function",
"from",
"(",
"$",
"inputName",
")",
"{",
"$",
"this",
"->",
"sourceInputName",
"=",
"(",
"string",
")",
"$",
"inputName",
";",
"// remove leading and trailing whitespace",
"$",
"this",
"->",
"sourceInputName",
"=",
"\\",
"trim",
"(",
"$",... | Sets the name of the file input whose selected file is to be received and stored
@param string $inputName usually the `name` attribute of the `<input type="file">` HTML element
@return static this instance for chaining | [
"Sets",
"the",
"name",
"of",
"the",
"file",
"input",
"whose",
"selected",
"file",
"is",
"to",
"be",
"received",
"and",
"stored"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/FileUpload.php#L138-L145 |
40,977 | delight-im/PHP-FileUpload | src/AbstractUpload.php | AbstractUpload.withMaximumSizeInBytes | public function withMaximumSizeInBytes($size) {
$size = (int) $size;
if ($size > $this->maxTotalSize) {
throw new TotalSizeExceededError();
}
$this->maxIndividualSize = $size;
return $this;
} | php | public function withMaximumSizeInBytes($size) {
$size = (int) $size;
if ($size > $this->maxTotalSize) {
throw new TotalSizeExceededError();
}
$this->maxIndividualSize = $size;
return $this;
} | [
"public",
"function",
"withMaximumSizeInBytes",
"(",
"$",
"size",
")",
"{",
"$",
"size",
"=",
"(",
"int",
")",
"$",
"size",
";",
"if",
"(",
"$",
"size",
">",
"$",
"this",
"->",
"maxTotalSize",
")",
"{",
"throw",
"new",
"TotalSizeExceededError",
"(",
")... | Restricts the maximum size of individual files to be uploaded to the specified size
@param int $size the size in bytes
@return static this instance for chaining
@throws Error (do *not* catch) | [
"Restricts",
"the",
"maximum",
"size",
"of",
"individual",
"files",
"to",
"be",
"uploaded",
"to",
"the",
"specified",
"size"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/AbstractUpload.php#L55-L65 |
40,978 | delight-im/PHP-FileUpload | src/AbstractUpload.php | AbstractUpload.withTargetFilename | public function withTargetFilename($targetFilename) {
$targetFilename = (string) $targetFilename;
$targetFilename = \trim($targetFilename);
$this->targetFilename = $targetFilename;
return $this;
} | php | public function withTargetFilename($targetFilename) {
$targetFilename = (string) $targetFilename;
$targetFilename = \trim($targetFilename);
$this->targetFilename = $targetFilename;
return $this;
} | [
"public",
"function",
"withTargetFilename",
"(",
"$",
"targetFilename",
")",
"{",
"$",
"targetFilename",
"=",
"(",
"string",
")",
"$",
"targetFilename",
";",
"$",
"targetFilename",
"=",
"\\",
"trim",
"(",
"$",
"targetFilename",
")",
";",
"$",
"this",
"->",
... | Sets the target filename which uploaded files are to be stored with
If you do not specify a filename explicitly, a new random filename will be generated automatically
The filename should *not* include any file extension because the extension will be appended automatically
@param string $targetFilename
@return static this instance for chaining | [
"Sets",
"the",
"target",
"filename",
"which",
"uploaded",
"files",
"are",
"to",
"be",
"stored",
"with"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/AbstractUpload.php#L173-L180 |
40,979 | delight-im/PHP-FileUpload | src/AbstractUpload.php | AbstractUpload.describeTargetFile | protected function describeTargetFile($extension) {
if ($this->targetDirectory === null) {
throw new TargetDirectoryNotSpecifiedError();
}
$targetFilename = isset($this->targetFilename) ? $this->targetFilename : self::createRandomString();
if (!File::mayNameBeValid($targetFilename)) {
throw new InvalidFilenameException();
}
if (!$this->targetDirectory->exists() && !$this->targetDirectory->createRecursively(0755)) {
throw new TargetFileWriteError();
}
return new File($this->targetDirectory, $targetFilename, $extension);
} | php | protected function describeTargetFile($extension) {
if ($this->targetDirectory === null) {
throw new TargetDirectoryNotSpecifiedError();
}
$targetFilename = isset($this->targetFilename) ? $this->targetFilename : self::createRandomString();
if (!File::mayNameBeValid($targetFilename)) {
throw new InvalidFilenameException();
}
if (!$this->targetDirectory->exists() && !$this->targetDirectory->createRecursively(0755)) {
throw new TargetFileWriteError();
}
return new File($this->targetDirectory, $targetFilename, $extension);
} | [
"protected",
"function",
"describeTargetFile",
"(",
"$",
"extension",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"targetDirectory",
"===",
"null",
")",
"{",
"throw",
"new",
"TargetDirectoryNotSpecifiedError",
"(",
")",
";",
"}",
"$",
"targetFilename",
"=",
"isset... | Returns a description of the target file
@param string $extension the filename extension to use
@return File the description of the targe file
@throws InvalidFilenameException if the supplied filename has been invalid
@throws Error (do *not* catch) | [
"Returns",
"a",
"description",
"of",
"the",
"target",
"file"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/AbstractUpload.php#L212-L228 |
40,980 | delight-im/PHP-FileUpload | src/AbstractUpload.php | AbstractUpload.areFileUploadsEnabled | private static function areFileUploadsEnabled() {
if (self::parseIniBoolean(\ini_get('file_uploads')) === false) {
return false;
}
if (((int) \ini_get('max_file_uploads')) <= 0) {
return false;
}
return true;
} | php | private static function areFileUploadsEnabled() {
if (self::parseIniBoolean(\ini_get('file_uploads')) === false) {
return false;
}
if (((int) \ini_get('max_file_uploads')) <= 0) {
return false;
}
return true;
} | [
"private",
"static",
"function",
"areFileUploadsEnabled",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"parseIniBoolean",
"(",
"\\",
"ini_get",
"(",
"'file_uploads'",
")",
")",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"(",
"(",
"int",... | Returns whether file uploads are enabled as per PHP's configuration
@return bool | [
"Returns",
"whether",
"file",
"uploads",
"are",
"enabled",
"as",
"per",
"PHP",
"s",
"configuration"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/AbstractUpload.php#L235-L245 |
40,981 | delight-im/PHP-FileUpload | src/AbstractUpload.php | AbstractUpload.determineMaximumUploadSize | private static function determineMaximumUploadSize() {
$postMaxSize = self::parseIniSize(
\ini_get('post_max_size')
);
if ($postMaxSize <= 0) {
$postMaxSize = \PHP_INT_MAX;
}
$memoryLimit = self::parseIniSize(
\ini_get('memory_limit')
);
if ($memoryLimit === -1) {
$memoryLimit = \PHP_INT_MAX;
}
return \min(
self::parseIniSize(
\ini_get('upload_max_filesize')
),
$postMaxSize,
$memoryLimit
);
} | php | private static function determineMaximumUploadSize() {
$postMaxSize = self::parseIniSize(
\ini_get('post_max_size')
);
if ($postMaxSize <= 0) {
$postMaxSize = \PHP_INT_MAX;
}
$memoryLimit = self::parseIniSize(
\ini_get('memory_limit')
);
if ($memoryLimit === -1) {
$memoryLimit = \PHP_INT_MAX;
}
return \min(
self::parseIniSize(
\ini_get('upload_max_filesize')
),
$postMaxSize,
$memoryLimit
);
} | [
"private",
"static",
"function",
"determineMaximumUploadSize",
"(",
")",
"{",
"$",
"postMaxSize",
"=",
"self",
"::",
"parseIniSize",
"(",
"\\",
"ini_get",
"(",
"'post_max_size'",
")",
")",
";",
"if",
"(",
"$",
"postMaxSize",
"<=",
"0",
")",
"{",
"$",
"post... | Determines the maximum allowed size of file uploads as per PHP's configuration
@return int the size in bytes | [
"Determines",
"the",
"maximum",
"allowed",
"size",
"of",
"file",
"uploads",
"as",
"per",
"PHP",
"s",
"configuration"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/AbstractUpload.php#L252-L276 |
40,982 | delight-im/PHP-FileUpload | src/AbstractUpload.php | AbstractUpload.parseIniSize | private static function parseIniSize($sizeStr) {
$sizeStr = \trim($sizeStr);
$unitPrefix = \strtoupper(
\substr($sizeStr, -1)
);
$sizeInt = (int) $sizeStr;
switch ($unitPrefix) {
case 'K':
$sizeInt *= 1024;
break;
case 'M':
$sizeInt *= 1024 * 1024;
break;
case 'G':
$sizeInt *= 1024 * 1024 * 1024;
break;
}
return $sizeInt;
} | php | private static function parseIniSize($sizeStr) {
$sizeStr = \trim($sizeStr);
$unitPrefix = \strtoupper(
\substr($sizeStr, -1)
);
$sizeInt = (int) $sizeStr;
switch ($unitPrefix) {
case 'K':
$sizeInt *= 1024;
break;
case 'M':
$sizeInt *= 1024 * 1024;
break;
case 'G':
$sizeInt *= 1024 * 1024 * 1024;
break;
}
return $sizeInt;
} | [
"private",
"static",
"function",
"parseIniSize",
"(",
"$",
"sizeStr",
")",
"{",
"$",
"sizeStr",
"=",
"\\",
"trim",
"(",
"$",
"sizeStr",
")",
";",
"$",
"unitPrefix",
"=",
"\\",
"strtoupper",
"(",
"\\",
"substr",
"(",
"$",
"sizeStr",
",",
"-",
"1",
")"... | Parses a memory or storage size as found in the `php.ini` configuration file
@param string $sizeStr the representation found in `php.ini`
@return int the effective memory or storage size | [
"Parses",
"a",
"memory",
"or",
"storage",
"size",
"as",
"found",
"in",
"the",
"php",
".",
"ini",
"configuration",
"file"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/AbstractUpload.php#L284-L306 |
40,983 | delight-im/PHP-FileUpload | src/AbstractUpload.php | AbstractUpload.parseIniBoolean | private static function parseIniBoolean($booleanStr) {
if (empty($booleanStr)) {
return false;
}
$booleanStr = \strtolower($booleanStr);
if ($booleanStr === 'off' || $booleanStr === 'false' || $booleanStr === 'no' || $booleanStr === 'none') {
return false;
}
if (((bool) $booleanStr) === false) {
return false;
}
return true;
} | php | private static function parseIniBoolean($booleanStr) {
if (empty($booleanStr)) {
return false;
}
$booleanStr = \strtolower($booleanStr);
if ($booleanStr === 'off' || $booleanStr === 'false' || $booleanStr === 'no' || $booleanStr === 'none') {
return false;
}
if (((bool) $booleanStr) === false) {
return false;
}
return true;
} | [
"private",
"static",
"function",
"parseIniBoolean",
"(",
"$",
"booleanStr",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"booleanStr",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"booleanStr",
"=",
"\\",
"strtolower",
"(",
"$",
"booleanStr",
")",
";",
... | Parses a boolean value as found in the `php.ini` configuration file
@param string $booleanStr the representation found in `php.ini`
@return bool the effective boolean value | [
"Parses",
"a",
"boolean",
"value",
"as",
"found",
"in",
"the",
"php",
".",
"ini",
"configuration",
"file"
] | a793f4b9d6d2fc4ce57487c324a1547cce942cb6 | https://github.com/delight-im/PHP-FileUpload/blob/a793f4b9d6d2fc4ce57487c324a1547cce942cb6/src/AbstractUpload.php#L314-L330 |
40,984 | dereuromark/cakephp-tinyauth | src/Controller/Component/AuthComponent.php | AuthComponent._getAuth | protected function _getAuth($path = null) {
if ($this->getConfig('autoClearCache') && Configure::read('debug')) {
Cache::delete($this->getConfig('allowCacheKey'), $this->getConfig('cache'));
}
$roles = Cache::read($this->getConfig('allowCacheKey'), $this->getConfig('cache'));
if ($roles !== false) {
return $roles;
}
if ($path === null) {
$path = $this->getConfig('allowFilePath');
}
$iniArray = $this->_parseFiles($path, $this->getConfig('allowFile'));
$res = [];
foreach ($iniArray as $key => $actions) {
$res[$key] = $this->_deconstructIniKey($key);
$res[$key]['map'] = $actions;
$actions = explode(',', $actions);
if (in_array('*', $actions)) {
$res[$key]['actions'] = [];
continue;
}
foreach ($actions as $action) {
$action = trim($action);
if (!$action) {
continue;
}
$res[$key]['actions'][] = $action;
}
}
Cache::write($this->getConfig('allowCacheKey'), $res, $this->getConfig('cache'));
return $res;
} | php | protected function _getAuth($path = null) {
if ($this->getConfig('autoClearCache') && Configure::read('debug')) {
Cache::delete($this->getConfig('allowCacheKey'), $this->getConfig('cache'));
}
$roles = Cache::read($this->getConfig('allowCacheKey'), $this->getConfig('cache'));
if ($roles !== false) {
return $roles;
}
if ($path === null) {
$path = $this->getConfig('allowFilePath');
}
$iniArray = $this->_parseFiles($path, $this->getConfig('allowFile'));
$res = [];
foreach ($iniArray as $key => $actions) {
$res[$key] = $this->_deconstructIniKey($key);
$res[$key]['map'] = $actions;
$actions = explode(',', $actions);
if (in_array('*', $actions)) {
$res[$key]['actions'] = [];
continue;
}
foreach ($actions as $action) {
$action = trim($action);
if (!$action) {
continue;
}
$res[$key]['actions'][] = $action;
}
}
Cache::write($this->getConfig('allowCacheKey'), $res, $this->getConfig('cache'));
return $res;
} | [
"protected",
"function",
"_getAuth",
"(",
"$",
"path",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'autoClearCache'",
")",
"&&",
"Configure",
"::",
"read",
"(",
"'debug'",
")",
")",
"{",
"Cache",
"::",
"delete",
"(",
"$",
... | Parse ini file and returns the allowed actions.
Uses cache for maximum performance.
@param string|null $path
@return array Actions | [
"Parse",
"ini",
"file",
"and",
"returns",
"the",
"allowed",
"actions",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Controller/Component/AuthComponent.php#L122-L160 |
40,985 | dereuromark/cakephp-tinyauth | src/Auth/AuthUserTrait.php | AuthUserTrait.isMe | public function isMe($userId) {
$field = $this->getConfig('idColumn');
return $userId && (string)$userId === (string)$this->user($field);
} | php | public function isMe($userId) {
$field = $this->getConfig('idColumn');
return $userId && (string)$userId === (string)$this->user($field);
} | [
"public",
"function",
"isMe",
"(",
"$",
"userId",
")",
"{",
"$",
"field",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'idColumn'",
")",
";",
"return",
"$",
"userId",
"&&",
"(",
"string",
")",
"$",
"userId",
"===",
"(",
"string",
")",
"$",
"this",
"-... | This check can be used to tell if a record that belongs to some user is the
current logged in user
@param string|int $userId
@return bool | [
"This",
"check",
"can",
"be",
"used",
"to",
"tell",
"if",
"a",
"record",
"that",
"belongs",
"to",
"some",
"user",
"is",
"the",
"current",
"logged",
"in",
"user"
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Auth/AuthUserTrait.php#L60-L63 |
40,986 | dereuromark/cakephp-tinyauth | src/Auth/AuthUserTrait.php | AuthUserTrait.user | public function user($key = null) {
$user = $this->_getUser();
if ($key === null) {
return $user;
}
return Hash::get($user, $key);
} | php | public function user($key = null) {
$user = $this->_getUser();
if ($key === null) {
return $user;
}
return Hash::get($user, $key);
} | [
"public",
"function",
"user",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"_getUser",
"(",
")",
";",
"if",
"(",
"$",
"key",
"===",
"null",
")",
"{",
"return",
"$",
"user",
";",
"}",
"return",
"Hash",
"::",
"get"... | Get the user data of the current session.
@param string|null $key Key in dot syntax.
@return mixed Data | [
"Get",
"the",
"user",
"data",
"of",
"the",
"current",
"session",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Auth/AuthUserTrait.php#L71-L77 |
40,987 | dereuromark/cakephp-tinyauth | src/Auth/AuthUserTrait.php | AuthUserTrait.hasRole | public function hasRole($expectedRole, $providedRoles = null) {
if ($providedRoles !== null) {
$roles = (array)$providedRoles;
} else {
$roles = $this->roles();
}
if (!$roles) {
return false;
}
if (array_key_exists($expectedRole, $roles) || in_array($expectedRole, $roles)) {
return true;
}
return false;
} | php | public function hasRole($expectedRole, $providedRoles = null) {
if ($providedRoles !== null) {
$roles = (array)$providedRoles;
} else {
$roles = $this->roles();
}
if (!$roles) {
return false;
}
if (array_key_exists($expectedRole, $roles) || in_array($expectedRole, $roles)) {
return true;
}
return false;
} | [
"public",
"function",
"hasRole",
"(",
"$",
"expectedRole",
",",
"$",
"providedRoles",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"providedRoles",
"!==",
"null",
")",
"{",
"$",
"roles",
"=",
"(",
"array",
")",
"$",
"providedRoles",
";",
"}",
"else",
"{",
... | Check if the current session has this role.
@param mixed $expectedRole
@param mixed|null $providedRoles
@return bool Success | [
"Check",
"if",
"the",
"current",
"session",
"has",
"this",
"role",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Auth/AuthUserTrait.php#L105-L120 |
40,988 | dereuromark/cakephp-tinyauth | src/Auth/AuthUserTrait.php | AuthUserTrait.hasRoles | public function hasRoles($expectedRoles, $oneRoleIsEnough = true, $providedRoles = null) {
if ($providedRoles !== null) {
$roles = $providedRoles;
} else {
$roles = $this->roles();
}
$expectedRoles = (array)$expectedRoles;
if (!$expectedRoles) {
return false;
}
$count = 0;
foreach ($expectedRoles as $expectedRole) {
if ($this->hasRole($expectedRole, $roles)) {
if ($oneRoleIsEnough) {
return true;
}
$count++;
} else {
if (!$oneRoleIsEnough) {
return false;
}
}
}
if ($count === count($expectedRoles)) {
return true;
}
return false;
} | php | public function hasRoles($expectedRoles, $oneRoleIsEnough = true, $providedRoles = null) {
if ($providedRoles !== null) {
$roles = $providedRoles;
} else {
$roles = $this->roles();
}
$expectedRoles = (array)$expectedRoles;
if (!$expectedRoles) {
return false;
}
$count = 0;
foreach ($expectedRoles as $expectedRole) {
if ($this->hasRole($expectedRole, $roles)) {
if ($oneRoleIsEnough) {
return true;
}
$count++;
} else {
if (!$oneRoleIsEnough) {
return false;
}
}
}
if ($count === count($expectedRoles)) {
return true;
}
return false;
} | [
"public",
"function",
"hasRoles",
"(",
"$",
"expectedRoles",
",",
"$",
"oneRoleIsEnough",
"=",
"true",
",",
"$",
"providedRoles",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"providedRoles",
"!==",
"null",
")",
"{",
"$",
"roles",
"=",
"$",
"providedRoles",
";... | Check if the current session has one of these roles.
You can either require one of the roles (default), or you can require all
roles to match.
@param mixed $expectedRoles
@param bool $oneRoleIsEnough (if all $roles have to match instead of just one)
@param mixed|null $providedRoles
@return bool Success | [
"Check",
"if",
"the",
"current",
"session",
"has",
"one",
"of",
"these",
"roles",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Auth/AuthUserTrait.php#L133-L163 |
40,989 | dereuromark/cakephp-tinyauth | src/Utility/Utility.php | Utility.deconstructIniKey | public static function deconstructIniKey($key) {
$res = [
'plugin' => null,
'prefix' => null
];
if (strpos($key, '.') !== false) {
list($res['plugin'], $key) = explode('.', $key);
}
if (strpos($key, '/') !== false) {
list($res['prefix'], $key) = explode('/', $key);
}
$res['controller'] = $key;
return $res;
} | php | public static function deconstructIniKey($key) {
$res = [
'plugin' => null,
'prefix' => null
];
if (strpos($key, '.') !== false) {
list($res['plugin'], $key) = explode('.', $key);
}
if (strpos($key, '/') !== false) {
list($res['prefix'], $key) = explode('/', $key);
}
$res['controller'] = $key;
return $res;
} | [
"public",
"static",
"function",
"deconstructIniKey",
"(",
"$",
"key",
")",
"{",
"$",
"res",
"=",
"[",
"'plugin'",
"=>",
"null",
",",
"'prefix'",
"=>",
"null",
"]",
";",
"if",
"(",
"strpos",
"(",
"$",
"key",
",",
"'.'",
")",
"!==",
"false",
")",
"{"... | Deconstructs an authentication ini section key into a named array with authentication parts.
@param string $key INI section key as found in authentication.ini
@return array Array with named keys for controller, plugin and prefix | [
"Deconstructs",
"an",
"authentication",
"ini",
"section",
"key",
"into",
"a",
"named",
"array",
"with",
"authentication",
"parts",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Utility/Utility.php#L14-L28 |
40,990 | dereuromark/cakephp-tinyauth | src/Utility/Utility.php | Utility.parseFile | public static function parseFile($ini) {
if (!file_exists($ini)) {
throw new Exception(sprintf('Missing TinyAuth config file (%s)', $ini));
}
if (function_exists('parse_ini_file')) {
$iniArray = parse_ini_file($ini, true);
} else {
$content = file_get_contents($ini);
if ($content === false) {
throw new Exception('Cannot load INI file.');
}
$iniArray = parse_ini_string($content, true);
}
if (!is_array($iniArray)) {
throw new Exception(sprintf('Invalid TinyAuth config file (%s)', $ini));
}
return $iniArray;
} | php | public static function parseFile($ini) {
if (!file_exists($ini)) {
throw new Exception(sprintf('Missing TinyAuth config file (%s)', $ini));
}
if (function_exists('parse_ini_file')) {
$iniArray = parse_ini_file($ini, true);
} else {
$content = file_get_contents($ini);
if ($content === false) {
throw new Exception('Cannot load INI file.');
}
$iniArray = parse_ini_string($content, true);
}
if (!is_array($iniArray)) {
throw new Exception(sprintf('Invalid TinyAuth config file (%s)', $ini));
}
return $iniArray;
} | [
"public",
"static",
"function",
"parseFile",
"(",
"$",
"ini",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"ini",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"sprintf",
"(",
"'Missing TinyAuth config file (%s)'",
",",
"$",
"ini",
")",
")",
";"... | Returns the ini file as an array.
@param string $ini Full path to the ini file
@return array List
@throws \Cake\Core\Exception\Exception | [
"Returns",
"the",
"ini",
"file",
"as",
"an",
"array",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Utility/Utility.php#L57-L76 |
40,991 | dereuromark/cakephp-tinyauth | src/Auth/AclTrait.php | AclTrait._loadAclAdapter | protected function _loadAclAdapter($adapter) {
if (!class_exists($adapter)) {
throw new Exception(sprintf('The Acl Adapter class "%s" was not found.', $adapter));
}
$adapterInstance = new $adapter();
if (!($adapterInstance instanceof AclAdapterInterface)) {
throw new InvalidArgumentException(sprintf(
'TinyAuth Acl adapters have to implement %s.', AclAdapterInterface::class
));
}
return $adapterInstance;
} | php | protected function _loadAclAdapter($adapter) {
if (!class_exists($adapter)) {
throw new Exception(sprintf('The Acl Adapter class "%s" was not found.', $adapter));
}
$adapterInstance = new $adapter();
if (!($adapterInstance instanceof AclAdapterInterface)) {
throw new InvalidArgumentException(sprintf(
'TinyAuth Acl adapters have to implement %s.', AclAdapterInterface::class
));
}
return $adapterInstance;
} | [
"protected",
"function",
"_loadAclAdapter",
"(",
"$",
"adapter",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"adapter",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"sprintf",
"(",
"'The Acl Adapter class \"%s\" was not found.'",
",",
"$",
"adapter",... | Finds the Acl adapter to use for this request.
@param string $adapter Acl adapter to load.
@return \TinyAuth\Auth\AclAdapter\AclAdapterInterface
@throws \Cake\Core\Exception\Exception
@throws \InvalidArgumentException | [
"Finds",
"the",
"Acl",
"adapter",
"to",
"use",
"for",
"this",
"request",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Auth/AclTrait.php#L117-L130 |
40,992 | dereuromark/cakephp-tinyauth | src/Auth/AclTrait.php | AclTrait._getAcl | protected function _getAcl($path = null) {
if ($this->getConfig('autoClearCache') && Configure::read('debug')) {
Cache::delete($this->getConfig('aclCacheKey'), $this->getConfig('cache'));
}
$roles = Cache::read($this->getConfig('aclCacheKey'), $this->getConfig('cache'));
if ($roles !== false) {
return $roles;
}
if ($path === null) {
$path = $this->getConfig('aclFilePath');
}
$config = $this->getConfig();
$config['filePath'] = $path;
$config['file'] = $config['aclFile'];
unset($config['aclFilePath']);
unset($config['aclFile']);
$roles = $this->_aclAdapter->getAcl($this->_getAvailableRoles(), $config);
Cache::write($this->getConfig('aclCacheKey'), $roles, $this->getConfig('cache'));
return $roles;
} | php | protected function _getAcl($path = null) {
if ($this->getConfig('autoClearCache') && Configure::read('debug')) {
Cache::delete($this->getConfig('aclCacheKey'), $this->getConfig('cache'));
}
$roles = Cache::read($this->getConfig('aclCacheKey'), $this->getConfig('cache'));
if ($roles !== false) {
return $roles;
}
if ($path === null) {
$path = $this->getConfig('aclFilePath');
}
$config = $this->getConfig();
$config['filePath'] = $path;
$config['file'] = $config['aclFile'];
unset($config['aclFilePath']);
unset($config['aclFile']);
$roles = $this->_aclAdapter->getAcl($this->_getAvailableRoles(), $config);
Cache::write($this->getConfig('aclCacheKey'), $roles, $this->getConfig('cache'));
return $roles;
} | [
"protected",
"function",
"_getAcl",
"(",
"$",
"path",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'autoClearCache'",
")",
"&&",
"Configure",
"::",
"read",
"(",
"'debug'",
")",
")",
"{",
"Cache",
"::",
"delete",
"(",
"$",
"... | Parses INI file and returns the allowed roles per action.
Uses cache for maximum performance.
Improved speed by several actions before caching:
- Resolves role slugs to their primary key / identifier
- Resolves wildcards to their verbose translation
@param string|array|null $path
@return array Roles | [
"Parses",
"INI",
"file",
"and",
"returns",
"the",
"allowed",
"roles",
"per",
"action",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Auth/AclTrait.php#L290-L312 |
40,993 | dereuromark/cakephp-tinyauth | src/Auth/AclTrait.php | AclTrait._constructIniKey | protected function _constructIniKey($params) {
$res = $params['controller'];
if (!empty($params['prefix'])) {
$res = $params['prefix'] . "/$res";
}
if (!empty($params['plugin'])) {
$res = $params['plugin'] . ".$res";
}
return $res;
} | php | protected function _constructIniKey($params) {
$res = $params['controller'];
if (!empty($params['prefix'])) {
$res = $params['prefix'] . "/$res";
}
if (!empty($params['plugin'])) {
$res = $params['plugin'] . ".$res";
}
return $res;
} | [
"protected",
"function",
"_constructIniKey",
"(",
"$",
"params",
")",
"{",
"$",
"res",
"=",
"$",
"params",
"[",
"'controller'",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"params",
"[",
"'prefix'",
"]",
")",
")",
"{",
"$",
"res",
"=",
"$",
"param... | Constructs an ACL INI section key from a given Request.
@param array $params The request params
@return string Hash with named keys for controller, plugin and prefix | [
"Constructs",
"an",
"ACL",
"INI",
"section",
"key",
"from",
"a",
"given",
"Request",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Auth/AclTrait.php#L341-L350 |
40,994 | dereuromark/cakephp-tinyauth | src/Auth/AclTrait.php | AclTrait._getAvailableRoles | protected function _getAvailableRoles() {
if ($this->_roles !== null) {
return $this->_roles;
}
$roles = Configure::read($this->getConfig('rolesTable'));
if (is_array($roles)) {
if ($this->getConfig('superAdminRole')) {
$key = $this->getConfig('superAdmin') ?: 'superadmin';
$roles[$key] = $this->getConfig('superAdminRole');
}
return $roles;
}
$rolesTable = TableRegistry::get($this->getConfig('rolesTable'));
$result = $rolesTable->find()->formatResults(function (ResultSetInterface $results) {
return $results->combine($this->getConfig('aliasColumn'), 'id');
});
$roles = $result->toArray();
if ($this->getConfig('superAdminRole')) {
$key = $this->getConfig('superAdmin') ?: 'superadmin';
$roles[$key] = $this->getConfig('superAdminRole');
}
if (count($roles) < 1) {
throw new Exception('Invalid TinyAuth role setup (roles table `' . $this->getConfig('rolesTable') . '` has no roles)');
}
$this->_roles = $roles;
return $roles;
} | php | protected function _getAvailableRoles() {
if ($this->_roles !== null) {
return $this->_roles;
}
$roles = Configure::read($this->getConfig('rolesTable'));
if (is_array($roles)) {
if ($this->getConfig('superAdminRole')) {
$key = $this->getConfig('superAdmin') ?: 'superadmin';
$roles[$key] = $this->getConfig('superAdminRole');
}
return $roles;
}
$rolesTable = TableRegistry::get($this->getConfig('rolesTable'));
$result = $rolesTable->find()->formatResults(function (ResultSetInterface $results) {
return $results->combine($this->getConfig('aliasColumn'), 'id');
});
$roles = $result->toArray();
if ($this->getConfig('superAdminRole')) {
$key = $this->getConfig('superAdmin') ?: 'superadmin';
$roles[$key] = $this->getConfig('superAdminRole');
}
if (count($roles) < 1) {
throw new Exception('Invalid TinyAuth role setup (roles table `' . $this->getConfig('rolesTable') . '` has no roles)');
}
$this->_roles = $roles;
return $roles;
} | [
"protected",
"function",
"_getAvailableRoles",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_roles",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"_roles",
";",
"}",
"$",
"roles",
"=",
"Configure",
"::",
"read",
"(",
"$",
"this",
"->",
"get... | Returns a list of all available roles.
Will look for a roles array in
Configure first, tries database roles table next.
@return array List with all available roles
@throws \Cake\Core\Exception\Exception | [
"Returns",
"a",
"list",
"of",
"all",
"available",
"roles",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Auth/AclTrait.php#L361-L393 |
40,995 | dereuromark/cakephp-tinyauth | src/Auth/AclTrait.php | AclTrait._getUserRoles | protected function _getUserRoles($user) {
// Single-role from session
if (!$this->getConfig('multiRole')) {
if (!array_key_exists($this->getConfig('roleColumn'), $user)) {
throw new Exception(sprintf('Missing TinyAuth role id field (%s) in user session', 'Auth.User.' . $this->getConfig('roleColumn')));
}
if (!isset($user[$this->getConfig('roleColumn')])) {
return [];
}
return $this->_mapped([$user[$this->getConfig('roleColumn')]]);
}
// Multi-role from session
if (isset($user[$this->getConfig('rolesTable')])) {
$userRoles = $user[$this->getConfig('rolesTable')];
if (isset($userRoles[0]['id'])) {
$userRoles = Hash::extract($userRoles, '{n}.id');
}
return $this->_mapped((array)$userRoles);
}
// Multi-role from session via pivot table
$pivotTableName = $this->getConfig('pivotTable');
if (!$pivotTableName) {
list(, $rolesTableName) = pluginSplit($this->getConfig('rolesTable'));
list(, $usersTableName) = pluginSplit($this->getConfig('usersTable'));
$tables = [
$usersTableName,
$rolesTableName
];
asort($tables);
$pivotTableName = implode('', $tables);
}
if (isset($user[$pivotTableName])) {
$userRoles = $user[$pivotTableName];
if (isset($userRoles[0][$this->getConfig('roleColumn')])) {
$userRoles = Hash::extract($userRoles, '{n}.' . $this->getConfig('roleColumn'));
}
return $this->_mapped((array)$userRoles);
}
// Multi-role from DB: load the pivot table
$roles = $this->_getRolesFromDb($pivotTableName, $user[$this->getConfig('idColumn')]);
if (!$roles) {
return [];
}
return $this->_mapped($roles);
} | php | protected function _getUserRoles($user) {
// Single-role from session
if (!$this->getConfig('multiRole')) {
if (!array_key_exists($this->getConfig('roleColumn'), $user)) {
throw new Exception(sprintf('Missing TinyAuth role id field (%s) in user session', 'Auth.User.' . $this->getConfig('roleColumn')));
}
if (!isset($user[$this->getConfig('roleColumn')])) {
return [];
}
return $this->_mapped([$user[$this->getConfig('roleColumn')]]);
}
// Multi-role from session
if (isset($user[$this->getConfig('rolesTable')])) {
$userRoles = $user[$this->getConfig('rolesTable')];
if (isset($userRoles[0]['id'])) {
$userRoles = Hash::extract($userRoles, '{n}.id');
}
return $this->_mapped((array)$userRoles);
}
// Multi-role from session via pivot table
$pivotTableName = $this->getConfig('pivotTable');
if (!$pivotTableName) {
list(, $rolesTableName) = pluginSplit($this->getConfig('rolesTable'));
list(, $usersTableName) = pluginSplit($this->getConfig('usersTable'));
$tables = [
$usersTableName,
$rolesTableName
];
asort($tables);
$pivotTableName = implode('', $tables);
}
if (isset($user[$pivotTableName])) {
$userRoles = $user[$pivotTableName];
if (isset($userRoles[0][$this->getConfig('roleColumn')])) {
$userRoles = Hash::extract($userRoles, '{n}.' . $this->getConfig('roleColumn'));
}
return $this->_mapped((array)$userRoles);
}
// Multi-role from DB: load the pivot table
$roles = $this->_getRolesFromDb($pivotTableName, $user[$this->getConfig('idColumn')]);
if (!$roles) {
return [];
}
return $this->_mapped($roles);
} | [
"protected",
"function",
"_getUserRoles",
"(",
"$",
"user",
")",
"{",
"// Single-role from session",
"if",
"(",
"!",
"$",
"this",
"->",
"getConfig",
"(",
"'multiRole'",
")",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"this",
"->",
"getConfig",
... | Returns a list of all roles belonging to the authenticated user.
Lookup in the following order:
- single role id using the roleColumn in single-role mode
- direct lookup in the pivot table (to support both Configure and Model
in multi-role mode)
@param array $user The user to get the roles for
@return array List with all role ids belonging to the user
@throws \Cake\Core\Exception\Exception | [
"Returns",
"a",
"list",
"of",
"all",
"roles",
"belonging",
"to",
"the",
"authenticated",
"user",
"."
] | a5ce544d93f28a5d3aecc141e3fd59dafef90521 | https://github.com/dereuromark/cakephp-tinyauth/blob/a5ce544d93f28a5d3aecc141e3fd59dafef90521/src/Auth/AclTrait.php#L407-L455 |
40,996 | spatie/laravel-partialcache | src/PartialCache.php | PartialCache.cache | public function cache($data, $view, $mergeData = null, $minutes = null, $key = null, $tag = null)
{
if (! $this->enabled) {
return call_user_func($this->renderView($view, $data, $mergeData));
}
$viewKey = $this->getCacheKeyForView($view, $key);
$mergeData = $mergeData ?: [];
$tags = $this->getTags($tag);
$minutes = $this->resolveCacheDuration($minutes);
if ($this->cacheIsTaggable && $minutes === null) {
return $this->cache
->tags($tags)
->rememberForever($viewKey, $this->renderView($view, $data, $mergeData));
}
if ($this->cacheIsTaggable) {
return $this->cache
->tags($tags)
->remember($viewKey, $minutes, $this->renderView($view, $data, $mergeData));
}
if ($minutes === null) {
return $this->cache
->rememberForever($viewKey, $this->renderView($view, $data, $mergeData));
}
return $this->cache
->remember($viewKey, $minutes, $this->renderView($view, $data, $mergeData));
} | php | public function cache($data, $view, $mergeData = null, $minutes = null, $key = null, $tag = null)
{
if (! $this->enabled) {
return call_user_func($this->renderView($view, $data, $mergeData));
}
$viewKey = $this->getCacheKeyForView($view, $key);
$mergeData = $mergeData ?: [];
$tags = $this->getTags($tag);
$minutes = $this->resolveCacheDuration($minutes);
if ($this->cacheIsTaggable && $minutes === null) {
return $this->cache
->tags($tags)
->rememberForever($viewKey, $this->renderView($view, $data, $mergeData));
}
if ($this->cacheIsTaggable) {
return $this->cache
->tags($tags)
->remember($viewKey, $minutes, $this->renderView($view, $data, $mergeData));
}
if ($minutes === null) {
return $this->cache
->rememberForever($viewKey, $this->renderView($view, $data, $mergeData));
}
return $this->cache
->remember($viewKey, $minutes, $this->renderView($view, $data, $mergeData));
} | [
"public",
"function",
"cache",
"(",
"$",
"data",
",",
"$",
"view",
",",
"$",
"mergeData",
"=",
"null",
",",
"$",
"minutes",
"=",
"null",
",",
"$",
"key",
"=",
"null",
",",
"$",
"tag",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
... | Cache a view. If minutes are null, the view is cached forever.
@param array $data
@param string $view
@param array $mergeData
@param int $minutes
@param string $key
@param string|array $tag
@return string | [
"Cache",
"a",
"view",
".",
"If",
"minutes",
"are",
"null",
"the",
"view",
"is",
"cached",
"forever",
"."
] | 1e0d24a8c2f0f53a23a59f81a3af41ba9089914c | https://github.com/spatie/laravel-partialcache/blob/1e0d24a8c2f0f53a23a59f81a3af41ba9089914c/src/PartialCache.php#L59-L92 |
40,997 | spatie/laravel-partialcache | src/PartialCache.php | PartialCache.getCacheKeyForView | public function getCacheKeyForView($view, $key = null)
{
$parts = [$this->cacheKey, $view];
if ($key !== null) {
$parts[] = $key;
}
return implode('.', $parts);
} | php | public function getCacheKeyForView($view, $key = null)
{
$parts = [$this->cacheKey, $view];
if ($key !== null) {
$parts[] = $key;
}
return implode('.', $parts);
} | [
"public",
"function",
"getCacheKeyForView",
"(",
"$",
"view",
",",
"$",
"key",
"=",
"null",
")",
"{",
"$",
"parts",
"=",
"[",
"$",
"this",
"->",
"cacheKey",
",",
"$",
"view",
"]",
";",
"if",
"(",
"$",
"key",
"!==",
"null",
")",
"{",
"$",
"parts",... | Create a key name for the cached view.
@param string $view
@param string $key
@return string | [
"Create",
"a",
"key",
"name",
"for",
"the",
"cached",
"view",
"."
] | 1e0d24a8c2f0f53a23a59f81a3af41ba9089914c | https://github.com/spatie/laravel-partialcache/blob/1e0d24a8c2f0f53a23a59f81a3af41ba9089914c/src/PartialCache.php#L102-L111 |
40,998 | spatie/laravel-partialcache | src/PartialCache.php | PartialCache.forget | public function forget($view, $key = null, $tag = null)
{
$cacheKey = $this->getCacheKeyForView($view, $key);
if ($this->cacheIsTaggable) {
$tags = $this->getTags($tag);
$this->cache->tags($tags)->forget($cacheKey);
}
$this->cache->forget($cacheKey);
} | php | public function forget($view, $key = null, $tag = null)
{
$cacheKey = $this->getCacheKeyForView($view, $key);
if ($this->cacheIsTaggable) {
$tags = $this->getTags($tag);
$this->cache->tags($tags)->forget($cacheKey);
}
$this->cache->forget($cacheKey);
} | [
"public",
"function",
"forget",
"(",
"$",
"view",
",",
"$",
"key",
"=",
"null",
",",
"$",
"tag",
"=",
"null",
")",
"{",
"$",
"cacheKey",
"=",
"$",
"this",
"->",
"getCacheKeyForView",
"(",
"$",
"view",
",",
"$",
"key",
")",
";",
"if",
"(",
"$",
... | Forget a rendered view.
@param string $view
@param string $key
@param null|string|array $tag | [
"Forget",
"a",
"rendered",
"view",
"."
] | 1e0d24a8c2f0f53a23a59f81a3af41ba9089914c | https://github.com/spatie/laravel-partialcache/blob/1e0d24a8c2f0f53a23a59f81a3af41ba9089914c/src/PartialCache.php#L120-L130 |
40,999 | spatie/laravel-partialcache | src/PartialCache.php | PartialCache.getTags | protected function getTags($tag = null)
{
$tags = [$this->cacheKey];
if ($tag) {
if (! is_array($tag)) {
$tag = [$tag];
}
$tags = array_merge($tags, $tag);
}
return $tags;
} | php | protected function getTags($tag = null)
{
$tags = [$this->cacheKey];
if ($tag) {
if (! is_array($tag)) {
$tag = [$tag];
}
$tags = array_merge($tags, $tag);
}
return $tags;
} | [
"protected",
"function",
"getTags",
"(",
"$",
"tag",
"=",
"null",
")",
"{",
"$",
"tags",
"=",
"[",
"$",
"this",
"->",
"cacheKey",
"]",
";",
"if",
"(",
"$",
"tag",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"tag",
")",
")",
"{",
"$",
"tag... | Constructs tag array.
@param null|string|array $tag
@return array | [
"Constructs",
"tag",
"array",
"."
] | 1e0d24a8c2f0f53a23a59f81a3af41ba9089914c | https://github.com/spatie/laravel-partialcache/blob/1e0d24a8c2f0f53a23a59f81a3af41ba9089914c/src/PartialCache.php#L177-L190 |
Subsets and Splits
Yii Code Samples
Gathers all records from test, train, and validation sets that contain the word 'yii', providing a basic filtered view of the dataset relevant to Yii-related content.