A sequence of values indexed by keys, which supports various operations: generation, projection, filtering, ordering, joining, grouping, aggregation etc.

To create a Enumerable, call {@link Enumerable::from} (aliased as a global function {@link from}) or any of the generation functions. To convert to array, call {@link Enumerable::toArrayDeep} or any of the conversion functions.

Internally, it is a wrapper around a lazily created iterator. The wrapped iterator is evaluated when {@link getIterator} is called.

See also: from
Inheritance: implements IteratorAggregate, use trait EnumerableGeneration, use trait EnumerablePagination
Beispiel #1
0
 /** @inheritdoc */
 public function clean($validPackages)
 {
     foreach (Linq::from($this->filesystem->listContents($this->vendorDir))->where(function ($v) {
         return $v['type'] == 'dir';
     }) as $vendor) {
         if (!Linq::from($validPackages)->any(function ($v, $k) use($vendor) {
             return preg_match('/^' . $vendor['basename'] . '/i', $k);
         })) {
             $this->notify("DELETING: " . $vendor['path'] . "\n");
             $this->filesystem->deleteDir($vendor['path']);
             continue;
         }
         foreach (Linq::from($this->filesystem->listContents($vendor['path']))->where(function ($v) {
             return $v['type'] == 'dir';
         }) as $package) {
             if (!Linq::from($validPackages)->any(function ($v, $k) use($vendor, $package) {
                 return $k == $vendor['basename'] . '/' . $package['basename'];
             })) {
                 $this->notify("DELETING: " . $package['path'] . "\n");
                 $this->filesystem->deleteDir($package['path']);
                 continue;
             }
             foreach (Linq::from($this->filesystem->listContents($package['path']))->where(function ($v) {
                 return $v['type'] == 'dir';
             }) as $version) {
                 if (!Linq::from($validPackages[$vendor['basename'] . '/' . $package['basename']])->any(function ($v) use($version) {
                     return $v == $version['basename'];
                 })) {
                     $this->notify("DELETING: " . $version['path'] . "\n");
                     $this->filesystem->deleteDir($version['path']);
                 }
             }
         }
     }
 }
Beispiel #2
0
 /**
  * Finds all theme route files and adds the routes to the RouteCollection.
  *
  * @return void
  */
 private function discoverRoutes()
 {
     // Where are our routes located?
     $parentRoutes = $this->config->paths->theme->parent->routes;
     $childRoutes = $this->config->paths->theme->child->routes;
     $files = $this->finder->createFinder()->files()->name('*.php')->in($parentRoutes);
     if ($parentRoutes != $childRoutes && is_dir($childRoutes)) {
         $files = $files->in($childRoutes);
     }
     // Collect all the files
     $splFiles = [];
     foreach ($files as $file) {
         $splFiles[] = $file;
     }
     // Now we need to sort them ourselves because it seems Finder's
     // sortByName(), only sorts per in('dir') and not across the
     // entire list.
     $orderedFiles = Linq::from($splFiles)->orderBy('$v', function ($a, $b) {
         return strnatcasecmp($a->getBasename('.php'), $b->getBasename('.php'));
     });
     // Finally lets add some routes.
     foreach ($orderedFiles as $file) {
         $route = import($file->getRealPath(), ['route' => $this->routes]);
         if (is_callable($route)) {
             $this->container->call($route, ['config' => $this->config]);
         }
     }
 }
Beispiel #3
0
 /** {@inheritdoc} */
 public function getIterator()
 {
     $canMultisort = $this->sortFlags !== null;
     $array = $this->source->tryGetArrayCopy();
     $it = $this->trySortBySingleField($array, $canMultisort);
     if ($it !== null) {
         return $it;
     }
     return $this->sortByMultipleFields($array, $canMultisort);
 }
 /**
  * @param $organisation
  * @return array
  */
 private function getStatistics($organisation)
 {
     $httpClient = new CachedHttpClient();
     $githubClient = new GithubAPI($httpClient);
     $packagistClient = new PackagistApi();
     $oregon = new Oregon($organisation, $githubClient, $packagistClient);
     $contributors = $oregon->getContributors();
     $repositories = $githubClient->api('organization')->repositories($organisation);
     $downloads = $oregon->getDownloads();
     $statistics = array('contributions' => Enumerable::from($contributors)->sum('$v["contributions"]'), 'contributors' => count($contributors), 'forks' => Enumerable::from($repositories)->sum('$v["forks_count"]'), 'watchers' => Enumerable::from($repositories)->sum('$v["watchers_count"]'), 'downloadstotal' => $downloads->getTotal(), 'downloadsmonthly' => $downloads->getMonthly());
     return $statistics;
 }
Beispiel #5
0
    /**
     * Index Page action for this controller.
     *
     * Maps to the following URL
     * 		/index.php/admin/skills
     */
    public function index()
    {
        $skillCategories = $this->Categories_model->get_categories();
        $skills = $this->Portfolios_model->get_portfolios();
        $skillsByCategory = Enumerable::from($skillCategories)->orderBy('$cat ==> $cat["name"]')->groupJoin(from($skills)->orderBy('$skill ==> $skill["name"]'), '$cat ==> $cat["id"]', '$skill ==> $skill["categoryId"]', '($cat, $sks) ==> array(
	            "name" => $cat["name"],
	            "skills" => $sks
	        )');
        $this->view_bag['skillsByCategory'] = $skillsByCategory;
        $this->view_bag['title'] = 'Skills';
        $this->template->load(ADMIN_TEMPLATE_NAME, 'admin/skills/index', $this->view_bag);
    }
Beispiel #6
0
 public function getDownloads()
 {
     $downloads = new Downloads();
     $packagist = $this->packagist;
     $packages = $this->packagist->all(array('vendor' => $this->organization));
     $downloads->setTotal(Enumerable::from($packages)->sum(function ($package) use($packagist) {
         return $packagist->get($package)->getDownloads()->getTotal();
     }));
     $downloads->setMonthly(Enumerable::from($packages)->sum(function ($package) use($packagist) {
         return $packagist->get($package)->getDownloads()->getMonthly();
     }));
     $downloads->setDaily(Enumerable::from($packages)->sum(function ($package) use($packagist) {
         return $packagist->get($package)->getDownloads()->getDaily();
     }));
     return $downloads;
 }
 /** {@inheritdoc} */
 public function getIterator()
 {
     $orders = [];
     for ($order = $this; $order != null; $order = $order->parent) {
         $orders[] = $order;
     }
     $orders = array_reverse($orders);
     $map = $this->source->select(function ($v, $k) {
         return ['v' => $v, 'k' => $k];
     })->toList();
     $comparers = [];
     for ($i = 0; $i < count($orders); ++$i) {
         $order = $orders[$i];
         $comparer = $order->comparer;
         if ($order->desc) {
             $comparer = function ($a, $b) use($comparer) {
                 return -$comparer($a, $b);
             };
         }
         $comparers[] = $comparer;
         for ($j = 0; $j < count($map); ++$j) {
             $keySelector = $order->keySelector;
             $map[$j][] = $keySelector($map[$j]['v'], $map[$j]['k']);
         }
     }
     usort($map, function ($a, $b) use($comparers) {
         for ($i = 0; $i < count($comparers); ++$i) {
             $diff = $comparers[$i]($a[$i], $b[$i]);
             if ($diff != 0) {
                 return $diff;
             }
         }
         return 0;
     });
     return Enumerable::from($map)->select(function ($v) {
         return $v['v'];
     }, function ($v) {
         return $v['k'];
     })->getIterator();
 }
Beispiel #8
0
 /** @inheritdoc */
 public function extract($zipBallPath, $to)
 {
     $absolutePathToZipBall = $this->filesystem->getAdapter()->applyPathPrefix($zipBallPath);
     if ($this->zip->open($absolutePathToZipBall) === true) {
         $absolutePathToExtract = $this->filesystem->getAdapter()->applyPathPrefix($to);
         $this->zip->extractTo($absolutePathToExtract);
         $this->zip->close();
         $zipCreatedFolder = Linq::from($this->filesystem->listContents($to))->single(function ($object) {
             return $object['type'] == 'dir';
         })['path'];
         foreach ($this->filesystem->listContents($zipCreatedFolder, true) as $object) {
             if ($object['type'] == "file") {
                 $segments = explode('/', $object['path']);
                 unset($segments[4]);
                 $this->filesystem->rename($object['path'], implode('/', $segments));
             }
         }
         $this->filesystem->deleteDir($zipCreatedFolder);
         return;
     }
     throw new ZipExtractionFailed($zipBall, $to);
 }
Beispiel #9
0
 /**
  * <p><b>Syntax</b>: groupJoin (inner [, outerKeySelector {{(v, k) ==> key} [, innerKeySelector {{(v, k) ==> key} [, resultSelectorValue {{(v, e, k) ==> value} [, resultSelectorKey {{(v, e, k) ==> key}]]]])
  * <p>Correlates the elements of two sequences based on equality of keys and groups the results.
  * <p>GroupJoin produces hierarchical results, which means that elements from outer are paired with collections of matching elements from inner. GroupJoin enables you to base your results on a whole set of matches for each element of outer. If there are no correlated elements in inner for a given element of outer, the sequence of matches for that element will be empty but will still appear in the results.
  * <p>The resultSelectorValue and resultSelectorKey functions are called only one time for each outer element together with a collection of all the inner elements that match the outer element. This differs from the {@link join} method, in which the result selector function is invoked on pairs that contain one element from outer and one element from inner. GroupJoin preserves the order of the elements of outer, and for each element of outer, the order of the matching elements from inner.
  * <p>GroupJoin has no direct equivalent in traditional relational database terms. However, this method does implement a superset of inner joins and left outer joins. Both of these operations can be written in terms of a grouped join.
  * @param array|\Iterator|\IteratorAggregate|Enumerable $inner The second (inner) sequence to join to the first (source, outer) sequence.
  * @param callable|null $outerKeySelector {(v, k) ==> key} A function to extract the join key from each element of the first sequence. Default: key.
  * @param callable|null $innerKeySelector {(v, k) ==> key} A function to extract the join key from each element of the second sequence. Default: key.
  * @param callable|null $resultSelectorValue {(v, e, k) ==> value} A function to create a result value from an element from the first sequence and a collection of matching elements from the second sequence. Default: {(v, e, k) ==> array(v, e)}.
  * @param callable|null $resultSelectorKey {(v, e, k) ==> key} A function to create a result key from an element from the first sequence and a collection of matching elements from the second sequence. Default: {(v, e, k) ==> k} (keys returned by outerKeySelector and innerKeySelector functions).
  * @return Enumerable A sequence that contains elements that are obtained by performing a grouped join on two sequences.
  */
 public function groupJoin($inner, $outerKeySelector = null, $innerKeySelector = null, $resultSelectorValue = null, $resultSelectorKey = null)
 {
     $self = $this;
     $inner = self::from($inner);
     $outerKeySelector = Utils::createLambda($outerKeySelector, 'v,k', Functions::$key);
     $innerKeySelector = Utils::createLambda($innerKeySelector, 'v,k', Functions::$key);
     /** @noinspection PhpUnusedParameterInspection */
     $resultSelectorValue = Utils::createLambda($resultSelectorValue, 'v,e,k', function ($v, $e, $k) {
         return array($v, $e);
     });
     /** @noinspection PhpUnusedParameterInspection */
     $resultSelectorKey = Utils::createLambda($resultSelectorKey, 'v,e,k', function ($v, $e, $k) {
         return $k;
     });
     return new Enumerable(function () use($self, $inner, $outerKeySelector, $innerKeySelector, $resultSelectorValue, $resultSelectorKey) {
         /** @var $self Enumerable */
         /** @var $inner Enumerable */
         $it = $self->getIterator();
         $it->rewind();
         $lookup = $inner->toLookup($innerKeySelector);
         return new Enumerator(function ($yield) use($it, $lookup, $outerKeySelector, $resultSelectorValue, $resultSelectorKey) {
             /** @var $it \Iterator */
             /** @var $lookup \YaLinqo\collections\Lookup */
             if (!$it->valid()) {
                 return false;
             }
             $key = call_user_func($outerKeySelector, $it->current(), $it->key());
             $args = array($it->current(), Enumerable::from($lookup[$key]), $key);
             $yield(call_user_func_array($resultSelectorValue, $args), call_user_func_array($resultSelectorKey, $args));
             $it->next();
             return true;
         });
     });
 }
         return $a["Date"] == $iItem["date"];
     })->singleOrDefault();
     $patchedItem = patch($iItem, $dbItem, array("date" => "Date", "name" => "Name"));
     if ($patchedItem) {
         if (!$dbItem) {
             $database->insert("EventConferenceDay", $patchedItem);
         } else {
             $database->update("EventConferenceDay", $patchedItem, "Id=%s", $dbItem["Id"]);
         }
     }
 });
 $dbConferenceDays = Enumerable::from($database->query("SELECT * FROM EventConferenceDay WHERE IsDeleted = 0"));
 /* Events */
 Log::info("Importing Events");
 $dbEntries = Enumerable::from($database->query("SELECT * FROM EventEntry WHERE IsDeleted = 0"));
 $importEntries = Enumerable::from($eventQuery->toList());
 $dbEntries->each(function ($dbItem) use($importEntries, $database) {
     $importEntry = $importEntries->where('$v["event_id"] == ' . $dbItem["SourceEventId"])->singleOrDefault();
     if (!$importEntry) {
         Log::info("Deleting event " . $dbItem["Slug"]);
         $database->update("EventEntry", array("LastChangeDateTimeUtc" => $database->sqleval("utc_timestamp()"), "IsDeleted" => 1), "Id=%s", $dbItem["Id"]);
     }
 });
 $importEntries->each(function ($iItem) use($dbEntries, $database, $dbConferenceTracks, $dbConferenceDays, $dbConferenceRooms) {
     $dbItem = $dbEntries->where(function ($a) use($iItem) {
         return $a["SourceEventId"] == $iItem["event_id"];
     })->singleOrDefault();
     $iItem["conference_day_name"] = fixConferenceDayName($iItem["conference_day_name"]);
     $conferenceTrack = $dbConferenceTracks->where(function ($a) use($iItem) {
         return $a["Name"] == $iItem["conference_track"];
     })->singleOrDefault();
Beispiel #11
0
 /**
  * Given an array of mappings we will return a list of php src files.
  *
  * @param  array $mappings
  * @return array
  */
 private function getFilesFromMap($package, $version, $mappings)
 {
     $paths = [];
     $basePath = $this->vendorDir . '/' . $package . '/' . $version;
     foreach ($mappings as $ns => $mapping) {
         // Handle an exact file
         if (s($mapping)->endsWith('.php')) {
             $paths[] = $mapping;
             continue;
         }
         $files = $this->filesystem->listContents($basePath . '/' . $mapping, true);
         $query = Linq::from($files)->where(function ($v) {
             return $v['type'] == 'file';
         })->where(function ($v) {
             return isset($v['extension']);
         })->where(function ($v) {
             return $v['extension'] == 'php';
         })->select(function ($v) use($basePath) {
             return str_replace($basePath . '/', '', $v['path']);
         })->where(function ($v) {
             foreach ($this->excludes as $regex) {
                 if (preg_match($regex, $v)) {
                     return false;
                 }
             }
             return true;
         })->toArray();
         if (is_int($ns)) {
             // Handle a classmap
             $paths = array_merge($paths, $query);
         } else {
             // Handle a PSR-0/4 map
             // We save the namespace for later use.
             if (!isset($paths[$ns])) {
                 $paths[$ns] = [];
             }
             $paths[$ns] = array_merge($paths[$ns], $query);
         }
     }
     return $paths;
 }
Beispiel #12
0
}, array(1, 1), function ($v) {
    return $v[1];
}, 1)->toKeys()->take(10)->toArray());
var_dump(Enumerable::generate(function ($v, $k) {
    return pow(-1, $k) / (2 * $k + 1);
}, 0)->take(1000)->sum() * 4);
var_dump(Enumerable::toInfinity()->take(999)->sum(function ($k) {
    return pow(-1, $k) / (2 * $k + 1);
}) * 4);
echo "Lambdas\n";
var_dump(from(array(1, 2, 3, 4, 5, 6))->where('$v ==> $v > 3')->select('$v ==> $v*$v')->toArray());
var_dump(from(array(1, 2, 3, 4, 5, 6))->where('($v) ==> $v > 3')->select('$v, $k ==> $v+$k')->toArray());
var_dump(from(array(1, 2, 3, 4, 5, 6))->where('($v) ==> { echo $v; return $v > 3; }')->select('($v, $k) ==> { return $v*2+$k*3; }')->toArray());
var_dump(from(array(1, 2, 3, 4, 5, 6))->where('$v > 2')->where('$v>3')->select('$v+$k')->toArray());
var_dump(Enumerable::split('1 2 3 4 5 6', '# #')->toArray());
var_dump(Enumerable::matches('1 2 3 4 5 6', '#\\d+#')->select('$v[0]')->maxBy(Functions::$compareStrict));
var_dump(from(array(1, 2))->selectMany('$v ==> array(1, 2)', '"$v1 $v2"', '"$k1 $k2"')->toArray());
var_dump(from(array(1, 2))->selectMany('$v ==> array(1, 2)', '"$k1=$v1 $k2=$v2"')->toArray());
var_dump(from(array(1, 2))->selectMany('$v ==> array(1, 2)', 'array($v1, $v2)')->toArray());
var_dump(from(array(1, 2))->selectMany('$v ==> array()', '"$v1 $v2"', '"$k1 $k2"')->toArray());
var_dump(from(array())->selectMany('$v ==> array(1, 2)', '"$v1 $v2"', '"$k1 $k2"')->toArray());
var_dump(from(array('a' => array(1, 2), 'b' => array(3)))->selectMany('$v')->toArray());
var_dump(from(array(array(1, 3, 4), array(2, 1, 4), array(2, 1, 1), array(2, 3, 1), array(1, 3, 1), array(1, 1, 1)))->orderBy('$v[0]')->thenBy('$v[1]')->thenByDescending('$v[2]')->select('implode(" ", $v)')->toList());
var_dump(from(array(1, 1, 1, 2, 2, 3))->select('$v', '$v')->toLookup());
var_dump(from(array('a' => 1, 'b' => 2))->toObject());
var_dump(from(array('a', 'b', 'c', 10 => 'z'))->join(array('d', 'e', 10 => 'y', 11 => 'x'))->toArray());
var_dump(from(array(array('id' => 10, 'name' => 'cat1'), array('id' => 11, 'name' => 'cat2'), array('id' => 12, 'name' => 'cat3')))->join(array(array('name' => 'prod1', 'catId' => 10), array('name' => 'prod2', 'catId' => 10), array('name' => 'prod3', 'catId' => 11), array('name' => 'prod4', 'catId' => 13)), '$v["id"]', '$v["catId"]', function ($cat, $prod) {
    return "prod {$prod['name']} from {$cat['name']}";
})->toLookup()->toArray());
var_dump(from(array('a', 'b', 'c', 10 => 'z'))->groupJoin(array('d', 'e', 10 => 'y', 11 => 'x'), null, null, 'array($v, $e->toArray())')->toArray());
var_dump(from(array(array('id' => 10, 'name' => 'cat1'), array('id' => 11, 'name' => 'cat2'), array('id' => 12, 'name' => 'cat3')))->groupJoin(array(array('name' => 'prod1', 'catId' => 10), array('name' => 'prod2', 'catId' => 10), array('name' => 'prod3', 'catId' => 11), array('name' => 'prod4', 'catId' => 13)), '$v["id"]', '$v["catId"]', function ($cat, $prods) {
Beispiel #13
0
 public static function assertEnumValuesEquals(array $expected, E $actual, $maxLength = PHP_INT_MAX)
 {
     self::assertEquals($expected, $actual->take($maxLength)->toValues()->toArrayDeep());
 }
Beispiel #14
0
 /**
  * Filters our all development, alpha, beta & rc versions.
  *
  * @param  array $versions
  * @return array
  */
 private function filterRc($versions)
 {
     return array_values(Linq::from($versions)->where(function ($v) {
         return !preg_match("/dev|alpha|beta|rc/i", $v);
     })->toArray());
 }
Beispiel #15
0
 private function buildClass($replacement)
 {
     $type = $this->splitNsandClass($replacement['originalFullyQualifiedType']);
     $class = new ClassGenerator();
     $class->setName($type['class']);
     $class->setNamespaceName($type['ns']);
     $class->setExtendedClass('\\Brads\\Ppm\\Proxy');
     $properties = [];
     $methods = [];
     $implementedInterfaces = [];
     foreach ($versions as $version => $info) {
         foreach ($info['files'] as $file) {
             echo "Parsing: " . $this->vendorDir . '/' . $package . '/' . $version . '/' . $file . "\n";
             $parsedFile = new ReflectionFile($this->vendorDir . '/' . $package . '/' . $version . '/' . $file);
             $parsedClass = $parsedFile->getFileNamespace($info['toNs'])->getClass($info['toNs'] . '\\' . $type['class']);
             if ($parsedClass->getInterfaceNames() != null) {
                 $implementedInterfaces = array_merge($implementedInterfaces, $parsedClass->getInterfaceNames());
             }
             foreach ($parsedClass->getMethods() as $method) {
                 if ($method->isPublic()) {
                     $generatedMethod = new MethodGenerator();
                     $generatedMethod->setName($method->name);
                     $generatedMethod->setBody('echo "Hello world!";');
                     $generatedMethod->setAbstract($method->isAbstract());
                     $generatedMethod->setFinal($method->isFinal());
                     $generatedMethod->setStatic($method->isStatic());
                     $generatedMethod->setVisibility(MethodGenerator::VISIBILITY_PUBLIC);
                     foreach ($method->getParameters() as $param) {
                         $generatedParam = new ParameterGenerator();
                         $generatedParam->setName($param->name);
                         if ($param->hasType()) {
                             $generatedParam->setType($param->getType());
                         }
                         //$generatedParam->setDefaultValue($param->getDefaultValue());
                         $generatedParam->setPosition($param->getPosition());
                         $generatedParam->setVariadic($param->isVariadic());
                         $generatedParam->setPassedByReference($param->isPassedByReference());
                         $generatedMethod->setParameter($generatedParam);
                     }
                     $existingMethod = Linq::from($methods)->firstOrDefault(null, function (MethodGenerator $v) use($method) {
                         return $v->getName() == $method->name;
                     });
                     if ($existingMethod != null) {
                         $existingParams = $existingMethod->getParameters();
                         foreach ($generatedMethod->getParameters() as $newParam) {
                             $existingParam = Linq::from($existingParams)->firstOrDefault(function (ParameterGenerator $v) {
                                 return $v->getName() == $newParam->getName();
                             });
                             if ($existingParam == null) {
                                 $existingMethod->setParameter($newParam);
                             }
                         }
                     } else {
                         $methods[] = $generatedMethod;
                     }
                 }
             }
             foreach ($parsedClass->getProperties() as $prop) {
                 //$properties[] = PropertyGenerator::fromReflection($prop);
             }
         }
     }
     $class->setImplementedInterfaces($implementedInterfaces);
     $class->addMethods($methods);
     $class->addProperties($properties);
     return (new FileGenerator(['classes' => [$class]]))->generate();
 }
 function assertBinArrayEquals(array $expected, E $actual)
 {
     $this->assertEquals($expected, $actual->select('implode($v)')->toList());
 }
Beispiel #17
0
 /**
  * Create Enumerable from an array or any other traversible source.
  * @param array|\Iterator|\IteratorAggregate|\YaLinqo\Enumerable $source
  * @throws \InvalidArgumentException If source is not array or Traversible or Enumerable.
  * @return \YaLinqo\Enumerable
  * @see \YaLinqo\Enumerable::from
  */
 function from($source)
 {
     return \YaLinqo\Enumerable::from($source);
 }
 public function delete_userCredential($delete_data)
 {
     $userId = empty($delete_data['id']) ? NULL : $delete_data['id'];
     $user = $this->Users_model->get_user(array('id' => $userId));
     if (!array_key_exists('credentialType', $delete_data) || empty($delete_data['credentialType'])) {
         $error_message = 'credentialType is required';
         throw new NSH_ValidationException(110, $error_message);
     }
     $credentialTypeToBeDeleted = strtolower($delete_data['credentialType']);
     if ($this->equalIgnorecase(STANDARD_CREDENTIALTYPE, $credentialTypeToBeDeleted)) {
         throw new NSH_ValidationException(223);
     }
     $existingCredentialTypes = Enumerable::from($user->credentialTypes)->select('$credType ==> strtolower($credType)')->toArray();
     if (!in_array($credentialTypeToBeDeleted, $existingCredentialTypes)) {
         throw new NSH_ValidationException(225);
     }
     if (count($existingCredentialTypes) == 1) {
         throw new NSH_ValidationException(224);
     }
     $credentialTypeResult = $this->db->get_where(CREDENTIALTYPES_TABLE, array('name' => $delete_data['credentialType']))->row_array();
     $credentialTypeId = $credentialTypeResult['id'];
     $this->db->delete(USERGENERICCREDENTIALS_TABLE, array('userId' => $userId, 'credentialTypeId' => $credentialTypeId));
 }
Beispiel #19
0
 private function buildFileIncludes()
 {
     $map = [];
     foreach ($this->installedPackages as $package => $versions) {
         foreach ($versions as $version) {
             $composer = $this->reader->setPackage($package)->setVersion($version)->getComposerObject();
             if (!isset($composer['autoload'])) {
                 continue;
             }
             if (!isset($composer['autoload']['files'])) {
                 continue;
             }
             foreach ($composer['autoload']['files'] as $path) {
                 if ($package != null && $version != null) {
                     $path = $package . '/' . $version . '/' . $path;
                 }
                 $map[] = $path;
             }
         }
     }
     return array_values(Linq::from($map)->distinct()->orderBy('$v')->toArray());
 }
Beispiel #20
0
 /**
  * Creates an array of file paths that contain middleware.
  *
  * The middleware files are hierarchical, allowing the child theme to
  * override any middleware that we provide by default. The array is also
  * sorted by filename. So the child theme can "insert" it's middleware
  * in the desired order.
  *
  * @return array
  */
 private function buildQueue()
 {
     $queue = [];
     // Where is our middleware located?
     $parentMiddleware = $this->config->paths->theme->parent->middleware;
     $childMiddleware = $this->config->paths->theme->child->middleware;
     // Loop through our middleware files
     foreach ($this->finder->createFinder()->files()->name('*.php')->in($parentMiddleware) as $file) {
         if ($this->kernel->childHasMiddleware()) {
             // Only register one of our middleware files if the
             // child theme does not have the same middleware file.
             if (!file_exists(str_replace($parentMiddleware, $childMiddleware, $file))) {
                 $queue[] = $file;
             }
         } else {
             $queue[] = $file;
         }
     }
     // Now lets loop through the child theme middleware files.
     if ($this->kernel->childHasMiddleware()) {
         foreach ($this->finder->createFinder()->files()->name('*.php')->in($childMiddleware) as $file) {
             $queue[] = $file;
         }
     }
     // Ensure the middleware queue is sorted.
     return Linq::from($queue)->orderBy('$v')->toArray();
 }
Beispiel #21
0
 /** @covers YaLinqo\Enumerable::writeLine
  * @dataProvider dataProvider_testWriteLine
  */
 function testWriteLine($output, $source, $selector)
 {
     // toString ()
     $this->expectOutputString($output);
     E::from($source)->writeLine($selector);
 }
Beispiel #22
0
 /**
  * @test
  * @param string $tableName
  * @param array $setColumnNamesValues
  * @param null|string $where
  * @param null|string $whereLinq The corresponding string to create where clause with YaLinqo
  * @uses SlimApp\Db\DbTable::findRow
  * @dataProvider provider_update_updates_data_correctly_and_returns_true_on_success
  */
 public function update_updates_data_correctly_and_returns_true_on_success($tableName, $setColumnNamesValues, $where, $whereLinq)
 {
     $config = (require __DIR__ . '/database-config-for-dbunit.php');
     $table = $this->getMockBuilder('SlimApp\\Db\\DbTable')->setConstructorArgs([$config])->getMockForAbstractClass();
     $dbTable = new \SebastianBergmann\PeekAndPoke\Proxy($table);
     // Set tablename manually (set in subclasses, not in abstract class...)
     $dbTable->tableName = $tableName;
     $resultUpdate = $dbTable->update($setColumnNamesValues, $where);
     $result = $dbTable->findRow($where);
     // Get data as array from dataset (xml seed file)
     $resources = $this->getTablesFromDataSet()[$tableName];
     // ie. users
     // Query array using a php linq
     $expected = \YaLinqo\Enumerable::from($resources)->where('$resources ==> $resources' . $whereLinq)->toArray();
     // Substitute data in array
     $expected = array_merge($expected[0], $setColumnNamesValues);
     //die(var_dump($result, $expected));
     $this->assertTrue($resultUpdate);
     $this->assertEquals($expected, $result);
 }
 function assertEnumValuesEquals(array $expected, E $actual, $maxLength = PHP_INT_MAX)
 {
     $this->assertEquals($expected, $actual->take($maxLength)->toValues());
 }
Beispiel #24
0
 /**
  * Resolves a Wordpress Version Contraint.
  *
  * This is a private helper method. It takes a semantic version contraint,
  * parsable by [Composer's Semver](https://github.com/composer/semver) and
  * resolves an actual wordpress version number.
  *
  * We use this page: http://wordpress.org/download/release-archive/
  * As an offical list of released versions.
  *
  * @param  string $versionContraint A semantic version contraint.
  * @return string 					A semantic version number.
  */
 private function wpResolveVersionNo($versionContraint)
 {
     // Remove a v at the start if it exists
     $versionContraint = str_replace('v', '', $versionContraint);
     // If the constraint it a single wildcard, lets just
     // return the latest stable release of wordpress.
     if ($versionContraint == '*') {
         $json = (new Http())->request('GET', self::$WP_VERSION_URL)->getBody();
         return json_decode($json, true)['offers'][0]['version'];
     }
     // Download the releases from the wordpress site.
     $html = (new Http())->request('GET', self::$WP_RELEASES_URL)->getBody();
     // Extract a list of download links, these contain the versions.
     preg_match_all("#><a href='https://wordpress\\.org/wordpress-[^>]+#", $html, $matches);
     // Filter the links to obtain a list of just versions
     $versions = Linq::from($matches[0])->select(function ($v) {
         return s::create($v);
     })->where(function ($v) {
         return $v->endsWith(".zip'");
     })->where(function ($v) {
         return !$v->contains('IIS');
     })->where(function ($v) {
         return !$v->contains('mu');
     })->select(function ($v) {
         return $v->between('wordpress-', '.zip');
     })->where(function ($v) {
         if ($v->contains('-')) {
             return preg_match("#.*-(dev|beta|alpha|rc).*#i", $v) === 1;
         }
         return true;
     })->toArray();
     // Let semver take over and work it's magic
     return (string) Semver::satisfiedBy($versions, $versionContraint)[0];
 }
Beispiel #25
0
 /**
  * Downloads the packages zipball from github and extracts it.
  *
  * @param  array $package The selected version of the package.
  * @return void
  */
 private function downloadAndExtractPackageZipBall($package)
 {
     // NOTE: We actually use this list to determin if there are any stale
     // packages that need to be deleted, so we generate the list here
     // before we decide if we need to actually download the package or not.
     if (!isset($this->downloaded[$package['name']])) {
         $this->downloaded[$package['name']] = [];
     }
     if (!Linq::from($this->downloaded[$package['name']])->contains($package['version_normalized'])) {
         $this->downloaded[$package['name']][] = $package['version_normalized'];
     }
     $packagePath = $this->vendorDir . '/' . $package['name'] . '/' . $package['version_normalized'];
     if ($this->filesystem->has($packagePath)) {
         $this->notify("ALREADY HAVE PACKAGE\n");
         return;
     }
     $url = $package['dist']['url'];
     $zipBall = $this->http->request('GET', $url)->getBody();
     $zipBallPath = $packagePath . '/dist.zip';
     $this->filesystem->put($zipBallPath, $zipBall);
     $this->zip->extract($zipBallPath, $packagePath);
     $this->filesystem->delete($zipBallPath);
     $this->notify("DONE\n");
 }
 /**
  * {@inheritdoc}
  * @param Enumerable $actual
  */
 public function assertEquals($expected, $actual, $delta = 0, $canonicalize = FALSE, $ignoreCase = FALSE, array &$processed = array())
 {
     parent::assertEquals($expected, $actual->toArrayDeep(), $delta, $canonicalize, $ignoreCase, $processed);
 }