public function getPackageMaintainersQueryBuilder(Package $package, User $excludeUser = null) { $qb = $this->createQueryBuilder('u')->select('u')->innerJoin('u.packages', 'p', 'WITH', 'p.id = :packageId')->setParameter(':packageId', $package->getId())->orderBy('u.username', 'ASC'); if ($excludeUser) { $qb->andWhere('u.id <> :userId')->setParameter(':userId', $excludeUser->getId()); } return $qb; }
private function updateDocumentFromPackage(\Solarium_Document_ReadWrite $document, Package $package) { $document->id = $package->getId(); $document->name = $package->getName(); $document->description = $package->getDescription(); $tags = array(); foreach ($package->getVersions() as $version) { foreach ($version->getTags() as $tag) { $tags[mb_strtolower($tag->getName(), 'UTF-8')] = true; } } $document->tags = array_keys($tags); }
/** * @dataProvider githubApiProvider */ public function testGithubApi($url) { $client = self::createClient(); $package = new Package(); $package->setRepository($url); $user = new User(); $user->addPackages($package); $repo = $this->getMockBuilder('Packagist\\WebBundle\\Entity\\UserRepository')->disableOriginalConstructor()->getMock(); $em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock(); $updater = $this->getMockBuilder('Packagist\\WebBundle\\Package\\Updater')->disableOriginalConstructor()->getMock(); $repo->expects($this->once())->method('findOneBy')->with($this->equalTo(array('username' => 'test', 'apiToken' => 'token')))->will($this->returnValue($user)); static::$kernel->getContainer()->set('packagist.user_repository', $repo); static::$kernel->getContainer()->set('doctrine.orm.entity_manager', $em); static::$kernel->getContainer()->set('packagist.package_updater', $updater); $payload = json_encode(array('repository' => array('url' => 'git://github.com/composer/composer'))); $client->request('POST', '/api/github?username=test&apiToken=token', array('payload' => $payload)); $this->assertEquals(202, $client->getResponse()->getStatusCode()); }
/** * @Route("/api/create-package", name="generic_create", defaults={"_format" = "json"}) * @Method({"POST"}) */ public function createPackageAction(Request $request) { $payload = json_decode($request->getContent(), true); if (!$payload) { return new JsonResponse(array('status' => 'error', 'message' => 'Missing payload parameter'), 406); } $url = $payload['repository']['url']; $package = new Package(); $package->setEntityRepository($this->getDoctrine()->getRepository('PackagistWebBundle:Package')); $package->setRouter($this->get('router')); $user = $this->findUser($request); $package->addMaintainer($user); $package->setRepository($url); $errors = $this->get('validator')->validate($package); if (count($errors) > 0) { $errorArray = array(); foreach ($errors as $error) { $errorArray[$error->getPropertyPath()] = $error->getMessage(); } return new JsonResponse(array('status' => 'error', 'message' => $errorArray), 406); } try { $em = $this->getDoctrine()->getManager(); $em->persist($package); $em->flush(); } catch (\Exception $e) { $this->get('logger')->critical($e->getMessage(), array('exception', $e)); return new JsonResponse(array('status' => 'error', 'message' => 'Error saving package'), 500); } return new JsonResponse(array('status' => 'success'), 202); }
public function notifyUpdateFailure(Package $package, \Exception $e, $details = null) { if (!$package->isUpdateFailureNotified()) { $recipients = array(); foreach ($package->getMaintainers() as $maintainer) { if ($maintainer->isNotifiableForFailures()) { $recipients[$maintainer->getEmail()] = $maintainer->getUsername(); } } if ($recipients) { $body = $this->twig->render('PackagistWebBundle:Email:update_failed.txt.twig', array('package' => $package, 'exception' => get_class($e), 'exceptionMessage' => $e->getMessage(), 'details' => $details)); $message = \Swift_Message::newInstance()->setSubject($package->getName() . ' failed to update, invalid composer.json data')->setFrom($this->options['from'], $this->options['fromName'])->setTo($recipients)->setBody($body); try { $this->mailer->send($message); } catch (\Swift_TransportException $e) { $this->logger->error('[' . get_class($e) . '] ' . $e->getMessage()); return false; } } $package->setUpdateFailureNotified(true); $this->em->flush(); } return true; }
private function createDatePoints(DateTimeImmutable $from, DateTimeImmutable $to, $average, Package $package, Version $version = null) { $interval = $this->getStatsInterval($average); $dateKey = $average === 'monthly' ? 'Ym' : 'Ymd'; $dateFormat = $average === 'monthly' ? 'Y-m' : 'Y-m-d'; $dateJump = $average === 'monthly' ? '+1month' : '+1day'; if ($average === 'monthly') { $to = new DateTimeImmutable('last day of ' . $to->format('Y-m')); } $nextDataPointLabel = $from->format($dateFormat); $nextDataPoint = $from->modify($interval); $datePoints = []; while ($from <= $to) { $datePoints[$nextDataPointLabel][] = 'dl:' . $package->getId() . ($version ? '-' . $version->getId() : '') . ':' . $from->format($dateKey); $from = $from->modify($dateJump); if ($from >= $nextDataPoint) { $nextDataPointLabel = $from->format($dateFormat); $nextDataPoint = $from->modify($interval); } } return $datePoints; }
/** * Populates a feed entry with data coming from Package objects. * * @param \Zend\Feed\Writer\Entry $entry * @param Package $package */ protected function populatePackageData(Entry $entry, Package $package) { $entry->setTitle($package->getName()); $entry->setLink($this->generateUrl('view_package', array('name' => $package->getName()), true)); $entry->setId($package->getName()); $entry->setDateModified($package->getCreatedAt()); $entry->setDateCreated($package->getCreatedAt()); $entry->setDescription($package->getDescription() ?: ' '); }
/** * @param callable $onBeforeIndex TODO Add typehint when migrating to 5.4+ * @param array $orderBys * * @return array */ protected function commonTestSearchActionOrderBysAction($onBeforeIndex, array $orderBys = array()) { $client = self::createClient(); $container = $client->getContainer(); $kernelRootDir = $container->getParameter('kernel.root_dir'); $this->executeCommand('php ' . $kernelRootDir . '/console doctrine:database:drop --env=test --force', false); $this->executeCommand('php ' . $kernelRootDir . '/console doctrine:database:create --env=test'); $this->executeCommand('php ' . $kernelRootDir . '/console doctrine:schema:create --env=test'); $this->executeCommand('php ' . $kernelRootDir . '/console redis:flushall --env=test -n'); $lock = $container->getParameter('kernel.cache_dir') . '/composer-indexer.lock'; $this->executeCommand('rm -f ' . $lock); $em = $container->get('doctrine')->getManager(); if (!empty($orderBys)) { $orderBysQryStrPart = '&' . http_build_query(array('orderBys' => $orderBys)); } else { $orderBysQryStrPart = ''; } $twigPackage = new Package(); $twigPackage->setName('twig/twig'); $twigPackage->setRepository('https://github.com/twig/twig'); $packagistPackage = new Package(); $packagistPackage->setName('composer/packagist'); $packagistPackage->setRepository('https://github.com/composer/packagist'); $symfonyPackage = new Package(); $symfonyPackage->setName('symfony/symfony'); $symfonyPackage->setRepository('https://github.com/symfony/symfony'); $em->persist($twigPackage); $em->persist($packagistPackage); $em->persist($symfonyPackage); $em->flush(); $onBeforeIndex($container, $twigPackage, $packagistPackage, $symfonyPackage); $this->executeCommand('php ' . $kernelRootDir . '/console packagist:index --env=test --force'); $client->request('GET', '/search.json?q=' . $orderBysQryStrPart); $response = $client->getResponse(); $content = $client->getResponse()->getContent(); $this->assertSame(200, $response->getStatusCode(), $content); return json_decode($content, true); }
public function deletePackage(Package $package) { $this->redis->srem('set:packages', strtolower($package->getName())); }
private function updateDocumentFromPackage(\Solarium_Document_ReadWrite $document, Package $package, $redis) { $document->setField('id', $package->getId()); $document->setField('name', $package->getName()); $document->setField('description', $package->getDescription()); $document->setField('type', $package->getType()); $document->setField('trendiness', $redis->zscore('downloads:trending', $package->getId())); $document->setField('repository', $package->getRepository()); if ($package->isAbandoned()) { $document->setField('abandoned', 1); $document->setField('replacementPackage', $package->getReplacementPackage() ?: ''); } else { $document->setField('abandoned', 0); $document->setField('replacementPackage', ''); } $tags = array(); foreach ($package->getVersions() as $version) { foreach ($version->getTags() as $tag) { $tags[mb_strtolower($tag->getName(), 'UTF-8')] = true; } } $document->setField('tags', array_keys($tags)); }
private function updateGitHubInfo(RemoteFilesystem $rfs, Package $package, $owner, $repo) { $baseApiUrl = 'https://api.github.com/repos/' . $owner . '/' . $repo; try { $repoData = JsonFile::parseJson($rfs->getContents('github.com', $baseApiUrl, false), $baseApiUrl); } catch (\Exception $e) { return; } try { $opts = ['http' => ['header' => ['Accept: application/vnd.github.v3.html']]]; $readme = $rfs->getContents('github.com', $baseApiUrl . '/readme', false, $opts); } catch (\Exception $e) { if (!$e instanceof \Composer\Downloader\TransportException || $e->getCode() !== 404) { return; } // 404s just mean no readme present so we proceed with the rest } if (!empty($readme)) { $config = \HTMLPurifier_Config::createDefault(); $config->set('HTML.Allowed', 'a[href|target|rel|id],strong,b,em,i,strike,pre,code,p,ol,ul,li,br,h1,h2,h3,img[src|title|alt|width|height|style]'); $config->set('Attr.EnableID', true); $config->set('Attr.AllowedFrameTargets', ['_blank']); $purifier = new \HTMLPurifier($config); $readme = $purifier->purify($readme); $dom = new \DOMDocument(); $dom->loadHTML('<?xml encoding="UTF-8">' . $readme); // Links can not be trusted $links = $dom->getElementsByTagName('a'); foreach ($links as $link) { $link->setAttribute('rel', 'nofollow'); if ('#' === substr($link->getAttribute('href'), 0, 1)) { $link->setAttribute('href', '#user-content-' . substr($link->getAttribute('href'), 1)); } elseif (false === strpos($link->getAttribute('href'), '//')) { $link->setAttribute('href', 'https://github.com/' . $owner . '/' . $repo . '/blob/HEAD/' . $link->getAttribute('href')); } } // remove first title as it's usually the project name which we don't need if ($dom->getElementsByTagName('h1')->length) { $first = $dom->getElementsByTagName('h1')->item(0); $first->parentNode->removeChild($first); } elseif ($dom->getElementsByTagName('h2')->length) { $first = $dom->getElementsByTagName('h2')->item(0); $first->parentNode->removeChild($first); } $readme = $dom->saveHTML(); $readme = substr($readme, strpos($readme, '<body>') + 6); $readme = substr($readme, 0, strrpos($readme, '</body>')); $package->setReadme($readme); } if (!empty($repoData['language'])) { $package->setLanguage($repoData['language']); } if (!empty($repoData['stargazers_count'])) { $package->setGitHubStars($repoData['stargazers_count']); } if (!empty($repoData['subscribers_count'])) { $package->setGitHubWatches($repoData['subscribers_count']); } if (!empty($repoData['network_count'])) { $package->setGitHubForks($repoData['network_count']); } if (!empty($repoData['open_issues_count'])) { $package->setGitHubOpenIssues($repoData['open_issues_count']); } }
private function updateInformation(Package $package, PackageInterface $data, $flags) { $em = $this->doctrine->getEntityManager(); $version = new Version(); $version->setNormalizedVersion($data->getVersion()); // check if we have that version yet foreach ($package->getVersions() as $existingVersion) { if ($existingVersion->getNormalizedVersion() === $version->getNormalizedVersion()) { if ($existingVersion->getDevelopment() || $flags & self::UPDATE_TAGS) { $version = $existingVersion; break; } // mark it updated to avoid it being pruned $existingVersion->setUpdatedAt(new \DateTime()); return; } } $version->setName($package->getName()); $version->setVersion($data->getPrettyVersion()); $version->setDevelopment($data->isDev()); $em->persist($version); $version->setDescription($data->getDescription()); $package->setDescription($data->getDescription()); $version->setHomepage($data->getHomepage()); $version->setLicense($data->getLicense() ?: array()); $version->setPackage($package); $version->setUpdatedAt(new \DateTime()); $version->setReleasedAt($data->getReleaseDate()); if ($data->getSourceType()) { $source['type'] = $data->getSourceType(); $source['url'] = $data->getSourceUrl(); $source['reference'] = $data->getSourceReference(); $version->setSource($source); } if ($data->getDistType()) { $dist['type'] = $data->getDistType(); $dist['url'] = $data->getDistUrl(); $dist['reference'] = $data->getDistReference(); $dist['shasum'] = $data->getDistSha1Checksum(); $version->setDist($dist); } if ($data->getType()) { $version->setType($data->getType()); if ($data->getType() && $data->getType() !== $package->getType()) { $package->setType($data->getType()); } } $version->setTargetDir($data->getTargetDir()); $version->setAutoload($data->getAutoload()); $version->setExtra($data->getExtra()); $version->setBinaries($data->getBinaries()); $version->setIncludePaths($data->getIncludePaths()); $version->setSupport($data->getSupport()); $version->getTags()->clear(); if ($data->getKeywords()) { foreach ($data->getKeywords() as $keyword) { $tag = Tag::getByName($em, $keyword, true); if (!$version->getTags()->contains($tag)) { $version->addTag($tag); } } } $authorRepository = $this->doctrine->getRepository('PackagistWebBundle:Author'); $version->getAuthors()->clear(); if ($data->getAuthors()) { foreach ($data->getAuthors() as $authorData) { $author = null; // skip authors with no information if (empty($authorData['email']) && empty($authorData['name'])) { continue; } if (!empty($authorData['email'])) { $author = $authorRepository->findOneByEmail($authorData['email']); } if (!$author && !empty($authorData['homepage'])) { $author = $authorRepository->findOneBy(array('name' => $authorData['name'], 'homepage' => $authorData['homepage'])); } if (!$author && !empty($authorData['name'])) { $author = $authorRepository->findOneByNameAndPackage($authorData['name'], $package); } if (!$author) { $author = new Author(); $em->persist($author); } foreach (array('email', 'name', 'homepage', 'role') as $field) { if (isset($authorData[$field])) { $author->{'set' . $field}($authorData[$field]); } } $author->setUpdatedAt(new \DateTime()); if (!$version->getAuthors()->contains($author)) { $version->addAuthor($author); } if (!$author->getVersions()->contains($version)) { $author->addVersion($version); } } } // handle links foreach ($this->supportedLinkTypes as $linkType => $opts) { $links = array(); foreach ($data->{$opts['method']}() as $link) { $constraint = $link->getPrettyConstraint(); if (false !== strpos($constraint, '~')) { $constraint = str_replace(array('[', ']'), '', $link->getConstraint()); $constraint = preg_replace('{(\\d\\.\\d)(\\.0)+(?=$|,|-)}', '$1', $constraint); $constraint = preg_replace('{([><=,]) }', '$1', $constraint); $constraint = preg_replace('{(<[0-9.]+)-dev}', '$1', $constraint); } if (false !== strpos($constraint, ',') && false !== strpos($constraint, '@')) { $constraint = preg_replace_callback('{([><]=?\\s*[^@]+?)@([a-z]+)}i', function ($matches) { if ($matches[2] === 'stable') { return $matches[1]; } return $matches[1] . '-' . $matches[2]; }, $constraint); } $links[$link->getTarget()] = $constraint; } foreach ($version->{'get' . $linkType}() as $link) { // clear links that have changed/disappeared (for updates) if (!isset($links[$link->getPackageName()]) || $links[$link->getPackageName()] !== $link->getPackageVersion()) { $version->{'get' . $linkType}()->removeElement($link); $em->remove($link); } else { // clear those that are already set unset($links[$link->getPackageName()]); } } foreach ($links as $linkPackageName => $linkPackageVersion) { $class = 'Packagist\\WebBundle\\Entity\\' . $opts['entity']; $link = new $class(); $link->setPackageName($linkPackageName); $link->setPackageVersion($linkPackageVersion); $version->{'add' . $linkType . 'Link'}($link); $link->setVersion($version); $em->persist($link); } } // handle suggests if ($suggests = $data->getSuggests()) { foreach ($version->getSuggest() as $link) { // clear links that have changed/disappeared (for updates) if (!isset($suggests[$link->getPackageName()]) || $suggests[$link->getPackageName()] !== $link->getPackageVersion()) { $version->getSuggest()->removeElement($link); $em->remove($link); } else { // clear those that are already set unset($suggests[$link->getPackageName()]); } } foreach ($suggests as $linkPackageName => $linkPackageVersion) { $link = new SuggestLink(); $link->setPackageName($linkPackageName); $link->setPackageVersion($linkPackageVersion); $version->addSuggestLink($link); $link->setVersion($version); $em->persist($link); } } if (!$package->getVersions()->contains($version)) { $package->addVersions($version); } }
private function createDeletePackageForm(Package $package) { if (!($user = $this->getUser())) { return; } // super admins bypass additional checks if (!$this->get('security.context')->isGranted('ROLE_DELETE_PACKAGES')) { // non maintainers can not delete if (!$package->getMaintainers()->contains($user)) { return; } try { $downloads = $this->get('packagist.download_manager')->getDownloads($package); } catch (ConnectionException $e) { return; } // more than 50 downloads = established package, do not allow deletion by maintainers if ($downloads['total'] > 50) { return; } } return $this->createFormBuilder(array())->getForm(); }
private function updateDocumentFromPackage(\Solarium_Document_ReadWrite $document, Package $package) { $document->setField('id', strtolower($package->getName())); $document->setField('name', $package->getName()); $document->setField('description', $package->getDescription()); $document->setField('type', $package->getType()); $tags = array(); foreach ($package->getVersions() as $version) { foreach ($version->getTags() as $tag) { $tags[mb_strtolower($tag->getName(), 'UTF-8')] = true; } } $document->setField('tags', array_keys($tags)); }
private function updateDocumentFromPackage(Solarium_Document_ReadWrite $document, Package $package, array $tags, $redis, DownloadManager $downloadManager, FavoriteManager $favoriteManager) { $document->setField('id', $package->getId()); $document->setField('name', $package->getName()); $document->setField('package_name', $package->getPackageName()); $document->setField('description', preg_replace('{[\\x00-\\x1f]+}u', '', $package->getDescription())); $document->setField('type', $package->getType()); $document->setField('trendiness', $redis->zscore('downloads:trending', $package->getId())); $document->setField('downloads', $downloadManager->getTotalDownloads($package)); $document->setField('favers', $favoriteManager->getFaverCount($package)); $document->setField('repository', $package->getRepository()); $document->setField('language', $package->getLanguage()); if ($package->isAbandoned()) { $document->setField('abandoned', 1); $document->setField('replacementPackage', $package->getReplacementPackage() ?: ''); } else { $document->setField('abandoned', 0); $document->setField('replacementPackage', ''); } $tags = array_map(function ($tag) { return mb_strtolower(preg_replace('{[\\x00-\\x1f]+}u', '', $tag), 'UTF-8'); }, $tags); $document->setField('tags', $tags); }
public function isMarked(UserInterface $user, Package $package) { return null !== $this->redis->zrank('usr:'******':fav', $package->getId()); }
/** * @Route("/packages/fetch-info", name="submit.fetch_info", defaults={"_format"="json"}) */ public function fetchInfoAction() { $package = new Package(); $package->setEntityRepository($this->getDoctrine()->getRepository('PackagistWebBundle:Package')); $form = $this->createForm(new PackageType(), $package); $response = array('status' => 'error', 'reason' => 'No data posted.'); $request = $this->getRequest(); if ('POST' === $request->getMethod()) { $form->bindRequest($request); if ($form->isValid()) { $response = array('status' => 'success', 'name' => $package->getName()); } else { $errors = array(); foreach ($form->getChildren() as $child) { if ($child->hasErrors()) { foreach ($child->getErrors() as $error) { $errors[] = $error->getMessageTemplate(); } } } $response = array('status' => 'error', 'reason' => $errors); } } return new Response(json_encode($response)); }
public function findOneByNameAndPackage($author, Package $package) { $qb = $this->createQueryBuilder('a'); $qb->select('a')->leftJoin('a.versions', 'v')->leftJoin('v.package', 'p')->where('p.id = :packageId')->andWhere('a.name = :author')->setMaxResults(1)->setParameters(array('author' => $author, 'packageId' => $package->getId())); return $qb->getQuery()->getOneOrNullResult(); }
private function updateGitHubInfo(RemoteFilesystem $rfs, Package $package, $owner, $repo, VcsRepository $repository) { $baseApiUrl = 'https://api.github.com/repos/' . $owner . '/' . $repo; $driver = $repository->getDriver(); if (!$driver instanceof GitHubDriver) { return; } $repoData = $driver->getRepoData(); try { $opts = ['http' => ['header' => ['Accept: application/vnd.github.v3.html']]]; $readme = $rfs->getContents('github.com', $baseApiUrl . '/readme', false, $opts); } catch (\Exception $e) { if (!$e instanceof \Composer\Downloader\TransportException || $e->getCode() !== 404) { return; } // 404s just mean no readme present so we proceed with the rest } if (!empty($readme)) { $elements = array('p', 'br', 'small', 'strong', 'b', 'em', 'i', 'strike', 'sub', 'sup', 'ins', 'del', 'ol', 'ul', 'li', 'h1', 'h2', 'h3', 'dl', 'dd', 'dt', 'pre', 'code', 'samp', 'kbd', 'q', 'blockquote', 'abbr', 'cite', 'table', 'thead', 'tbody', 'th', 'tr', 'td', 'a[href|target|rel|id]', 'img[src|title|alt|width|height|style]'); $config = \HTMLPurifier_Config::createDefault(); $config->set('HTML.Allowed', implode(',', $elements)); $config->set('Attr.EnableID', true); $config->set('Attr.AllowedFrameTargets', ['_blank']); $purifier = new \HTMLPurifier($config); $readme = $purifier->purify($readme); $dom = new \DOMDocument(); $dom->loadHTML('<?xml encoding="UTF-8">' . $readme); // Links can not be trusted, mark them nofollow and convert relative to absolute links $links = $dom->getElementsByTagName('a'); foreach ($links as $link) { $link->setAttribute('rel', 'nofollow noopener external'); if ('#' === substr($link->getAttribute('href'), 0, 1)) { $link->setAttribute('href', '#user-content-' . substr($link->getAttribute('href'), 1)); } elseif ('mailto:' === substr($link->getAttribute('href'), 0, 7)) { // do nothing } elseif (false === strpos($link->getAttribute('href'), '//')) { $link->setAttribute('href', 'https://github.com/' . $owner . '/' . $repo . '/blob/HEAD/' . $link->getAttribute('href')); } } // convert relative to absolute images $images = $dom->getElementsByTagName('img'); foreach ($images as $img) { if (false === strpos($img->getAttribute('src'), '//')) { $img->setAttribute('src', 'https://raw.github.com/' . $owner . '/' . $repo . '/HEAD/' . $img->getAttribute('src')); } } // remove first title as it's usually the project name which we don't need if ($dom->getElementsByTagName('h1')->length) { $first = $dom->getElementsByTagName('h1')->item(0); $first->parentNode->removeChild($first); } elseif ($dom->getElementsByTagName('h2')->length) { $first = $dom->getElementsByTagName('h2')->item(0); $first->parentNode->removeChild($first); } $readme = $dom->saveHTML(); $readme = substr($readme, strpos($readme, '<body>') + 6); $readme = substr($readme, 0, strrpos($readme, '</body>')); $package->setReadme($readme); } if (!empty($repoData['language'])) { $package->setLanguage($repoData['language']); } if (isset($repoData['stargazers_count'])) { $package->setGitHubStars($repoData['stargazers_count']); } if (isset($repoData['subscribers_count'])) { $package->setGitHubWatches($repoData['subscribers_count']); } if (isset($repoData['network_count'])) { $package->setGitHubForks($repoData['network_count']); } if (isset($repoData['open_issues_count'])) { $package->setGitHubOpenIssues($repoData['open_issues_count']); } }
protected function initializePackages(ContainerInterface $container) { $kernelRootDir = $container->getParameter('kernel.root_dir'); $this->executeCommand('php ' . $kernelRootDir . '/console doctrine:database:drop --env=test --force', false); $this->executeCommand('php ' . $kernelRootDir . '/console doctrine:database:create --env=test'); $this->executeCommand('php ' . $kernelRootDir . '/console doctrine:schema:create --env=test'); $this->executeCommand('php ' . $kernelRootDir . '/console redis:flushall --env=test -n'); $em = $container->get('doctrine')->getManager(); $twigPackage = new Package(); $twigPackage->setName('twig/twig'); $twigPackage->setRepository('https://github.com/twig/twig'); $packagistPackage = new Package(); $packagistPackage->setName('composer/packagist'); $packagistPackage->setRepository('https://github.com/composer/packagist'); $symfonyPackage = new Package(); $symfonyPackage->setName('symfony/symfony'); $symfonyPackage->setRepository('https://github.com/symfony/symfony'); $em->persist($twigPackage); $em->persist($packagistPackage); $em->persist($symfonyPackage); $em->flush(); return [$twigPackage, $packagistPackage, $symfonyPackage]; }
private function createDeletePackageForm(Package $package) { if (!($user = $this->getUser())) { return; } // super admins bypass additional checks if (!$this->get('security.context')->isGranted('ROLE_DELETE_PACKAGES')) { // non maintainers can not delete if (!$package->getMaintainers()->contains($user)) { return; } try { /** @var $redis \Snc\RedisBundle\Client\Phpredis\Client */ $redis = $this->get('snc_redis.default'); $downloads = $redis->get('dl:' . $package->getId()); } catch (\Exception $e) { return; } // more than 50 downloads = established package, do not allow deletion by maintainers if ($downloads > 50) { return; } } return $this->createFormBuilder(array())->getForm(); }