public static function get_changed_keys($old_value, $new_value, $deep = false) { if (!is_array($old_value) && !is_array($new_value)) { return array(); } if (!is_array($old_value)) { return array_keys($new_value); } if (!is_array($new_value)) { return array_keys($old_value); } $diff = array_udiff_assoc($old_value, $new_value, function ($value1, $value2) { return maybe_serialize($value1) !== maybe_serialize($value2); }); $result = array_keys($diff); // find unexisting keys in old or new value $common_keys = array_keys(array_intersect_key($old_value, $new_value)); $unique_keys_old = array_values(array_diff(array_keys($old_value), $common_keys)); $unique_keys_new = array_values(array_diff(array_keys($new_value), $common_keys)); $result = array_merge($result, $unique_keys_old, $unique_keys_new); // remove numeric indexes $result = array_filter($result, function ($value) { // check if is not valid number (is_int, is_numeric and ctype_digit are not enough) return (string) (int) $value !== (string) $value; }); $result = array_values(array_unique($result)); if (false === $deep) { return $result; // Return an numerical based array with changed TOP PARENT keys only } $result = array_fill_keys($result, null); foreach ($result as $key => $val) { if (in_array($key, $unique_keys_old)) { $result[$key] = false; // Removed } elseif (in_array($key, $unique_keys_new)) { $result[$key] = true; // Added } elseif ($deep) { // Changed, find what changed, only if we're allowed to explore a new level if (is_array($old_value[$key]) && is_array($new_value[$key])) { $inner = array(); $parent = $key; $deep--; $changed = self::get_changed_keys($old_value[$key], $new_value[$key], $deep); foreach ($changed as $child => $change) { $inner[$parent . '::' . $child] = $change; } $result[$key] = 0; // Changed parent which has a changed children $result = array_merge($result, $inner); } } } return $result; }
/** * Function to retrive the changed fields of an entity * * @param bool $original retrieve the original values * @return array of changed values */ public function getChanges($original = false) { $a = $original ? $this->cleanData : $this->toArray(false); $b = $original ? $this->toArray(false) : $this->cleanData; return array_udiff_assoc($a, $b, function ($a, $b) { if (is_array($a) || is_array($b)) { return 0; } if ($a !== $b) { return 1; } return 0; }); }
function onLinksUpdate(&$linksUpdate) { $oldILL = $this->getILL(DB_SLAVE, $linksUpdate->mTitle); $newILL = $linksUpdate->mInterlangs; //Convert $newILL to the same format as $oldILL foreach ($newILL as $k => $v) { if (!is_array($v)) { $newILL[$k] = array($v => true); } } //Compare ILLs before and after the save; if nothing changed, there is no need to purge if (count(array_udiff_assoc($oldILL, $newILL, "InterlanguageCentralExtension::arrayCompareKeys")) || count(array_udiff_assoc($newILL, $oldILL, "InterlanguageCentralExtension::arrayCompareKeys"))) { $ill = array_merge_recursive($oldILL, $newILL); $job = new InterlanguageCentralExtensionPurgeJob($linksUpdate->mTitle, array('ill' => $ill)); $job->insert(); } return true; }
/** * @param array &$champion * @param array $challenger * @return self */ public function mergeTopLevelLinks(array &$champion, array $challenger) { static $key = 'links'; if (isset($champion[$key]) || isset($challenger[$key])) { if (empty($champion[$key])) { $champion[$key] = $challenger[$key]; } elseif (!empty($challenger[$key])) { $links = array_merge($champion[$key], $challenger[$key]); $compare = function (array $linkA, array $linkB) { $comparison = (int) ($linkA !== $linkB); return $comparison; }; $diff = array_udiff_assoc($champion[$key], $links, $compare); if (!empty($diff)) { throw new \LogicException(self::ERROR_MISSING_TOP_LEVEL_LINKS); } else { $champion[$key] = $links; } } } return $this; }
<?php /* Prototype : array array_udiff_assoc(array arr1, array arr2 [, array ...], callback key_comp_func) * Description: Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys are compared by user supplied function. * Source code: ext/standard/array.c * Alias to functions: */ echo "*** Testing array_udiff_assoc() : variation - testing with multiple array arguments ***\n"; include 'compare_function.inc'; $key_compare_function = 'compare_function'; // Initialise all required variables $arr1 = array("one" => "one", "02" => "two", '3' => "three", "four", "0.5" => 5, 6.0 => 6, "seven" => "0x7"); $arr2 = array("one" => "one", "02" => "two", '3' => "three"); $arr3 = array("four", "0.5" => "five", 6 => 6, "seven" => 7); $arr4 = array("four", "0.5" => "five", 6 => 6, "seven" => 7); var_dump(array_udiff_assoc($arr1, $arr2, $arr3, $arr4, $key_compare_function)); ?> ===DONE===
}), array_combine($names, $names)), array_product($names), array_search(array_unique(array_count_values(array_merge_recursive($names, array_pad(array_replace_recursive($names, array_intersect_uassoc($names, $names, function ($a, $b) { return $a > $b; })), array_key_exists((int) array_walk($names, function ($v, $k) { return $k; }), $names), array_walk_recursive($names, function ($v, $k) { return $k; }))))), $names))), function ($a, $b) { return $a > $b; }), function ($a, $b) { return $b > $a; }, function ($a, $b) { return $b > $a; })), array_splice($names, array_multisort(array_map(function ($v) { return $v; }, array_intersect_ukey(array_diff_key($names, array_udiff_assoc($names, $names, function ($a, $b) { return $a > $b; })), $names, function ($a, $b) use($names) { return array_push($names, $a) === $b; })))), function ($a, $b) { return $a; })))), function ($v) { if ($v !== '' && $v !== 'Rick Astley') { return true; } return false; }))) . "!\n"; /* Step 1: separate the functions by return value scalar/array Step 2: further separate by type, and type of array Step 3: pair similar functions together Step 4: tackle the hard functions first (indicated with *)
<?php // array_udiff_assoc_diffkeys.php $week = ["Monday" => "Rāhina", "Tuesday" => "Rātū", "Wednesday" => "Rāapa", "Thursday" => "Rāpare", "Friday" => "Rāmere", "Saturday" => "Rāhoroi", "Sunday" => "Rātapu"]; $weekend = ["Samedi" => "Rāhoroi", "Dimanche" => "Rātapu"]; $weekdays = array_udiff_assoc($week, $weekend, function ($v1, $v2) { echo "{$v1}:{$v2}<br>"; if ($v1 == $v2) { return 0; } return $v1 > $v2 ? 1 : -1; }); echo "<pre>"; var_dump($weekdays); echo "</pre>";
/** * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route * @throws InvalidParameterException When a parameter value for a placeholder is not correct because * it does not match the requirement */ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array()) { if (is_bool($referenceType) || is_string($referenceType)) { @trigger_error('The hardcoded value you are using for the $referenceType argument of the ' . __CLASS__ . '::generate method is deprecated since version 2.8 and will not be supported anymore in 3.0. Use the constants defined in the UrlGeneratorInterface instead.', E_USER_DEPRECATED); if (true === $referenceType) { $referenceType = self::ABSOLUTE_URL; } elseif (false === $referenceType) { $referenceType = self::ABSOLUTE_PATH; } elseif ('relative' === $referenceType) { $referenceType = self::RELATIVE_PATH; } elseif ('network' === $referenceType) { $referenceType = self::NETWORK_PATH; } } $variables = array_flip($variables); $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters); // all params must be given if ($diff = array_diff_key($variables, $mergedParams)) { throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name)); } $url = ''; $optional = true; foreach ($tokens as $token) { if ('variable' === $token[0]) { if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) { // check requirement if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#', $mergedParams[$token[3]])) { $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]); if ($this->strictRequirements) { throw new InvalidParameterException($message); } if ($this->logger) { $this->logger->error($message); } return; } $url = $token[1] . $mergedParams[$token[3]] . $url; $optional = false; } } else { // static text $url = $token[1] . $url; $optional = false; } } if ('' === $url) { $url = '/'; } // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request) $url = strtr(rawurlencode($url), $this->decodedChars); // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3 // so we need to encode them as they are not used for this purpose here // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/')); if ('/..' === substr($url, -3)) { $url = substr($url, 0, -2) . '%2E%2E'; } elseif ('/.' === substr($url, -2)) { $url = substr($url, 0, -1) . '%2E'; } $schemeAuthority = ''; if ($host = $this->context->getHost()) { $scheme = $this->context->getScheme(); if ($requiredSchemes) { if (!in_array($scheme, $requiredSchemes, true)) { $referenceType = self::ABSOLUTE_URL; $scheme = current($requiredSchemes); } } elseif (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) { // We do this for BC; to be removed if _scheme is not supported anymore $referenceType = self::ABSOLUTE_URL; $scheme = $req; } if ($hostTokens) { $routeHost = ''; foreach ($hostTokens as $token) { if ('variable' === $token[0]) { if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#i', $mergedParams[$token[3]])) { $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]); if ($this->strictRequirements) { throw new InvalidParameterException($message); } if ($this->logger) { $this->logger->error($message); } return; } $routeHost = $token[1] . $mergedParams[$token[3]] . $routeHost; } else { $routeHost = $token[1] . $routeHost; } } if ($routeHost !== $host) { $host = $routeHost; if (self::ABSOLUTE_URL !== $referenceType) { $referenceType = self::NETWORK_PATH; } } } if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) { $port = ''; if ('http' === $scheme && 80 != $this->context->getHttpPort()) { $port = ':' . $this->context->getHttpPort(); } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) { $port = ':' . $this->context->getHttpsPort(); } $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "{$scheme}://"; $schemeAuthority .= $host . $port; } } if (self::RELATIVE_PATH === $referenceType) { $url = self::getRelativePath($this->context->getPathInfo(), $url); } else { $url = $schemeAuthority . $this->context->getBaseUrl() . $url; } // add a query string if needed $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) { return $a == $b ? 0 : 1; }); if ($extra && ($query = http_build_query($extra, '', '&'))) { // "/" and "?" can be left decoded for better user experience, see // http://tools.ietf.org/html/rfc3986#section-3.4 $url .= '?' . strtr($query, array('%2F' => '/')); } return $url; }
/** * Recursively drop back to the parents menu style * when the current menu has a parent and has no changes * * @return MenuStyle */ private function getMenuStyle() { $diff = array_udiff_assoc($this->style, $this->getStyleClassDefaults(), function ($current, $default) { if ($current instanceof TerminalInterface) { return 0; } return $current === $default ? 0 : 1; }); if (!$diff && null !== $this->parent) { return $this->parent->getMenuStyle(); } return new MenuStyle(...array_values($this->style)); }
public function getDeleteDiff() { $this->initialize(); return array_udiff_assoc($this->snapshot, $this->collection->toArray(), function ($a, $b) { return $a === $b ? 0 : 1; }); }
<?php /* Prototype : array array_udiff_assoc(array arr1, array arr2 [, array ...], callback key_comp_func) * Description: Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys are compared by user supplied function. * Source code: ext/standard/array.c * Alias to functions: */ echo "*** Testing array_udiff_assoc() : usage variation - differing comparison functions***\n"; $arr1 = array(1); $arr2 = array(1, 2); echo "\n-- comparison function with an incorrect return value --\n"; function incorrect_return_value($val1, $val2) { return array(1); } var_dump(array_udiff_assoc($arr1, $arr2, 'incorrect_return_value')); echo "\n-- comparison function taking too many parameters --\n"; function too_many_parameters($val1, $val2, $val3) { return 1; } var_dump(array_udiff_assoc($arr1, $arr2, 'too_many_parameters')); echo "\n-- comparison function taking too few parameters --\n"; function too_few_parameters($val1) { return 1; } var_dump(array_udiff_assoc($arr1, $arr2, 'too_few_parameters')); ?> ===DONE===
/** * @param ConfigInterface $config * @SuppressWarnings(PHPMD) */ public function calculateConfigChangeSet(ConfigInterface $config) { $originConfigValue = []; $configKey = $this->buildConfigKey($config->getId()); if (isset($this->originalConfigs[$configKey])) { $originConfigValue = $this->originalConfigs[$configKey]->all(); } foreach ($config->all() as $key => $value) { if (!isset($originConfigValue[$key])) { $originConfigValue[$key] = null; } } $diffNew = array_udiff_assoc($config->all(), $originConfigValue, function ($a, $b) { return $a == $b ? 0 : 1; }); $diffOld = array_udiff_assoc($originConfigValue, $config->all(), function ($a, $b) { return $a == $b ? 0 : 1; }); $diff = []; foreach ($diffNew as $key => $value) { $oldValue = isset($diffOld[$key]) ? $diffOld[$key] : null; $diff[$key] = [$oldValue, $value]; } if (!isset($this->configChangeSets[$configKey])) { $this->configChangeSets[$configKey] = []; } if (count($diff)) { $changeSet = array_merge($this->configChangeSets[$configKey], $diff); $this->configChangeSets[$configKey] = $changeSet; } }
/** * INTERNAL: * getInsertDiff * * @return array */ public function getInsertDiff() { return array_udiff_assoc($this->coll->toArray(), $this->snapshot, array(__CLASS__, 'strictDiffCompare')); }
/** * @param \Viserio\Routing\Generator\RouteTreeNode $node1 * @param \Viserio\Routing\Generator\RouteTreeNode $node2 * * @return \Viserio\Routing\Generator\RouteTreeNode|null */ protected function extractCommonParentNode(RouteTreeNode $node1, RouteTreeNode $node2) { $matcherCompare = function (SegmentMatcherContract $matcher, SegmentMatcherContract $matcher2) { return strcmp($matcher->getHash(), $matcher2->getHash()); }; $commonMatchers = array_uintersect_assoc($node1->getMatchers(), $node2->getMatchers(), $matcherCompare); if (empty($commonMatchers)) { return; } $children = []; $nodes = [$node1, $node2]; foreach ($nodes as $node) { $specificMatchers = array_udiff_assoc($node->getMatchers(), $commonMatchers, $matcherCompare); $duplicateMatchers = array_uintersect_assoc($node->getMatchers(), $commonMatchers, $matcherCompare); foreach ($duplicateMatchers as $segmentDepth => $matcher) { $commonMatchers[$segmentDepth]->mergeParameterKeys($matcher); } if (empty($specificMatchers) && $node->isParentNode()) { foreach ($node->getContents()->getChildren() as $childNode) { $children[] = $childNode; } } else { $children[] = $node->update($specificMatchers, $node->getContents()); } } return new RouteTreeNode($commonMatchers, new ChildrenNodeCollection($children)); }
public function getDirties() { $to_insert = $this->getInsertDiff(); $remaining = array_udiff_assoc($this->items, $to_insert, function ($a, $b) { return $a === $b ? 0 : 1; }); $dirties = array(); if (count($remaining) == 0) { return $dirties; } foreach ($remaining as $r) { if ($r->isChanged()) { array_push($dirties, $r); } } return $dirties; }
private function getInsertDiff($snapshot, $current) { return array_udiff_assoc($current, $snapshot, function ($a, $b) { return $a === $b ? 0 : 1; }); }
/** * Prepares update array for document, using atomic operators * * @param mixed $document * @return array */ public function prepareUpdateData($document) { if (is_array($document) && isset($document['originalObject'])) { $document = $document['originalObject']; } $oid = spl_object_hash($document); $class = $this->dm->getClassMetadata(get_class($document)); $changeset = $this->uow->getDocumentChangeSet($document); $result = array(); foreach ($class->fieldMappings as $mapping) { if (isset($mapping['notSaved']) && $mapping['notSaved'] === true) { continue; } $old = isset($changeset[$mapping['fieldName']][0]) ? $changeset[$mapping['fieldName']][0] : null; $new = isset($changeset[$mapping['fieldName']][1]) ? $changeset[$mapping['fieldName']][1] : null; if ($mapping['type'] === 'many' || $mapping['type'] === 'collection') { if ($mapping['strategy'] === 'pushPull') { if (isset($mapping['embedded']) && $new) { foreach ($new as $k => $v) { if (!isset($old[$k])) { continue; } $update = $this->prepareUpdateData($v); foreach ($update as $cmd => $values) { foreach ($values as $key => $value) { $result[$cmd][$mapping['name'] . '.' . $k . '.' . $key] = $value; } } } } if ($old !== $new) { $old = $old ? $old : array(); $new = $new ? $new : array(); $compare = function ($a, $b) { $a = is_array($a) && isset($a['originalObject']) ? $a['originalObject'] : $a; $b = is_array($b) && isset($b['originalObject']) ? $b['originalObject'] : $b; return $a === $b ? 0 : 1; }; $deleteDiff = array_udiff_assoc($old, $new, $compare); $insertDiff = array_udiff_assoc($new, $old, $compare); // insert diff if ($insertDiff) { $result[$this->cmd . 'pushAll'][$mapping['name']] = $this->prepareValue($mapping, $insertDiff); } // delete diff if ($deleteDiff) { $result[$this->cmd . 'pullAll'][$mapping['name']] = $this->prepareValue($mapping, $deleteDiff); } } } elseif ($mapping['strategy'] === 'set') { if ($old !== $new) { $new = $this->prepareValue($mapping, $new); $result[$this->cmd . 'set'][$mapping['name']] = $new; } } } else { if ($old !== $new) { if ($mapping['type'] === 'increment') { $new = $this->prepareValue($mapping, $new); $old = $this->prepareValue($mapping, $old); if ($new >= $old) { $result[$this->cmd . 'inc'][$mapping['name']] = $new - $old; } else { $result[$this->cmd . 'inc'][$mapping['name']] = ($old - $new) * -1; } } else { // Single embedded if (isset($mapping['embedded']) && $mapping['type'] === 'one') { // If we didn't have a value before and now we do if (!$old && $new) { $new = $this->prepareValue($mapping, $new); if (isset($new) || $mapping['nullable'] === true) { $result[$this->cmd . 'set'][$mapping['name']] = $new; } // If we had an old value before and it has changed } elseif ($old && $new) { $embeddedDocument = $class->getFieldValue($document, $mapping['fieldName']); $update = $this->prepareUpdateData($embeddedDocument); foreach ($update as $cmd => $values) { foreach ($values as $key => $value) { $result[$cmd][$mapping['name'] . '.' . $key] = $value; } } } // $set all other fields } else { $new = $this->prepareValue($mapping, $new); if (isset($new) || $mapping['nullable'] === true) { $result[$this->cmd . 'set'][$mapping['name']] = $new; } else { $result[$this->cmd . 'unset'][$mapping['name']] = true; } } } } } } return $result; }
/** * (PHP 5)<br/> * Computes the difference of arrays with additional index check, compares data by a callback function * @link http://php.net/manual/en/function.array-udiff-assoc.php * @param array $array2 <p> * The second array. * </p> * @param array $_ [optional] * @param callable $value_compare_func <p> * The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. * </p> * int<b>callback</b><b>mixed<i>a</i></b><b>mixed<i>b</i></b> * @return array <b>array_udiff_assoc</b> returns an array * containing all the values from <i>array1</i> * that are not present in any of the other arguments. * Note that the keys are used in the comparison unlike * <b>array_diff</b> and <b>array_udiff</b>. * The comparison of arrays' data is performed by using an user-supplied * callback. In this aspect the behaviour is opposite to the behaviour of * <b>array_diff_assoc</b> which uses internal function for * comparison. */ public function udiff_assoc(array $array2, array $_ = null, callable $value_compare_func) { // TODO: use func_get_args() for multiple arguments, like Arr($array)->function($v1, $v2, $v3) return array_udiff_assoc($this->array, $array2, $value_compare_func); }
/** * Update authentication configuration * * @param array $authenticationConfig * @return AuthenticationEntity */ public function update(array $authenticationConfig) { $current = $this->fetch(); if (!$current instanceof AuthenticationEntity) { return $this->create($authenticationConfig); } $current->exchangeArray($authenticationConfig); if ($current->isOAuth2()) { $data = $current->getArrayCopy(); $dsnType = isset($data['dsn_type']) ? $data['dsn_type'] : AuthenticationEntity::DSN_PDO; $this->validateDsn($data['dsn'], $data['username'], $data['password'], $dsnType); } $allData = $current->getArrayCopy(); unset($allData['type']); $global = $this->removeSensitiveConfig($allData); $local = array_udiff_assoc($allData, $global, sprintf('%s::arrayDiffRecursive', __CLASS__)); switch (true) { case $current->isBasic(): case $current->isDigest(): $this->patchHttpAuthConfig($current, $global, $local); break; case $current->isOAuth2(): $this->patchOAuth2Config($current, $global, $local); break; } return $current; }
/** * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route * @throws InvalidParameterException When a parameter value for a placeholder is not correct because * it does not match the requirement */ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array()) { $variables = array_flip($variables); $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters); // all params must be given if ($diff = array_diff_key($variables, $mergedParams)) { throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name)); } $url = ''; $optional = true; $message = 'Parameter "{parameter}" for route "{route}" must match "{expected}" ("{given}" given) to generate a corresponding URL.'; foreach ($tokens as $token) { if ('variable' === $token[0]) { if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) { // check requirement if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#' . (empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) { if ($this->strictRequirements) { throw new InvalidParameterException(strtr($message, array('{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]]))); } if ($this->logger) { $this->logger->error($message, array('parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]])); } return; } $url = $token[1] . $mergedParams[$token[3]] . $url; $optional = false; } } else { // static text $url = $token[1] . $url; $optional = false; } } if ('' === $url) { $url = '/'; } // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request) $url = strtr(rawurlencode($url), $this->decodedChars); // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3 // so we need to encode them as they are not used for this purpose here // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/')); if ('/..' === substr($url, -3)) { $url = substr($url, 0, -2) . '%2E%2E'; } elseif ('/.' === substr($url, -2)) { $url = substr($url, 0, -1) . '%2E'; } $schemeAuthority = ''; if ($host = $this->context->getHost()) { $scheme = $this->context->getScheme(); if ($requiredSchemes) { if (!in_array($scheme, $requiredSchemes, true)) { $referenceType = self::ABSOLUTE_URL; $scheme = current($requiredSchemes); } } if ($hostTokens) { $routeHost = ''; foreach ($hostTokens as $token) { if ('variable' === $token[0]) { if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#i' . (empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) { if ($this->strictRequirements) { throw new InvalidParameterException(strtr($message, array('{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]]))); } if ($this->logger) { $this->logger->error($message, array('parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]])); } return; } $routeHost = $token[1] . $mergedParams[$token[3]] . $routeHost; } else { $routeHost = $token[1] . $routeHost; } } if ($routeHost !== $host) { $host = $routeHost; if (self::ABSOLUTE_URL !== $referenceType) { $referenceType = self::NETWORK_PATH; } } } if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) { $port = ''; if ('http' === $scheme && 80 != $this->context->getHttpPort()) { $port = ':' . $this->context->getHttpPort(); } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) { $port = ':' . $this->context->getHttpsPort(); } $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "{$scheme}://"; $schemeAuthority .= $host . $port; } } if (self::RELATIVE_PATH === $referenceType) { $url = self::getRelativePath($this->context->getPathInfo(), $url); } else { $url = $schemeAuthority . $this->context->getBaseUrl() . $url; } // add a query string if needed $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) { return $a == $b ? 0 : 1; }); // extract fragment $fragment = ''; if (isset($defaults['_fragment'])) { $fragment = $defaults['_fragment']; } if (isset($extra['_fragment'])) { $fragment = $extra['_fragment']; unset($extra['_fragment']); } if ($extra && ($query = http_build_query($extra, '', '&', PHP_QUERY_RFC3986))) { // "/" and "?" can be left decoded for better user experience, see // http://tools.ietf.org/html/rfc3986#section-3.4 $url .= '?' . strtr($query, array('%2F' => '/')); } if ('' !== $fragment) { $url .= '#' . strtr(rawurlencode($fragment), $this->decodedFragmentChars); } return $url; }
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array()) { $variables = array_flip($variables); $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters); if ($diff = array_diff_key($variables, $mergedParams)) { throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name)); } $url = ''; $optional = true; $message = 'Parameter "{parameter}" for route "{route}" must match "{expected}" ("{given}" given) to generate a corresponding URL.'; foreach ($tokens as $token) { if ('variable' === $token[0]) { if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) { if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#' . (empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) { if ($this->strictRequirements) { throw new InvalidParameterException(strtr($message, array('{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]]))); } if ($this->logger) { $this->logger->error($message, array('parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]])); } return; } $url = $token[1] . $mergedParams[$token[3]] . $url; $optional = false; } } else { $url = $token[1] . $url; $optional = false; } } if ('' === $url) { $url = '/'; } $url = strtr(rawurlencode($url), $this->decodedChars); $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/')); if ('/..' === substr($url, -3)) { $url = substr($url, 0, -2) . '%2E%2E'; } elseif ('/.' === substr($url, -2)) { $url = substr($url, 0, -1) . '%2E'; } $schemeAuthority = ''; if ($host = $this->context->getHost()) { $scheme = $this->context->getScheme(); if ($requiredSchemes) { if (!in_array($scheme, $requiredSchemes, true)) { $referenceType = self::ABSOLUTE_URL; $scheme = current($requiredSchemes); } } if ($hostTokens) { $routeHost = ''; foreach ($hostTokens as $token) { if ('variable' === $token[0]) { if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#i' . (empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) { if ($this->strictRequirements) { throw new InvalidParameterException(strtr($message, array('{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]]))); } if ($this->logger) { $this->logger->error($message, array('parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]])); } return; } $routeHost = $token[1] . $mergedParams[$token[3]] . $routeHost; } else { $routeHost = $token[1] . $routeHost; } } if ($routeHost !== $host) { $host = $routeHost; if (self::ABSOLUTE_URL !== $referenceType) { $referenceType = self::NETWORK_PATH; } } } if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) { $port = ''; if ('http' === $scheme && 80 != $this->context->getHttpPort()) { $port = ':' . $this->context->getHttpPort(); } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) { $port = ':' . $this->context->getHttpsPort(); } $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "{$scheme}://"; $schemeAuthority .= $host . $port; } } if (self::RELATIVE_PATH === $referenceType) { $url = self::getRelativePath($this->context->getPathInfo(), $url); } else { $url = $schemeAuthority . $this->context->getBaseUrl() . $url; } $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) { return $a == $b ? 0 : 1; }); $fragment = ''; if (isset($defaults['_fragment'])) { $fragment = $defaults['_fragment']; } if (isset($extra['_fragment'])) { $fragment = $extra['_fragment']; unset($extra['_fragment']); } if ($extra && ($query = http_build_query($extra, '', '&', PHP_QUERY_RFC3986))) { $url .= '?' . strtr($query, array('%2F' => '/')); } if ('' !== $fragment) { $url .= '#' . strtr(rawurlencode($fragment), array('%2F' => '/', '%3F' => '?')); } return $url; }
/** * Generates the changes between two address format collections. */ function generate_address_format_changes($oldAddressFormats, $newAddressFormats) { $changes = ['date' => date('c'), 'added' => array_keys(array_diff_key($newAddressFormats, $oldAddressFormats)), 'removed' => array_keys(array_diff_key($oldAddressFormats, $newAddressFormats)), 'modified' => array_keys(array_udiff_assoc(array_intersect_key($newAddressFormats, $oldAddressFormats), array_intersect_key($oldAddressFormats, $newAddressFormats), 'compare_arrays'))]; return $changes; }
/** * Compare arrays and return difference, such that: * * $modified = array_merge($original, $difference); * * @param array $original original array * @param array $modified modified array * @return array differences between original and modified */ public function array_unmerge($original, $modified) { // return key/value pairs for keys in $modified but not in $original // return key/value pairs for keys in both $modified and $original, but values differ // ignore keys that are in $original but not in $modified return array_udiff_assoc($modified, $original, array(__CLASS__, 'compareElements')); }
echo '$b='.var_export($b,TRUE).";\n"; echo '$c='.var_export($c,TRUE).";\n"; var_dump(array_diff($a,$b,$c)); var_dump(array_diff_assoc($a,$b,$c)); var_dump(array_udiff($a, $b, $c, "comp_func")); var_dump(array_diff_uassoc($a,$b,$c, "comp_func")); */ /* $a = array(new cr(9),new cr(12),new cr(23),new cr(4),new cr(-15),); $b = array(new cr(9),new cr(22),new cr( 3),new cr(4),new cr(-15),); var_dump(array_udiff($a, $b, "comp_func_cr")); */ $a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1 => new cr(4), 2 => new cr(-15)); $b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1 => new cr(4), 2 => new cr(-15)); echo '$a=' . var_export($a, TRUE) . ";\n"; echo '$b=' . var_export($b, TRUE) . ";\n"; echo 'var_dump(array_udiff_uassoc($a, $b, "comp_func_cr", "comp_func"));' . "\n"; var_dump(array_udiff_uassoc($a, $b, "comp_func_cr", "comp_func")); echo '$a=' . var_export($a, TRUE) . ";\n"; echo '$b=' . var_export($b, TRUE) . ";\n"; echo 'var_dump(array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), "comp_func"));' . "\n"; var_dump(array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), "comp_func")); echo '$a=' . var_export($a, TRUE) . ";\n"; echo '$b=' . var_export($b, TRUE) . ";\n"; echo 'var_dump(array_udiff($a, $b, "comp_func_cr"));' . "\n"; var_dump(array_udiff($a, $b, "comp_func_cr")); echo '$a=' . var_export($a, TRUE) . ";\n"; echo '$b=' . var_export($b, TRUE) . ";\n"; echo 'var_dump(array_udiff_assoc($a, $b, "comp_func_cr"));' . "\n"; var_dump(array_udiff_assoc($a, $b, "comp_func_cr"));
<?php /* * proto array array_udiff_assoc ( array $array1, array $array2 [, array $ ..., callback $data_compare_func] ) * Function is implemented in ext/standard/array.c */ class cr { private $priv_member; function __construct($val) { $this->priv_member = $val; } static function comp_func_cr($a, $b) { if ($a->priv_member === $b->priv_member) { return 0; } return $a->priv_member > $b->priv_member ? 1 : -1; } } $a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1 => new cr(4), 2 => new cr(-15)); $b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1 => new cr(4), 2 => new cr(-15)); $result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr")); var_dump($result);
/** * @param ConfigInterface $config * @SuppressWarnings(PHPMD) */ public function calculateConfigChangeSet(ConfigInterface $config) { $originConfigValue = array(); if ($this->originalConfigs->containsKey($config->getId()->toString())) { $originConfig = $this->originalConfigs->get($config->getId()->toString()); $originConfigValue = $originConfig->all(); } foreach ($config->all() as $key => $value) { if (!isset($originConfigValue[$key])) { $originConfigValue[$key] = null; } } $diffNew = array_udiff_assoc($config->all(), $originConfigValue, function ($a, $b) { return $a == $b ? 0 : 1; }); $diffOld = array_udiff_assoc($originConfigValue, $config->all(), function ($a, $b) { return $a == $b ? 0 : 1; }); $diff = array(); foreach ($diffNew as $key => $value) { $oldValue = isset($diffOld[$key]) ? $diffOld[$key] : null; $diff[$key] = array($oldValue, $value); } if (!$this->configChangeSets->containsKey($config->getId()->toString())) { $this->configChangeSets->set($config->getId()->toString(), array()); } if (count($diff)) { $changeSet = array_merge($this->configChangeSets->get($config->getId()->toString()), $diff); $this->configChangeSets->set($config->getId()->toString(), $changeSet); } }
//get an unset variable $unset_var = 10; unset($unset_var); // define some classes class classWithToString { public function __toString() { return "Class A object"; } } class classWithoutToString { } // heredoc string $heredoc = <<<EOT hello world EOT; // add arrays $index_array = array(1, 2, 3); $assoc_array = array('one' => 1, 'two' => 2); //array of values to iterate over $inputs = array('int 0' => 0, 'int 1' => 1, 'int 12345' => 12345, 'int -12345' => -2345, 'float 10.5' => 10.5, 'float -10.5' => -10.5, 'float 12.3456789000e10' => 123456789000.0, 'float -12.3456789000e10' => -123456789000.0, 'float .5' => 0.5, 'empty array' => array(), 'int indexed array' => $index_array, 'associative array' => $assoc_array, 'nested arrays' => array('foo', $index_array, $assoc_array), 'uppercase NULL' => NULL, 'lowercase null' => null, 'lowercase true' => true, 'lowercase false' => false, 'uppercase TRUE' => TRUE, 'uppercase FALSE' => FALSE, 'empty string DQ' => "", 'empty string SQ' => '', 'string DQ' => "string", 'string SQ' => 'string', 'mixed case string' => "sTrInG", 'heredoc' => $heredoc, 'instance of classWithToString' => new classWithToString(), 'instance of classWithoutToString' => new classWithoutToString(), 'undefined var' => @$undefined_var, 'unset var' => @$unset_var); // loop through each element of the array for key_comp_func foreach ($inputs as $key => $value) { echo "\n--{$key}--\n"; var_dump(array_udiff_assoc($arr1, $arr2, $value)); } ?> ===DONE===
//get an unset variable $unset_var = 10; unset($unset_var); // define some classes class classWithToString { public function __toString() { return "Class A object"; } } class classWithoutToString { } // heredoc string $heredoc = <<<EOT hello world EOT; // add arrays $index_array = array(1, 2, 3); $assoc_array = array('one' => 1, 'two' => 2); //array of values to iterate over $inputs = array('int 0' => 0, 'int 1' => 1, 'int 12345' => 12345, 'int -12345' => -2345, 'float 10.5' => 10.5, 'float -10.5' => -10.5, 'float 12.3456789000e10' => 123456789000.0, 'float -12.3456789000e10' => -123456789000.0, 'float .5' => 0.5, 'uppercase NULL' => NULL, 'lowercase null' => null, 'lowercase true' => true, 'lowercase false' => false, 'uppercase TRUE' => TRUE, 'uppercase FALSE' => FALSE, 'empty string DQ' => "", 'empty string SQ' => '', 'string DQ' => "string", 'string SQ' => 'string', 'mixed case string' => "sTrInG", 'heredoc' => $heredoc, 'instance of classWithToString' => new classWithToString(), 'instance of classWithoutToString' => new classWithoutToString(), 'undefined var' => @$undefined_var, 'unset var' => @$unset_var); // loop through each element of the array for arr1 foreach ($inputs as $key => $value) { echo "\n--{$key}--\n"; var_dump(array_udiff_assoc($value, $arr2, $key_comp_func)); } ?> ===DONE===
/** * INTERNAL: * getInsertDiff * * @return array */ public function getInsertDiff() { return array_udiff_assoc($this->coll->toArray(), $this->snapshot, function ($a, $b) { return $a === $b ? 0 : 1; }); }
<?php /* Prototype : array array_udiff_assoc(array arr1, array arr2 [, array ...], callback key_comp_func) * Description: Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys are compared by user supplied function. * Source code: ext/standard/array.c * Alias to functions: */ echo "*** Testing array_udiff_assoc() : error conditions ***\n"; $arr1 = array(1, 2); $arr2 = array(1, 2); $extra_arg = 10; include 'compare_function.inc'; $key_comp_func = 'compare_function'; //Test array_udiff_assoc with one more than the expected number of arguments echo "\n-- Testing array_udiff_assoc() function with more than expected no. of arguments --\n"; var_dump(array_udiff_assoc($arr1, $arr2, $key_comp_func, $extra_arg)); // Testing array_udiff_assoc with one less than the expected number of arguments echo "\n-- Testing array_udiff_assoc() function with less than expected no. of arguments --\n"; var_dump(array_udiff_assoc($arr1, $arr2)); ?> ===DONE===