Save acl.

@param string $idRole
@param array  $values
@param bool   $deleteBeforeSave
@return int
334582
public function saveAcl(string $idRole, array $values, bool $deleteBeforeSave = true): int
    {
        if ($deleteBeforeSave) {
            // delete all acl for idRole
            unset($this->data['acl'][$idRole]);
        }

        // save all to role
        if (isset($values['all']) && $values['all']) {
            $this->data['acl'][$idRole] = 'all';
            return file_put_contents($this->path, Neon::encode($this->data, Neon::BLOCK));
        }

        // save acl by role && resource
        foreach ($values as $idResource => $item) {
            if ($item && is_array($item)) {
                if (!in_array('all', $item)) {
                    if (!isset($this->data['acl'][$idRole][$idResource])) {
                        $this->data['acl'][$idRole][$idResource] = $item;
                    } else {
                        $this->data['acl'][$idRole][$idResource] = array_merge($this->data['acl'][$idRole][$idResource], $item);
                    }
                } else {
                    $this->data['acl'][$idRole][$idResource][] = 'all';
                }
            }
        }
        return file_put_contents($this->path, Neon::encode($this->data, Neon::BLOCK));
    }
882073
private function removeFromToArcPair( $role, $arcrole, $fromId, $toId, $fromLabel, $toLabel )
	{
		if ( ! XBRL::isValidating() ) return true;

		$hashFromTo = hash( 'SHA256', "{$arcrole}-{$fromId}-{$toId}" );
		unset( $this->extendedLinkFromToPairs[ $role ][ $hashFromTo ] );

		if ( $arcrole == XBRL_Constants::$arcRoleSummationItem )
		{
			$hashFromTo = hash( 'SHA256', "{$arcrole}-{$fromLabel}-{$toLabel}" );
			unset( $this->calculationExtendedLinkFromToPairs[ $role ][ $hashFromTo ] );
		}
	}
1218565
public function copy($oldRole, $newRoleName)
    {
        /**
         * @var Role $newRole
         */
        $newRole = new $this->model();
        $newRole->fill([
            'name'       => $newRoleName,
            'label'      => $newRoleName,
            'guard_name' => $oldRole->guard_name
        ]);
        $newRole->save();

        $newRole = $this->update(['permissions' => $oldRole->permissions->toArray()], $newRole->id);
        return $newRole;
    }
1295587
public Result<Void> delPermFromRole(AuthzTrans trans, RoleDAO.Data role,PermDAO.Data pd, boolean fromApproval) {
		String user = trans.user();
		if (!fromApproval) {
			Result<NsDAO.Data> ucr = q.mayUser(trans, user, role, Access.write);
			Result<NsDAO.Data> ucp = q.mayUser(trans, user, pd, Access.write);

			// If Can't change either Role or Perm, then deny
			if (ucr.notOK() && ucp.notOK()) {
				return Result.err(Status.ERR_Denied,
						"User [" + trans.user()
								+ "] does not have permission to delete ["
								+ pd.encode() + "] from Role ["
								+ role.fullName() + ']');
			}
		}

		Result<List<RoleDAO.Data>> rlr = q.roleDAO.read(trans, role);
		if (rlr.notOKorIsEmpty()) {
			// If Bad Data, clean out
			Result<List<PermDAO.Data>> rlp = q.permDAO.read(trans, pd);
			if (rlp.isOKhasData()) {
				for (PermDAO.Data pv : rlp.value) {
					q.permDAO.delRole(trans, pv, role);
				}
			}
			return Result.err(rlr);
		}
		String perm1 = pd.encode();
		boolean notFound;
		if (trans.forceRequested()) {
			notFound = false;
		} else { // only check if force not set.
			notFound = true;
			for (RoleDAO.Data r : rlr.value) {
				if (r.perms != null) {
					for (String perm : r.perms) {
						if (perm1.equals(perm)) {
							notFound = false;
							break;
						}
					}
					if(!notFound) {
						break;
					}
				}
			}
		}
		if (notFound) { // Need to check both, in case of corruption
			return Result.err(Status.ERR_PermissionNotFound,
					"Permission [%s.%s|%s|%s] not associated with any Role",
					pd.ns,pd.type,pd.instance,pd.action);
		}

		// Read Perm for full data
		Result<List<PermDAO.Data>> rlp = q.permDAO.read(trans, pd);
		Result<Void> rv = null;
		if (rlp.isOKhasData()) {
			for (PermDAO.Data pv : rlp.value) {
				if ((rv = q.permDAO.delRole(trans, pv, role)).isOK()) {
					if ((rv = q.roleDAO.delPerm(trans, role, pv)).notOK()) {
						trans.error().log(
								"Error removing Perm during delFromPermRole:",
								trans.getUserPrincipal(), rv.errorString());
					}
				} else {
					trans.error().log(
							"Error removing Role during delFromPermRole:",
							trans.getUserPrincipal(), rv.errorString());
				}
			}
		} else {
			rv = q.roleDAO.delPerm(trans, role, pd);
			if (rv.notOK()) {
				trans.error().log("Error removing Role during delFromPermRole",
						rv.errorString());
			}
		}
		return rv == null ? Result.ok() : rv;
	}
1251945
public function syncRoles($roles, $detach = false)
    {
        foreach ($roles as $k => $slug) {
            // add dealer role to user
            $role = Role::where('keyword', $slug)->first();
            $this->roles()->syncWithoutDetaching([$role->id]);
        }

        return $this->roles;
    }
665685
public function removeRole($idOrName)
    {
        $ids = is_array($idOrName) ? $idOrName : func_get_args();

        foreach ($ids as $search) {
            $role = Role::search($search)->firstOrFail();

            $this->roles()->detach($role->id);
        }
    }
1069175
public function removeRole($id, $role)
    {
        $user = $this->getUser($id);

        if (empty($user) || empty($role)) {
            return false;
        }

        // Remove the role from the $user['roles'] array.
        $user['roles'] = array_diff($user['roles'], [(string) $role]);

        return $this->saveUser($user);
    }
1291810
public static function createRole($name, $isDefault, $permissions = [])
    {

        // Create admin role
        $role = (new static());
        $role->name = $name;
        $role->isDefault = $isDefault;
        $role->slug = str_slug($name);

        if($createdRole = $role->save()) {
            // Assert Permissions
            if($permissions) {
                $permissionObj = new Permission();
                foreach ($permissions as $permission) {
                    $permissionObj->assertPermission($role->groupID, $permission);
                }
            }

            return true;
        }

        return false;
    }
311979
protected function saveProperty( $id, $name, $value )
    {
        $rows   = 0;
        $sql    = $this->sql( $this->getTableInSchema(
            static::$propertyTableName
        ) );

        $like = strtr( $name, array(
            '\\' => '\\\\',
            '%' => '\%',
            '_' => '\_',
        ) ) . '.%';

        if ( is_array( $value ) )
        {
            $nameLikeOrEq = new Sql\Predicate\PredicateSet( array(
                new Sql\Predicate\Like( 'name', $like ),
                new Sql\Predicate\Operator( 'name', Sql\Predicate\Operator::OP_EQ, $name )
            ), Sql\Predicate\PredicateSet::OP_OR );

            if ( empty( $value ) )
            {
                $delete = $sql->delete()
                              ->where( array(
                                  'menuId'  => $id,
                                  $nameLikeOrEq,
                              ) );

                $rows += $sql->prepareStatementForSqlObject( $delete )
                             ->execute()
                             ->getAffectedRows();
            }
            else
            {
                $keys = array();

                foreach ( $value as $idx => $val )
                {
                    $keys[] = $key = $name . '.' . $idx;
                    $rows += $this->saveSingleProperty( $id, $key, $val );
                }

                $delete = $sql->delete()
                              ->where( array(
                                  'menuId'  => $id,
                                  $nameLikeOrEq,
                                  new NotIn( 'name', $keys ),
                              ) );

                $rows += $sql->prepareStatementForSqlObject( $delete )
                             ->execute()
                             ->getAffectedRows();
            }
        }
        else
        {
            $rows += $this->saveSingleProperty( $id, $name, $value );

            $delete = $sql->delete()
                          ->where( array(
                              'menuId'  => $id,
                              new Sql\Predicate\Like( 'name', $like ),
                          ) );

            $rows += $sql->prepareStatementForSqlObject( $delete )
                         ->execute()
                         ->getAffectedRows();
        }

        return $rows;
    }
364777
public function createUserWithRoles(array $roles = ['authenticated'], $password = FALSE) {
    $faker = Faker::create();
    /** @var \Drupal\user\Entity\User $user */
    $user = User::create([
      'name' => $faker->userName,
      'mail' => $faker->email,
      'roles' => $roles,
      'pass' => $password ? $password : $faker->password(12, 14),
      'status' => 1,
    ]);

    $user->save();

    $this->users[] = $user->id();

    return $user;
  }
1115381
public function createXmlRightsValues($id, $datas, $isRole = false): array
    {
        /** @var \MelisCore\Service\MelisCoreConfigService $melisAppConfig */
        $melisAppConfig = $this->getServiceLocator()->get('MelisCoreConfig');
        $melisKeys = $melisAppConfig->getMelisKeys();

        /**
         * Core rights make no difference between user or userrole because
         * all nodes are shown, so we just need to check what was posted.
         * There's no lazy tree, so no need to compare whatever in the user or role xml
         * already existing.
         */
        $nodesSeen = Json::decode($datas['treeStatus']);
        $nodesSeen = $nodesSeen->treeStatus;
        $nodesInterface = Json::decode($datas[self::MELISCORE_PREFIX_INTERFACE . '_root']);
        $nodesTools = Json::decode($datas[self::MELIS_PLATFORM_TOOLS_PREFIX . '_root']);

        // Creating interface xml
        $interfaceNode = self::MELISCORE_PREFIX_INTERFACE . '_root';
        $xmlRights = '<' . self::MELISCORE_PREFIX_INTERFACE . '>' . self::XML_ENDLINE;
        if (!empty($nodesInterface) && !empty($nodesInterface->$interfaceNode)) {
            foreach ($nodesInterface->$interfaceNode as $idInterface) {
                if ($idInterface != $interfaceNode) {
                    $idUnPrefixed = str_replace(self::MELISCORE_PREFIX_INTERFACE . '_', '', $idInterface);
                } else {
                    $idUnPrefixed = $idInterface;
                }
                $xmlRights .= self::XML_SPACER . '<id>' . $idUnPrefixed . '</id>' . self::XML_ENDLINE;
            }
        }
        $xmlRights .= '</' . self::MELISCORE_PREFIX_INTERFACE . '>' . self::XML_ENDLINE;

        // Creating tools xml
        $toolsNode = self::MELIS_PLATFORM_TOOLS_PREFIX . '_root';
        $xmlRights .= '<' . self::MELIS_PLATFORM_TOOLS_PREFIX . '>' . self::XML_ENDLINE;

        // here we list all the available tool sections
        foreach ($this->getMelisKeyPaths() as $toolSection) {
            $xmlRights .=  self::XML_SPACER . '<' . $toolSection . '>' . self::XML_ENDLINE;
            if (!empty($nodesTools) && !empty($nodesTools->$toolsNode)) {
                foreach ($nodesTools->$toolsNode as $idTool) {
                    $parent = $this->getSectionParent($idTool) ?? null;

                    if (! $parent) {
                        // check if this tool ID exists in xml
                        if (! preg_match("/$idTool/", $xmlRights) && $idTool !== $toolsNode) {
                            $xmlRights .= self::XML_SPACER . self::XML_SPACER . '<noparent>' . $idTool . '</noparent>' . self::XML_ENDLINE;
                        }
                    } else {
                        if ($parent === $toolSection && $idTool !== $toolsNode) {
                            $id = $idTool === $parent ? $idTool . '_root' : $idTool;
                            $xmlRights .= self::XML_SPACER . self::XML_SPACER . '<id>' . $id . '</id>' . self::XML_ENDLINE;
                        }
                    }
                }
            }
            $xmlRights .=  self::XML_SPACER . '</' . $toolSection . '>' . self::XML_ENDLINE;
        }

        // for general business, if it's checked then we just saved its root
        if (!empty($nodesTools) && !empty($nodesTools->$toolsNode)) {
            foreach ($nodesTools->$toolsNode as $idTool) {
                if ($idTool === $toolsNode) {
                    $xmlRights .= self::XML_SPACER . '<id>' . $toolsNode . '</id>' . self::XML_ENDLINE;
                }
            }
        }

        $xmlRights .= '</' . self::MELIS_PLATFORM_TOOLS_PREFIX . '>' . self::XML_ENDLINE;

        return ['meliscore_rights' => $xmlRights];
    }
283143
protected function hasUnprocessedTransactionStatusLogs($idSalesOrder, $idSalesOrderItem)
    {
        $records = $this->getUnprocessedTransactionStatusLogs($idSalesOrder, $idSalesOrderItem);

        return !empty($transactionStatusLogs);
    }
1106293
public function saveRoles($inputRoles)
    {
        if (!empty($inputRoles)) {
            $this->roles()->sync($inputRoles);
        } else {
            $this->roles()->detach();
        }
    }
90541
public static function deleteExternalAccount($id, $externalAccountId, $params = null, $opts = null)
    {
        return self::_deleteNestedResource($id, static::PATH_EXTERNAL_ACCOUNTS, $externalAccountId, $params, $opts);
    }
1222904
public function beforePropertyModelSave(Property &$property, $insert)
    {
        // static values are forced to be of integer data type
        $property->data_type = Property::DATA_TYPE_INTEGER;
        return parent::beforePropertyModelSave($property, $insert);
    }
1341639
public function edit(BlockManagerInterface $blockManager, array $values)
    {
        try {
            $this->blockRepository->startTransaction();

            $result = $blockManager->save($values);
            if ($result !== false) {
                $this->blockRepository->commit();
                $this->lastEdited = $blockManager;

                return $result;
            }

            $this->blockRepository->rollBack();

            return $result;
        } catch (\Exception $e) {
            $this->blockRepository->rollBack();

            throw $e;
        }
    }
633986
private function generalSave(array $values, $dataIndex): int
    {
        $id = $values['id'];
        unset($values['id']);

        if (!$id) {
            // add
            if (!in_array($values[$dataIndex], $this->data[$dataIndex] ?? [])) {
                $this->data[$dataIndex][] = $values[$dataIndex];
            } else {
                throw new UniqueConstraintViolationException('Item already exist!');
            }
        } else {
            // update
            if ($values) {
                if ($id != $values[$dataIndex]) {
                    $index = array_search($id, $this->data[$dataIndex]);
                    if ($index !== false && !in_array($values[$dataIndex], $this->data[$dataIndex])) {
                        $this->data[$dataIndex][$index] = $values[$dataIndex];
                    } else {
                        throw new UniqueConstraintViolationException('Item already exist!');
                    }
                } else {
                    return 0;
                }
            } else {
                // delete
                $index = array_search($id, $this->data[$dataIndex]);
                if ($index !== false) {
                    unset($this->data[$dataIndex][$index]);
                    $this->data[$dataIndex] = array_values($this->data[$dataIndex]);    // correct fix for index array
                }
            }
        }
        return file_put_contents($this->path, Neon::encode($this->data, Neon::BLOCK));
    }