Giter Site home page Giter Site logo

infinum / eightshift-libs Goto Github PK

View Code? Open in Web Editor NEW
61.0 10.0 10.0 21.2 MB

Library that is meant to be used inside Eightshift Boilerplate and Eightshift Boilerplate Plugin libs via composer in order to be able to easily set up a modern development process.

Home Page: https://eightshift.com

License: MIT License

PHP 87.88% JavaScript 0.28% SCSS 0.10% Twig 11.74%
eightshift-libs eightshift-boilerplate wordpress open-source

eightshift-libs's Introduction

image

GitHub tag GitHub stars license codecov

Eightshift Libs

This library is aimed at bringing the modern backend development tools to the Eightshift Boilerplate or Eightshift Boilerplate Plugin, but you can use it on any WordPress project.

Documentation

For the full documentation please check this link.

Who do I talk to?

If you have any questions or problems, please open an issue on github and we will do our best to give you a timely answer.

Maintainers

Eightshift Libs is maintained and sponsored by Eightshift and Infinum.

License

Eightshift Libs ยฉ2022 Eightshift and Infinum. It is free software, and may be redistributed under the terms specified in the LICENSE file.

eightshift-libs's People

Contributors

dadadavorin avatar dingo-d avatar gabriel-glo avatar goranalkovic-infinum avatar iobrado avatar iruzevic avatar jerryspecter avatar kancijan avatar lukicdev avatar metardev avatar szepeviktor avatar volfkarlo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eightshift-libs's Issues

Localization missing in blocks

Currently, there is no way to provide localization, in the same way, it's possible in admin scripts and theme scripts

public function enqueueBlockEditorScript(): void
{
$handler = "{$this->getAssetsPrefix()}-block-editor-scripts";
\wp_register_script(
$handler,
$this->manifest->getAssetsManifestItem(static::BLOCKS_EDITOR_SCRIPT_URI),
$this->getAdminScriptDependencies(),
$this->getAssetsVersion(),
$this->scriptInFooter()
);
\wp_enqueue_script($handler);
}

This should be added as well.

Fix project path for pre-commit

Current Behavior

When staging php files and running npm run lint it stops on Checking PHP Lint while giving the wrong path to the staged file.

Possible Solution

Change line 8 in bin/lintPhp.sh from PROJECT=php -r "echo dirname(dirname(realpath('$0')));" to `PROJECT=`php -r "echo dirname(dirname(dirname(dirname(dirname(realpath('$0'))))));"

Add example commands to the CLI commands

Usually, WP-CLI commands have examples in the help, like:

NAME

  wp config create

DESCRIPTION

  Generates a wp-config.php file.

...

EXAMPLES

    # Standard wp-config.php file
    $ wp config create --dbname=testing --dbuser=wp --dbpass=securepswd --locale=ro_RO
    Success: Generated 'wp-config.php' file.

    # Enable WP_DEBUG and WP_DEBUG_LOG
    $ wp config create --dbname=testing --dbuser=wp --dbpass=securepswd --extra-php <<PHP
    define( 'WP_DEBUG', true );
    define( 'WP_DEBUG_LOG', true );
    PHP
    Success: Generated 'wp-config.php' file.

    # Avoid disclosing password to bash history by reading from password.txt
    # Using --prompt=dbpass will prompt for the 'dbpass' argument
    $ wp config create --dbname=testing --dbuser=wp --prompt=dbpass < password.txt
    Success: Generated 'wp-config.php' file.

We should also create examples so that people can just copy/paste from them.

shortcode

How do I execute shortcode in custom component?
... shortcode( '[mc4wp_form id="'.$id.'"]' ); This not works for example
Thanks

Some 0x08 characters are left in

$ grep -rFn $'\x08'

src/enqueue/class-enqueue-theme.php:37:   * @since 2.0.
src/enqueue/class-enqueue-theme.php:59:   * @since 2.0.
src/enqueue/class-enqueue-theme.php:71:   * @since 2.0.
src/enqueue/class-enqueue-theme.php:90:   * @since 2.0.
src/blocks/class-blocks.php:21: * @since 2.0.
src/menu/class-menu.php:18: * @since 2.0.
src/menu/class-menu.php:27:   * @since 2.0.
src/menu/class-menu.php:38:   * @since 2.0.
src/menu/class-menu.php:51:   * @since 2.0.
src/menu/class-menu.php:67:   * @since 2.0.

Scope eightshift-libs during installation

In a situation in which two instances of boilerplate, with different versions, exist in the same project there is a collision with the classes that use older implementation of libs.

Example:
Plugin boilerplate is using newer version and theme is using older version of the libs. Since plugins are loaded earlier than theme, newer Eightshift_Libs namespace will be used and older one (from the theme) will be ignored. This creates fatal errors in theme.

Solution would be to somehow scope or differentiate each installation of libs, so we don't get these collisions. This could be done during the npx installation process but then there is no way to potentially update libs in the future.

[FEATURE] Write all the tests! ๐Ÿ™†๐Ÿผโ€โ™‚๏ธ

As discussed on the standup we need to divide and conquer the task of writing the unit tests.

The initial setup and test examples have been merged to the release/3.1.0 branch so you can branch from there. The GH Actions are also set up, so that will work as well ๐Ÿ™‚ .

@infinum/wordpress-team you can comment which parts you'll like to test so that we don't overlap.

[BUG] Bug when setuping the theme for the first time

I went to test the bem menu on a clean theme, I used the release/3.1.0 branch and the bem menu branch on the frontend libs, and I ran into a strange issue, not sure where the problem lies tbh.

When setting up the theme using the wp boilerplate setup_theme command, it looks like when copying the components, the command for blocks is somehow used, and all the files and folders for blocks are created for components (transforms, hooks, etc.).

And the command failed on the footer component because the command tried to copy the footer editor component (which doesn't exist).

This happens in the new 3.1.0 release branch so I suspect there is an issue with changing the CLI commands.

[BUG] Creating taxonomy will capitalize the textdomain in the contents

Describe the bug

When creating a custom taxonomy using

wp boilerplate create_taxonomy

The textdomain in the labels will be capitalized. Not sure what happens to text domain with a dash in it.

Steps to Reproduce

  1. Setup theme
  2. Try to create a custom taxonomy
  3. Check the label field in the getTaxonomyArguments() method
  4. The text domain should be lowercased

Your Environment

  • PHP version: 7.4.14
  • Development environment: Valet
  • Server type: Nginx
  • Operating System and version: MacOS Bug Sur 11.2.2
  • Libs version: 3.0.4

[BUG] getManifest missing throwable error

public static function getManifest(string $path): array
{
$manifest = "{$path}/manifest.json";
if (!file_exists($manifest)) {
ComponentException::throwUnableToLocateComponent($manifest);
}
return json_decode(implode(' ', (array)file($manifest)), true);
}

the getManifest helper is missing the throw keyword, and on top of that, everywhere it's used a try/catch block should be added so that that exception can be caught.

[FEATURE] Add aditional svg path properties

Add additional properties to SVG -> path in AbstractEscapedView

Properties to add:

'clip-rule' => true,
'stroke-width' => true,
'stroke-linecap' => true,
'stroke-linejoin' => true,

[BUG] Constants not renamed

When running the npx [email protected] --eightshiftBoilerplateBranch="release/5.0.0" command and setting up a new projects the src/Config.php file still has the original values for project name, prefix and env var name.

/**
	 * Method that returns project name.
	 *
	 * Generally used for naming assets handlers, languages, etc.
	 */
	public static function getProjectName(): string
	{
		return 'eightshift-libs';
	}

	/**
	 * Method that returns project version.
	 *
	 * Generally used for versioning asset handlers while enqueueing them.
	 */
	public static function getProjectVersion(): string
	{
		return '1.0.0';
	}

	/**
	 * Method that returns project prefix.
	 *
	 * The WordPress filters live in a global namespace, so we need to prefix them to avoid naming collisions.
	 *
	 * @return string Full path to asset.
	 */
	public static function getProjectPrefix(): string
	{
		return 'eb';
	}

	/**
	 * Returns the project environment variable descriptor.
	 *
	 * Used for defining global settings depending on the environment of the project.
	 * Can be one of, but not limited to, develop, staging, production.
	 *
	 * Defaults to 'develop' (as to not cache manifest in transient) if not otherwise
	 * defined in wp-config.php
	 *
	 * @return string Current project environment string.
	 */
	public static function getProjectEnv(): string
	{
		if (defined('EB_ENV')) {
			return EB_ENV;
		}

		return 'develop';
	}

[FEATURE] Add admin menu and submenu generation

A new CLI command should be added for creating admin menus and submenus. This is useful for plugins and can be abstracted into templates.

For reference check:

https://github.com/dingo-d/woo-solo-api/blob/develop/src/Admin/AdminMenus/AdminMenu.php

Note to self, the render method in the base admin should be changed a bit:

	/**
	 * Render the current view.
	 *
	 * @param array  $attributes Array of attributes passed to the view.
	 * @param string $innerBlockContent Not used here.
	 *
	 * @return string Rendered HTML.
	 * @throws Exception On missing attributes OR missing template.
	 */
	public function render(array $attributes = [], string $innerBlockContent = ''): string
	{
		try {
			return Components::render($this->getViewComponent(), $attributes);
		} catch (ComponentException $exception) { 
			// Don't let exceptions bubble up. Just render the exception message into the admin menu.
			return sprintf(
				'<pre>%s</pre>',
				$exception->getMessage()
			);
		}
	}

	/**
	 * Get the view component that will render correct view.
	 *
	 * @return string View component name.
	 */
	abstract protected function getViewComponent(): string;

[FEATURE] Allow assigning multiple post types on taxonomy registration

When registering a custom taxonomy by extending Base_Taxonomy class and implementing method get_post_type_slug, only thing that is possible is to return a string of post type slug. That value is passed as an argument to register_taxonomy by putting it in array. Because of that there is no way to assign taxonomy to multiple post types.
If we change the return type of get_post_type_slug method to array, this would be possible.

This was already implemented for Base_Post_Type_Columns class.

Remove force update from the setup script

The following snippet:

// Install core version.
if (!empty($core)) {
WP_CLI::runcommand("core update --version={$core} --force");
WP_CLI::log('--------------------------------------------------');
} else {

Will always overwrite the core update even if we don't need it to. For instance, if I want to use this command to deploy the changes to the staging setup, I don't need it to run if the version hasn't changed.

With --force argument, the WP would always reinstall on every deployment. Which is unnecessary.

Make project path more robust

If this is going to be used for themes/plugins maybe we should do something like

  /**
   * Get the possible locations for the view.
   *
   * @param string $uri URI of the view to get the locations for.
   *
   * @return array Array of possible locations.
   */
  protected function get_locations( string $path = '' ) : array {
    return [
      trailingslashit( \get_stylesheet_directory() ) . $path,
      trailingslashit( \get_template_directory() ) . $path,
      trailingslashit( __DIR__ ) . $path,
    ];
  }

And then in the consuming code do something like

foreach ( $this->get_locations( $path ) as $location ) {
  if ( is_readable( $location ) ) {
    return $location;
  }
}

This way we are covering multiple possibilities. Thoughts?

PHP lint command fails

In the new project, the linting that is run from the husky pre-commit hook seems to fail no matter from which context I call it

> @php ./vendor/squizlabs/php_codesniffer/bin/phpcs 'wp-content/themes/project/index.php'
Script @php ./vendor/squizlabs/php_codesniffer/bin/phpcs handling the standards:check event returned with error code 3
> @php ./vendor/squizlabs/php_codesniffer/bin/phpcs 'wp-content/themes/project/page.php'
Script @php ./vendor/squizlabs/php_codesniffer/bin/phpcs handling the standards:check event returned with error code 3
ERROR: The file "wp-content/themes/project/index.php" does not exist.

Run "phpcs --help" for usage information

ERROR: The file "wp-content/themes/project/page.php" does not exist.

Run "phpcs --help" for usage information


Error: Please fix all linting issues before continuing.

Something seems to be wrong with the way the files are passed to the PHPCS.

Constant name name must be statically referenced

I started to write unit tests (branch), and when I created a fake plugin, I noticed that the hook name used for plugins cannot be changed because it's referenced as self inside the method get_register_action_hook().

public function get_register_action_hook() : string {
return self::DEFAULT_REGISTER_ACTION_HOOK;
}

This means that it cannot be overridden in the plugin. It needs to be set to static so that we can use late static binding to change it in plugins.

I've fixed this in the testing branch (because I want my tests to pass).

Asset handle should be a public constant

$handle = "{$this->getAssetsPrefix()}-styles";

Sometimes, especially in plugins and places when we need to extend or reference it, like when we want to use wp_set_script_translations, we need to get the handle where we can hook into.

Currently, that's not possible. When extending the class I need to manually add this.

If this was a constant I could just reference it using self::JS_ADMIN_HANDLE or something like that. This applies to every enqueue class (theme and block).

[FEATURE] Simplify certain service classes

Some classes use abstract classes to be extended, but they have no real need to do so (no template methods). In this case, all the logic can be placed inside the example class that will be copied over to the project exactly.

AbstarctI18n -> I18nExample
AbstarctLogin -> LoginExample
AbstractMedia -> MediaExample
AbstractModifyAdminAppearance -> ModifyAdminAppearance

Add parameters to enqueue callback methods

None of the enqueue methods in hooks have attributes in them. Which means that we cannot use the $hook_suffix parameter to check where the script should or shouldn't load.

For instance, I may want to load the admin script only on a certain post, or admin screen, and then I'd use the hook suffix to identify the page and load the script.

You may say: but we are using dynamic imports so that's not important, but what when you need to localize a script and provide it only in one place - like on a specific screen?

We should add them.

Personally, I blame WP core for not using interfaces so that we were notified that we should implement those in the first place ๐Ÿ˜„

Make routes interfaces less granular

I kinda feel like this and the above interfaces are almost too granular. There is Callable_Field, Callable_Route, Registrable_Field, Registrable_Route and Route_Security.

Do you really need all of them?

In the plugin I made I ended up with just one Route interface with method definitions and Rest_Callable interface for the rest_callback.
Then I added a Base_Route abstract class for creating routes and left every class in charge of defining the implementation of the rest_callback and the get_callback_arguments method which may or may not include permission_callback because not all routes need one.

I'm not sure how the implementation would look in this case.

Add Features

  • Table columns
  • Custom meta fields
  • Template View with parameters
  • Page Templates
  • Admin Menu
  • Manifest.json controler

Improve post type columns slug method docs

This documentation should be improved. The method name is also a bit misleading and not self-documenting.

/**
* Get the slug of the post type where the additional column should appear.
*
* @return array The name of the post type.
*
* @since 2.0.5
*/
abstract protected function get_post_type_slug() : array;

The method name suggest that the return value will just be a string, but it is an array of one or many post types.

So it would be good to change the documentation since the method name change would most probably cause a backwards compatibility break.

  /**
   * Return an array of post type slugs for which the new column should be added to
   *
   * @return array Array containing the post type slugs.
   *
   * @since 2.0.5
   */
  abstract protected function get_post_type_slug() : array;

Ideally, the method should be named like: get_post_type_slugs.

The same goes for other abstract classes.

[BUG] Creating enqueue before creating config will error out

On a clean project, I tried adding admin enqueue class, but I forgot to add config first and I got errors because the config class was missing.

We should have a way to identify dependencies before adding a class and either add the option to use to automatically create the dependencies or just gracefully exit.

That will prevent any errors.

Register Custom Post Type Labels

Rethink registering custom post type labels:

This labler function / process could be simplified. I.E. you define the labels in a function and the parent's (Base_Post_Type) function does all the work.

final class Faq extends Base_Post_Type {

...

function get_labels() {
return [
'singular-uc' => esc_html_x( 'FAQ', 'post type upper case singular name', 'eightshift-libs' ),
'singular-lc' => esc_html_x( 'faq', 'post type lower case singular name', 'eightshift-libs' ),
'plural-uc' => esc_html_x( 'FAQs', 'post type upper case plural name', 'eightshift-libs' ),
'plural-lc' => esc_html_x( 'faqs', 'post type lower case plural name', 'eightshift-libs' )
];
}

...

}
@IvanGrginovInf
IvanGrginovInf 18 minutes ago
Edit: First I thought about putting it in a const but then you can't have translation. This example above doesn't really simplify it all that much. Still the 'labels' => ( new Label_Generator() )->get_generated_labels( $nouns ), line is bothering me a bit.

[BUG] Service example command doesn't change service name

When I typed wp boilerplate create_service_example --folder=post --file_name=Excerpt the name of the class and all the comments were still ServiceExample.

Besides that, since we are using PSR-4 autoloading, maybe we should automatically uppercase the folder name. In the above case, the folder created inside my src folder was post and it should be Post. The same could be made with class name - make it automatically CamelCased.

[FEATURE] CI/CD setup

In one of our projects, I tried setting up the CI/CD pipeline using the new Build.php file. This, however, failed.

The following is a process that we should implement in our projects so that the CI/CD pipeline will work.

Existing issue

The main problem with the script at the moment is that it expects the WP_CLI class to be present when the script is executed. This will only be true if the wp-cli package has been installed using Composer. This would require an intermediary step and a modification of the Build.php script.

A solution could be to have a simple composer.json present where we'd have this dependency set up as a requirement, alongside any constraints (such as PHP versions) and autoloading.

Then we could just load the autoloader in the Build.php script and all the WP_CLI commands would run.

This does add an additional setup step that the CI server should run composer install from the bin folder before executing the Build.php script.

Missing CD part and incomplete CI part

At the moment, we only have a partial CI part done. We only install the project dependencies and that's it. The CI (continuous integration) step usually implies the running of certain code checks.

Since we cannot rely on GH actions for private repositories (those have to be paid), we then need to set up checks on the CI server. Ideally from the Check.php script.

This script will run after the Build.php one, and will execute all the lint scripts that we are using (eslint, stylelint, phpcs and phpstan).

Also, the Build.php script needs to run a full composer install --no-progress command (we are not interested in the progress output) in the project repo, so that we can then run the linters in the Check.php script.

The Check.php script should then autoload the correct packages in order to run the linters one by one.

Deploy script

The Deploy.php script can look similar to Build.php (will need the autoloader like Build.php), but the packages installed in this step must be installed for the production only.

For the JS packages that would be

  1. npm install - Need to install the packages
  2. npm run build - Need to bundle the assets

For PHP that would be

  1. composer install --no-ansi --no-dev --no-interaction --no-progress --no-scripts --optimize-autoloader
  2. WP_CLI::runcommand('boilerplate update');
  3. Deploy with the exclusions either from the ci-exclude.txt or from the .gitattributes and .gitignore files.

In this step, we wouldn't run the linters, as that step is done in the Build part of the CI/CD pipeline.

[BUG] Error while running init_config_project command

While running the wp boilerplate init_config_project command without any flags it will throw an error Parameter errors: missing --env parameter (Define project env variable name.).

As we discussed in the office, this will be removed and replaced with the WordPress core environments that they introduced in version 5.5.0 using the wp_get_environment_type() function (link)

Add .gitattributes

Currently, a lot of files will be pulled when you do a composer install which shouldn't be in the vendor folder - test folder .github folder etc.

See this for reference.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.