Copies files over from a package map

@access private
@param array $package_map A package map to lookup sources and destinations
@param array $result A reference which will be loaded up update and conflict information
@return void
493184
private function copyMap($package_map, &$result = NULL)
	{
		$result   = (array) $result;
		$manager  = $this->composer->getRepositoryManager();
		$packages = $manager->getLocalRepository()->getPackages();

		foreach ($packages as $package) {
			$package_name = $package->getName();
			$package_root = rtrim($this->getInstallPath($package), '/\\' . DIRECTORY_SEPARATOR);

			if (!isset($package_map[$package_name])) {
				continue;
			}

			$this->io->write(sprintf(
				self::TAB . 'Copying files from %s',
				substr($package_root, strlen(getcwd()))
			));

			foreach ($package_map[$package_name] as $a => $b) {
				$a =  trim($a, '/\\' . DIRECTORY_SEPARATOR);
				$b = ltrim($b, '/\\' . DIRECTORY_SEPARATOR);
				$result = array_replace_recursive(
					$this->copy(
						$package_root . DIRECTORY_SEPARATOR . $a,
						getcwd() . DIRECTORY_SEPARATOR . $b,
						$package_name
					),
					$result
				);
			}
		}
	}
1017205
public function addMapping($package_class_name, $class_name)
    {
        $this->mappings[$package_class_name] = $class_name;
        self::add($package_class_name, $class_name);
    }
508341
private void setPackages(DocEnv env, List<String> packages) {
        ListBuffer<PackageDocImpl> packlist = new ListBuffer<PackageDocImpl>();
        for (String name : packages) {
            PackageDocImpl pkg = env.lookupPackage(name);
            if (pkg != null) {
                pkg.isIncluded = true;
                packlist.append(pkg);
            } else {
                env.warning(null, "main.no_source_files_for_package", name);
            }
        }
        cmdLinePackages = packlist.toList();
    }
1288635
private void appendSourceFilesFromSchemaResolver(ParseResult result)
  {
    for (Map.Entry<String, DataSchemaLocation> entry : _schemaResolver.nameToDataSchemaLocations().entrySet())
    {
      final File sourceFile = entry.getValue().getSourceFile();
      if (sourceFile != null)
      {
        result.getSourceFiles().add(sourceFile);
      }
    }
  }
53837
public function hasPackage($package_name)
    {
        if (!isset($this->packages_instances[$package_name])) {
            try {
                $this->packages_instances[$package_name] = $this->_buildNewPackage($package_name);
            } catch (\Exception $e) {
            }
        }
        return isset($this->packages_instances[$package_name]);
    }
995094
public static function writePbjSchemaStoresFile(PackageEvent $event)
    {
        if (!$event->isDevMode()) {
            return;
        }

        $dirs = [];
        /** @var PackageInterface $package */
        foreach ($event->getInstalledRepo()->getPackages() as $package) {
            if (!$package instanceof PackageInterface) {
                continue;
            }

            if ('pbj-schema-store' !== $package->getType()) {
                continue;
            }

            $dir = sprintf('$vendorDir.\'/%s/schemas/\'', $package->getName());

            // override for current package
            if ($event->getComposer()->getPackage()->getName() == $package->getName()) {
                $dir = '__DIR__.\'/schemas/\'';
            }

            $dirs[] = sprintf('%s    %s', PHP_EOL, $dir);
        }

        if (empty($dirs)) {
            return;
        }

        $dirs = array_unique($dirs);
        $dirs = implode(',', $dirs);

        $event->getIO()->write('<info>Writing "pbj-schema-store" locations to "pbj-schema-stores.php"</info>');

        $text = <<<TEXT
<?php

/**
 * DO NOT EDIT THIS FILE as it will be overwritten by Composer as part of
 * the installation/update process.
 *
 * Registers all directories from all required packages which are of
 * of the type "pbj-schema-store".
 *
 * This file has been auto-generated by the Pbj Compiler.
 */

\$vendorDir = realpath(__DIR__.'/vendor');

\\Gdbots\\Pbjc\\SchemaStore::addDirs([{$dirs}
]);

TEXT;

        $fs = new Filesystem();
        $fs->dumpFile('pbj-schema-stores.php', $text);
    }
323674
@Override
    public void dumpResponse(Map<String, Object> result) {
        this.statusCodeResult = String.valueOf(exchange.getStatusCode());
        this.putDumpInfoTo(result);
    }
93105
protected function processDetails(Buffer &$buffer, Result &$result)
    {
        parent::processDetails($buffer, $result);

        // Add in map
        $result->add('mapname', 'Panau');
        $result->add('dedicated', 'true');
    }
1337944
public function writeSupportDirectories(Package $package, $directory)
	{
		foreach (array('config', 'controllers', 'lang', 'migrations', 'views') as $support)
		{
			$this->writeSupportDirectory($package, $support, $directory);
		}
	}
955227
public void flattenPackagesSourcesAndArtifacts(Map<String,Module> m) {
        modules = m;
        // Extract all the found packages.
        for (Module i : modules.values()) {
            for (Map.Entry<String,Package> j : i.packages().entrySet()) {
                Package p = packages.get(j.getKey());
                // Check that no two different packages are stored under same name.
                assert(p == null || p == j.getValue());
                if (p == null) {
                    p = j.getValue();
                    packages.put(j.getKey(),j.getValue());
                }
                for (Map.Entry<String,Source> k : p.sources().entrySet()) {
                    Source s = sources.get(k.getKey());
                    // Check that no two different sources are stored under same name.
                    assert(s == null || s == k.getValue());
                    if (s == null) {
                        s = k.getValue();
                        sources.put(k.getKey(), k.getValue());
                    }
                }
                for (Map.Entry<String,File> g : p.artifacts().entrySet()) {
                    File f = artifacts.get(g.getKey());
                    // Check that no two artifacts are stored under the same file.
                    assert(f == null || f == g.getValue());
                    if (f == null) {
                        f = g.getValue();
                        artifacts.put(g.getKey(), g.getValue());
                    }
                }
            }
        }
    }
401723
static String[] mergePackages(String[] packages1, String[] packages2) {
    String[] all = new String[packages1.length + packages2.length];
    System.arraycopy(packages1, 0, all, 0, packages1.length);
    System.arraycopy(packages2, 0, all, packages1.length, packages2.length);
    return all;
  }
1051288
public function checkPackagesCanBeInstalled($packages_names_list)
    {
        foreach ($packages_names_list as $package_name) {
            $this->checkNoOtherPackageNeedsThisDependencyInALowerVersion($package_name,
                $this->getLatestVersionOfPackage($package_name), $packages_names_list);
        }
    }
824294
function processResult(result) {
    return {
        whenErrorIs: (errorCode) => {
            if (
                errorCode === EAUDITNOLOCK &&
                packageLockHasNotBeenFound(result)
            ) {
                const summary = result.error.summary || '';
                result.error.summary = `package.json file is missing or is badly formatted. ${summary}`;
                return result;
            }
            return result;
        },
    };
}
883192
public function publishPackage($package, $packagePath = null)
    {
        $source = $this->getSource($package, $packagePath ?: $this->packagePath);

        return $this->publish($package, $source);
    }
488349
private function resolve(&$result)
	{
		if (!isset($result['conflicts']) || !count($result['conflicts'])) {
			return;
		}

		$original_checksums = isset($this->installationMap['__CHECKSUMS__'])
			? $this->installationMap['__CHECKSUMS__']
			: array();

		foreach ($result['conflicts'] as $a => $b) {
			$base_path        = str_replace(DIRECTORY_SEPARATOR, '/', getcwd());
			$opus_path        = str_replace($base_path, '', $b);
			$current_checksum = md5(@file_get_contents($b));
			$new_checksum     = md5(@file_get_contents($a));
			$old_checksum     = isset($original_checksums[$opus_path])
				? $original_checksums[$opus_path]
				: md5(FALSE);

			switch ($this->integrity) {
				case 'low':
					copy ($a, $b);
					break;

				case 'medium':
					if ($new_checksum == $old_checksum) {

						//
						// A conflict is only raised if the destinaton differs from the source.
						// However, if we "keep" a file on a previous conflict, the map will be
						// updated with the new checksum even though the file is not copied.  By
						// checking if the new checksum is equal to the old, we can determine if
						// the file has actually changed in the package.  If it has not, we
						// don't need to do anything.
						//

						break;

					} elseif ($old_checksum == $current_checksum) {

						//
						// If we didn't pass the previous condition, then it means that the file
						// in the package has changed since the previous copy or keep.  So now
						// we want to see if the old checksum is equivalent to the current file.
						// This would imply we have not changed it.  If we have no customizations
						// then we can  safely copy the file and update the checksum in the map.
						//

						copy($a, $b);
						$result['updates'][$opus_path] = $new_checksum;
						break;

					} else {

						//
						// Lastly, if our new checksum is not the same as our old one and our
						// old one is not our current one, we want to give the user the option
						// to resolve this as if it were 'high' integrity.
						//

					}

				case 'high':
					$answer = NULL;
					$this->io->write(
						PHP_EOL . self::TAB . 'The following conflicts were found:' . PHP_EOL
					);

					while (!$answer) {
						$answer = $this->io->ask(sprintf(
							self::TAB . '- %s [o=overwrite (default), k=keep, d=diff]: ',
							$opus_path
						), 'o');

						switch(strtolower($answer[0])) {
							case 'o':
								copy($a, $b);
								$result['updates'][$opus_path] = $new_checksum;
								break;

							case 'k':
								$result['updates'][$opus_path] = $new_checksum;
								break;

							case 'd':
								$this->io->write(PHP_EOL . self::diff($a, $b) . PHP_EOL);
							default:
								$answer = NULL;
								break;
						}
					}

					break;
			}
		}
	}
185505
public function freezePackageReflection($packageKey)
    {
        if (!$this->initialized) {
            $this->initialize();
        }
        if (empty($this->availableClassNames)) {
            $this->availableClassNames = $this->reflectionDataRuntimeCache->get('__availableClassNames');
        }

        $reflectionData = [
            'classReflectionData' => $this->classReflectionData,
            'classSchemata' => $this->classSchemata,
            'annotatedClasses' => $this->annotatedClasses,
            'classesByMethodAnnotations' => $this->classesByMethodAnnotations
        ];

        $reflectionData['classReflectionData'] = $this->filterArrayByClassesInPackageNamespace($reflectionData['classReflectionData'], $packageKey);
        $reflectionData['classSchemata'] = $this->filterArrayByClassesInPackageNamespace($reflectionData['classSchemata'], $packageKey);
        $reflectionData['annotatedClasses'] = $this->filterArrayByClassesInPackageNamespace($reflectionData['annotatedClasses'], $packageKey);

        $reflectionData['classesByMethodAnnotations'] = isset($reflectionData['classesByMethodAnnotations']) ? $reflectionData['classesByMethodAnnotations'] : [];
        $methodAnnotationsFilters = function ($className) use ($packageKey) {
            return (isset($this->availableClassNames[$packageKey]) && in_array($className, $this->availableClassNames[$packageKey]));
        };

        foreach ($reflectionData['classesByMethodAnnotations'] as $annotationClassName => $classNames) {
            $reflectionData['classesByMethodAnnotations'][$annotationClassName] = array_filter($classNames, $methodAnnotationsFilters);
        }

        $precompiledReflectionStoragePath = $this->getPrecompiledReflectionStoragePath();
        if (!is_dir($precompiledReflectionStoragePath)) {
            Files::createDirectoryRecursively($precompiledReflectionStoragePath);
        }
        $pathAndFilename = $precompiledReflectionStoragePath . $packageKey . '.dat';
        file_put_contents($pathAndFilename, extension_loaded('igbinary') ? igbinary_serialize($reflectionData) : serialize($reflectionData));
    }
261072
protected function copyMigration(AbstractPackage $package)
    {
        $dir = $package->getDir() . '/Migration';

        // Config
        $targetFolder = $this->console->get('path.resources') . '/migrations';

        $relativePath = str_replace($this->console->get('path.root') . DIRECTORY_SEPARATOR, '', $targetFolder);

        if (!is_dir($dir)) {
            return;
        }

        if (!(new BooleanPrompter)->ask('Do your want to copy migrations to <comment>' . $relativePath . '</comment>? [Y/n]: ',
            true)) {
            return;
        }

        $files = Folder::files($dir, true, Folder::PATH_RELATIVE);

        /** @var \SplFileInfo $file */
        foreach ($files as $file) {
            $dest = new \SplFileInfo($targetFolder . '/' . $file);

            if (is_file($dest->getPathname())) {
                $this->out(sprintf('  [<comment>File exists</comment>] ' . $file));

                continue;
            }

            File::copy($dir . '/' . $file, $dest);

            $this->out(sprintf('  [<info>Copied</info>] ' . $file));
        }

        $this->out()->out('  Copy migrations completed.');
    }