Zend Framework 2 Autoload Third Party library using composer - zend-framework2

I am trying to use composer to autoload a third party library into my ZF2 application - specifically Google api.
I followed the answer in this post on SO, edited my composer.json
"autoload": {
"psr-0": {"Googleanalytics\\": "vendor/google-api-php-client/src/"}
}
and ran update.
I can see the entry in composer/autoload_namespaces.php
'Googleanalytics\\' => array($vendorDir . '/google-api-php-client/src'),
but i still get a fatal error class not found when trying to instantiate a class in that directory (Google_Client.php).
Any ideas what i am missing?
I am including the file in the class i am trying to use it:
use Googleanalytics\Google_Client;
I have tried renaming the directory in case the - was the problem and also creating a simple test.php file in that dir in case the underscore in the class name (Google_Client.php) was the problem, but still the same error.
Is there anything else i need to add to my ZF2 application to autoload this library?
Also note i decided not to use ZendGdata as this component does not seem to be maintained anymore.
Thanks in advance

The autoload definition of your software should not include the autoload definition of any vendor module. Move that to the package definition you use to include the software.
And in other news: If it does not work with PSR-0, the classmap autoloader should take care of it.
Update
How to create the package for a repository not offering a composer.json
Essentially you'd need only a couple of pieces of information:
The version number and where it's located in that repository.
A name of the software you are trying to use - you'd probably only want to add a vendor name and not be too creative with the module.
Know how to autoload the package, i.e. know which path is used for the software and apply the classmap autoloader to it.
At least one of the following, preferredly both:
The URL of the repository that hosts the code
The URL of a download of a published version
In case of the "google-api-php-client", the a) URL of the repository is http://google-api-php-client.googlecode.com/svn/, the b) most current version number is 0.6.7, the A) download URL of that package is http://google-api-php-client.googlecode.com/files/google-api-php-client-0.6.7.tar.gz.
And now you fill it into this "template":
"repositories": [
{
"type": "package",
"package": {
"name": "name from (2)",
"version": "version from (1)",
"dist": {
"url": "URL from (4/2)",
"type": "tar or zip according to download"
},
"source": {
"url": "URL from (4/1)",
"type": "svn",
"reference": "tags/version from (1)"
},
"autoload": {
"classmap": ["path from (3)"]
}
}
}
]
And then you can require that exact package in your requirements: "require": { "name from (2)": "version from (1)" }
For the google package you are using this would essentially get you to use this:
"require": {
"google/google-api-php-client":"*"
},
"repositories": [
{
"type": "package",
"package": {
"name": "google/google-api-php-client",
"version": "0.6.7",
"dist": {
"url": "http://google-api-php-client.googlecode.com/files/google-api-php-client-0.6.7.tar.gz",
"type": "tar"
},
"source": {
"url": "http://google-api-php-client.googlecode.com/svn/",
"type": "svn",
"reference": "tags/0.6.7"
},
"autoload": {
"classmap": ["src/"]
}
}
}
]
The benefit of adding this mostly boilerplate stuff is that you get the downloading of the software for free now. You don't have to care about how to manually download, unpack and install the package. You did add the autoloading information for this software to your own composer.json, but it is contained in the package definition of the software you want to use, it is not contained in the autoloading area of your own software.
You also do not have to worry about Composer removing your manually downloaded package accidentally.

For anyone else looking to add a third party library to ZF2 using composer, here are the steps that worked for me.
Copy third party library to vendor folder
Add following line to composer.json
"autoload": {
"classmap": ["vendor/PATH TO LIBRARY"]
}
Run php composer.phar update
Then you should see all the classes that were in the 3rd party library in the file in the composer folder: composer/autoload_classmap.php
When instantiating any class from the library in your zf2 application, dont forget to prefix the class name with a \.
For example:
$client = new \Google_Client();

Related

How to query repository rule in bazel?

I'm trying to translate my company's project from legacy build tool to bazel. Now I'm facing this problem and searched a lot, but unfortunately, I haven't had a clue so far.
Here's the thing:
For compliance with open source audit, we must provide a list of open-source software which are built into our binary. As external dependencies are introduced by repository rules, my intuitive thought is to query these rules and get the URLs. However, subcommand query/cquery hasn't provided such functionality yet AFAIK, it can print rule/target/buildfiles but no repository rules nor their attributes.
Is there a way that I can gather such information from repository rules in WORKSPACE? It's not viable to do it manually as there are thousands of projects in my company and the dependencies also change frequently.
For example, a workspace rule:
http_archive(
name = "testrunner",
urls = ["https://github.com/testrunner/v2.zip"],
sha256 = "..."
)
This dependency is used by a rule named "my_target", so what i expected is that the dependency could be queried like this:
> bazel queryExtDep my_target
External Dependency of my_target: name->testrunner, urls = "https://github.com/testrunner/v2.zip"
--experimental_repository_resolved_file will give you all that information in a single Starlark file, which you can easily process with Starlark or Python etc to extract the information you're looking for.
The resolved file looks something like this:
resolved = [
...,
{
"original_rule_class": "#bazel_tools//tools/build_defs/repo:git.bzl%git_repository",
"original_attributes": {
"name": "com_google_protobuf",
"remote": "https://github.com/google/protobuf",
"branch": "master"
},
"repositories": [
{
"rule_class": "#bazel_tools//tools/build_defs/repo:git.bzl%git_repository",
"attributes": {
"remote": "https://github.com/google/protobuf",
"commit": "78ba021b846e060d5b8f3424259d30a1f3ae4eef",
"shallow_since": "2018-02-07",
"init_submodules": False,
"verbose": False,
"strip_prefix": "",
"patches": [],
"patch_tool": "patch",
"patch_args": [
"-p0"
],
"patch_cmds": [],
"name": "com_google_protobuf"
}
}
]
}
]
This includes the original attributes, which is where that URL you're looking for is. It also includes any additional information returned by the repository rule (ie for git_repository, the actual commit a given ref refers to).
I got that example from blog post introducing that flag, which also has some more background.

Electron: Keep Getting 'You'll need a new app to open this' Screen

Developed an Electron app using Vuejs and everything works fine in development, but when packaged I keep getting this pop-up after start up (NOTE: This is a sample image - mine doesn't say 'windowsdefender' but is otherwise the same).
Using electron-builder to create the application with the following build json, and it is installed on the PC:
{
"productName": "My App",
"appId": "com.mycompany.myapp",
"win": {
"icon": "build/icon.png",
"target": [
"nsis"
]
}
}
Though the app does open, there is no initial screen. However, I can open the dev tools but there are no errors displayed.
Any ideas on what is causing this or how to resolve?
After many tries, I finally figured it out (or at least I think I know what caused the issue).
The primary issue was that in using vue router (from an app ported from the web), it is important that you use 'hash' mode and not 'history. Add this to your router file:
const router = new VueRouter({
mode: process.env.IS_ELECTRON ? "hash" : "history",
routes
});
See this link for more details (common issues): Vue CLI plugin common issues
Second, I think there is a rights issue (i.e. having elevated rights to install) so I added this line along with the guid to my electron-builder.json file. The result was a build file like this:
{
"productName": "My App",
"appId": "com.abcco.my-app",
"win": {
"icon": "build/icon.png",
"target": "nsis",
"requestedExecutionLevel": "requireAdministrator"
},
"nsis": {
"guid": "6ee647a9-d5c6-46a9-a480-aa7d6d3d1c10",
"oneClick": false,
"allowToChangeInstallationDirectory": true
}
}
As I am developing only for Windows I was able to use material from this page (React but not that different with respect to Electron packaging):
Electron Build file help
The last thing I did was to remove all 'dist' files and uninstall the app entirely (previous versions). I think this cleared up a lot of the 'baggage' left over from testing.
Hopefully this helps others who may experience the same issue.

how to configure files paths in VSCode task errors

I configured a task in VSCode to compile a Delphi 2005 dpk. It is working and returning the errors on the "problems view", but it is not showing that errors in the file.
I think it is happening because when I click on an error, I get the error message:
Unable to open 'sr075pro.pas': File not found
(...projectfolder\sr075pro.pas)
But the file is in ...projectfolder\webservices\sr075pro.pas.
I can't find a way to tell to the task that the file is in a subfolder. I tried to use the "relative" option on the "fileLocation" tag without sucess.
The error returned:
Compiling sa_webservices...
Borland Delphi Version 13.0 Copyright (c) 1983,99 Inprise Corporation
sr075pro.pas(99) Error: Undeclared identifier: 'ni'
sa_webservices.dpk(802) Fatal: Could not compile used unit 'sr075pro.pas'
My task configuration:
{
"version": "0.1.0",
"name": "Compilar",
"command": "C:\\Compilers\\compile.bat",
"suppressTaskName": true,
"isShellCommand": true,
"isBuildCommand": true,
"tasks": [
{
"taskName": "Compile sa_webservices",
"isBuildCommand": false,
"isTestCommand": false,
"showOutput": "always",
"args": [
"sa_webservices"
],
"problemMatcher": {
"owner": "external",
"fileLocation": "relative",
"pattern": {
"regexp": "^([\\w]+\\.(pas|dpr|dpk))\\((\\d+)\\)\\s(Fatal|Error|Warning|Hint):(.*)",
"file": 1,
"line": 3,
"message": 5
}
}
}
My compile.bat:
#echo off
#P:
#set arg1=%1
shift
...
if "%arg1%" == "sa_webservices" set arg2="webservices"
...
echo Compiling %arg1%...
cd\%arg2%
dcc32.exe -H -W -Q %arg1%.dpk
Your task configuration is wrong. First of all you don't close all brackets but I guess it's a mistake made by copying and pasting it here on StackOverflow. Otherwise the task configuration wouldn't have worked at all.
Now to the real problem:
DCC32 produces hints and warnings containing relative file paths. These paths are relative to the project file. In your task configuration you define the compiler's output to contain relative paths by setting
"fileLocation": "relative"
Visual Studio Code doesn't know how to build the correct absolute path from the relative paths given by the compiler message. So it guesses your current ${workspaceRoot} (in your case it's projectfolder) would be the absolute path.
This explains why you see errors and warnings which contain wrong file paths. In order to get the correct paths you'll need to tell VSCode the correct path to combine the relative paths with.
You do this by simply adding the correct path to the fileLocation entry in you tasks.json:
"fileLocation": ["relative", "${workspaceRoot}\\webservices"]
The entire tasks.json looks like that:
{
"version": "0.1.0",
"name": "Compilar",
"command": "C:\\Compilers\\compile.bat",
"suppressTaskName": true,
"isShellCommand": true,
"isBuildCommand": true,
"tasks": [
{
"taskName": "Compile sa_webservices",
"isBuildCommand": false,
"isTestCommand": false,
"showOutput": "always",
"args": [
"sa_webservices"
],
"problemMatcher": {
"owner": "external",
"fileLocation": ["relative", "${workspaceRoot}\\webservices"],
"pattern": {
"regexp": "^([\\w]+\\.(pas|dpr|dpk))\\((\\d+)\\)\\s(Fatal|Error|Warning|Hint):(.*)",
"file": 1,
"line": 3,
"message": 5
}
}
}
]
}
It might be easier to find files in the problemMatcher in vscode 1.74, see file location search: v1.74 release notes. There is a new option search for the fileLocation property:
New file location method; search
Previously, problem matchers needed to know exactly where to look for
the problematic files, via the fileLocation property. The supported
methods were absolute, relative, or autoDetect (i.e., check for
relative paths first and opt to absolute paths in case of failure).
However, in workspaces that need to invoke various scripts residing in
nested sub-directories, the developers could have a hard time setting
up their tasks; since such scripts seldom report file paths in a
unified manner (e.g., relative to the workspace's base directory).
To help alleviate the problem, a new file location method, named
search, is introduced in this version. With this method, a deep file
system search will be initiated to locate any captured path. See the
example below on how to setup the search file location method
(although, all parameters are optional):
// ...
"fileLocation": [
"search",
{
"include": [ // Optional; defaults to ["${workspaceFolder}"]
"${workspaceFolder}/src",
"${workspaceFolder}/extensions"
],
"exclude": [ // Optional
"${workspaceFolder}/extensions/node_modules"
]
}
],
// ... } ```
⚠️ Of course, users should be wary of the possibly **heavy file system
searches** (e.g., looking inside `node_modules` directories) and set
the `exclude` property with discretion.

How to get (tray) icon path/image in electron-builder

I'm using electron-react-boilerplate to develop electron app (which uses electron-builder to pack apps).
I want to create tray, but it requires icon path or native image. The question is how to retrieve icon image from electron-builder or how to tell electron-builder to include icons dir into resources (without packing), so I can use:
appIcon = new Tray(iconPath | nativeImage)
I kind of struggled with a solution about non-packaged assets (such as media or JSON config files), mostly because I was not familiar with Electron until now. :)
I built a simple personal tray-only app and I didn't want to repackage every time I change an icon for instance.
If you too plan on using changing/dynamic assets you can distinguish between "development" and "production" using this property:
https://electronjs.org/docs/api/app#appispackaged-readonly
Make sure you have this in your package.json:
"build": {
...
"extraResources": [
"./assets/**"
],
}
https://www.electron.build/configuration/contents#extraresources
Then in your code you can have:
const assetsPath = app.isPackaged ? path.join(process.resourcesPath, "assets") : "assets";
Of course you can also use a different path for storing assets, independent of your packaged app folder, for example your user's home or user's documents:
https://electronjs.org/docs/api/app#appgetpathname
Electron v7.0.1
electron-builder 21.2.0
Firstly you need to tell electron-builder which extra files need copying into your output build. I copy over native drivers for each os like below, but you should be able to adapt this to your needs. The "to": "resources" means you'll be able to use the next code to find the files later.
"build": {
...
"extraFiles": [
{
"from": "resources/${os}/drivers",
"to": "resources",
"filter": [
"**/*"
]
}
],
Then to get access to that path from in electron you can use:
const path = require('path');
const imgPath = path.join(process.resourcesPath, 'image.png')
If you're in the main process you can omit the remote part.
You can then use nativeImage.createFromPath to get a native image:
const nativeImage = require('electron').nativeImage
let image = nativeImage.createFromPath(imgPath)
Thanks, Tim, your answer gave me a good thought. I reused it with some addition depending on how I run my app - form vs code using electron or from installed deb file:
"build": {
...
"extraFiles": [
{
"from": "assets",
"to": "resources",
"filter": [
"**/*"
]
}
]
...
}
And then:
let imgPath = process.env.DEV ? "assets/icon.png" : path.join(process.resourcesPath, "icon.png");
tray = new Tray(imgPath);

Gulp task to bundle bower_components?

I'd appreciate it so much if someone could please tell me a good way to handle bundling bower components. I feel like I've tried everything... Although, I can't seem to find any gulp tasks that handle this already. Could it really not exist?
Let's say it doesn't exist. Worst case scenario is I have to specify the paths of each "dist" file from bower_components folder. (It is annoying that each component seems to have its own "dist" folder... nothing is standardized.)
So even if I do that, I've noticed some components like 'active-support' seem to have require('lodash') and such in them. I think that if I just simply copy that file, it will break because the requires won't resolve.
What am I missing? How do I simply take all bower_components and bundle into a "common.js"... is there a way or is it a clusterfluck?
Update
As pointed out by Alerty, the new Gulp policy seems to be: use bower directly and glob patterns (and hope that the packages maintainers have a proper "ignore" properties).
Previously
You can use main-bower-files or gulp-bower-src to get files from your bower components. They can also use "ignore" or "main" overrides in your own bower file.
This is how I managed it (but see gulpfile.js for project structure, it's not a single gigantic gulpfile) :
https://github.com/notbrain/viceroy/blob/master/gulp/tasks/bower.js
Would be a bit more modular to simply concat all bower deps and then do the uglify() and minifyCSS() tasks separately on dist/ source locations, based on dev/prod env targets, but will have to wait for future updates.
Use main-bower-files:
var gulp = require('gulp');
var mainBowerFiles = require('main-bower-files');
gulp.task('TASKNAME', function() {
return gulp.src(mainBowerFiles())
.pipe(/* what you want to do with the files */)
});
if you have folders like:
-app
-bower
-node_modules
Gulpfile.js
package.json
the solution are:
gulp.task("connect", function () {
connect.server({
root: ["app"],
livereload: true,
port: 8034,
middleware: function (connect) {
return [connect().use("/bower", connect.static("bower"))];
}
});
});
If your project use AMD specification.
You can use gulp-edp bundle the modules.
set module info at module.conf
{
"baseUrl": "src",
"paths": {},
"packages": [
{
"name": "etpl",
"location": "../bower_components/etpl/3.0.1/src",
"main": "main"
},
{
"name": "jquery",
"location": "../bower_components/jquery/1.9.1/src",
"main": "jquery.min"
}
],
"combine": {
"app": true
}
}
gulpfile.js
var gulp = require('gulp');
var edp = require('gulp-edp');
gulp.src(
[
'src/**/*.js'
'bower_components/**/*.js',
'!bower_components/**/{demo,demo/**}',
'!bower_components/**/{test,test/**}'
]
)
.pipe(edp({
getProcessors: function () {
var moduleProcessor = new this.ModuleCompiler();
return [moduleProcessor];
}
}))
.pipe(gulp.dest('dist'));
See EDP wiki for more features.

Resources